http://www.coreboot.org/api.php?action=feedcontributions&user=Stepan&feedformat=atomcoreboot - User contributions [en]2015-03-03T22:58:41ZUser contributionsMediaWiki 1.24.1http://www.coreboot.org/index.php?title=Flashmap&diff=15589Flashmap2015-02-12T00:15:14Z<p>Stepan: /* How do we fix it (the solution being pursued) */</p>
<hr />
<div>''or...''<br />
=Toward a unified representation for the layout of coreboot flash images=<br />
'''N.B.''' The changes described herein are being made as part of the Chromium OS project; as such, they will initially be committed to the project's own fork of the main coreboot repository, which is available at [https://chromium.googlesource.com/chromiumos/third_party/coreboot https://chromium.googlesource.com/chromiumos/third_party/coreboot]. Unless otherwise noted, the paths and processes described throughout this page are as they exist(ed) in a checkout of the master branch of the Chromium OS sources as they appeared at the beginning of 2015. One of the guiding design principles is to keep the tools general enough that they will be helpful to others, and the resulting work will be upstreamed to the main repository once it has been regression-tested in the context of Chromium OS hardware.<br />
<br />
==How it's currently done (how the Chromium OS project presently constructs firmware images)==<br />
Most Intel-based Chromium OS devices currently use an 8 MB firmware image that includes---among other things---the Intel ME firmware, a copy of coreboot including the ramstage and depthcharge (bootloader) payload, two additional copies of the ramstage and bootloader payload, and a separate SeaBIOS payload. The primary description of this format exists in board-specific flattened device tree files, which are used by a script called [https://chromium.googlesource.com/chromiumos/platform/dev-util/+/master/host/cros_bundle_firmware cros_bundle_firmware] to modify the image produced by the coreboot build system. For instance, the layout of the Panther board's firmware exists at [https://chromium.googlesource.com/chromiumos/platform/depthcharge/+/master/board/panther/fmap.dts https://chromium.googlesource.com/chromiumos/platform/depthcharge/+/master/board/panther/fmap.dts], and results in a final image that looks like this:<br />
{| class=&quot;wikitable&quot;<br />
! Section<br />
! Offset<br />
! Contents<br />
! Original source<br />
! Packaging procedure<br />
! Coreboot Kconfig entr[yi](es)<br />
|-<br />
| rowspan=&quot;8&quot; | RO<br />
|-<br />
| 0x700000<br />
| Boot (coreboot image)<br />
| coreboot.rom (coreboot build system)<br />
| cros_bundle_firmware helper [https://chromium.googlesource.com/chromiumos/platform/dev-util/+/master/host/lib/bundle_firmware.py#967 adds] depthcharge.payload and [https://chromium.googlesource.com/chromiumos/platform/dev-util/+/master/host/lib/fdt.py#693 compiled] (then [https://chromium.googlesource.com/chromiumos/platform/dev-util/+/master/host/lib/bundle_firmware.py#1072 mod] [https://chromium.googlesource.com/chromiumos/platform/dev-util/+/master/host/cros_bundle_firmware#96 ified]) version of fmap.dts to the existing CBFS<br />
| &lt;code&gt;CONFIG_CMOS_POST_OFFSET&lt;/code&gt;, &lt;code&gt;CONFIG_CBFS_SIZE&lt;/code&gt;<br />
|-<br />
| 0x611000<br />
| GBB (Google Binary Block)<br />
| chromeos-config section of fmap.dts<br />
| cros_bundle_firmware [https://chromium.googlesource.com/chromiumos/platform/dev-util/+/master/host/lib/bundle_firmware.py#389 generates] and inserts it<br />
|-<br />
| 0x610840<br />
| (Reserved)<br />
|-<br />
| 0x610800<br />
| FWID (Firmware ID)<br />
|-<br />
| 0x610000<br />
| FMAP (Flash MAP)<br />
|-<br />
| 0x604000<br />
| (Reserved)<br />
|-<br />
| 0x600000<br />
| RO-VPD (Vital Product Data)<br />
|-<br />
| rowspan=&quot;4&quot; |<br />
|-<br />
| 0x400000<br />
| Legacy (SeaBIOS image)<br />
|-<br />
| 0x3fa000<br />
| (Reserved)<br />
|-<br />
| 0x3f8000<br />
| RW-VPD (Vital Product Data)<br />
|-<br />
| rowspan=&quot;3&quot; | RW-shared<br />
|-<br />
| 0x3f6000<br />
| Vblock-dev (third-party kernel signing keys)<br />
|-<br />
| 0x3f4000<br />
| Shared-data (RW firmware calibration data)<br />
|-<br />
| rowspan=&quot;3&quot; |<br />
|-<br />
| 0x3f0000<br />
| ELOG (Event LOG)<br />
|-<br />
| 0x3e0000<br />
| MRC-cache (Memory Reference Code training data)<br />
|-<br />
| rowspan=&quot;4&quot; | RW-B<br />
|-<br />
| 0x3dffc0<br />
| FWID-B<br />
|-<br />
| 0x300000<br />
| Main-B (copy of coreboot ramstage and payload)<br />
|-<br />
| 0x2f0000<br />
| Vblock-B (signing keys)<br />
|-<br />
| rowspan=&quot;4&quot; | RW-A<br />
|-<br />
| 0x2effc0<br />
| FWID-A<br />
|-<br />
| 0x210000<br />
| Main-A (copy of coreboot ramstage and payload)<br />
|-<br />
| 0x200000<br />
| Vblock-A (signing keys)<br />
|-<br />
| rowspan=&quot;3&quot; | FW-descriptor<br />
|-<br />
| 0x001000<br />
| ME (Intel Management Engine firmware blob)<br />
|-<br />
| 0x000000<br />
| FD (Intel Firmware Descriptor header)<br />
|}<br />
<br />
==What's so bad about that (the pitfalls of this build model that we hope to solve)==<br />
<br />
==Why you should care (how this pertains to all coreboot users)==<br />
<br />
==How do we fix it (the solution being pursued)==</div>Stepanhttp://www.coreboot.org/index.php?title=Code_of_Conduct&diff=15496Code of Conduct2015-01-20T22:17:07Z<p>Stepan: /* Consequences of Unacceptable Behavior */</p>
<hr />
<div>This code of conduct outlines our rules and expectations for everybody participating in the coreboot community.<br />
<br />
<br />
= Mailing list and chat etiquette =<br />
<br />
We have a friendly and productive atmosphere on our mailing lists, development / code review tools and IRC chat rooms. Our principles evolve around the following:<br />
<br />
* It's not the user's fault if something goes wrong.<br />
* Attempt collaboration before conflict.<br />
* People who intentionally insult others (users, developers, corporations, other projects, or the coreboot project itself) will be dealt with. See policy below.<br />
* We are dealing with hardware with lots of undocumented pitfalls. It is quite possible that you did everything right, but coreboot or its tools still won’t work for you.<br />
<br />
Refrain from insulting anyone or the group they belong to. Remember that people might be sensitive to other things than you are.<br />
<br />
Most of our community members are not native English speakers, thus misunderstandings can (and do) happen. Always assume that others are friendly and may have picked less-than-stellar wording by accident.<br />
<br />
If you feel that you have been treated unfairly, we want to hear about it so we can handle the situation. Please contact our arbitration team directly: They will listen to you. If you don't get a response within a few days, your mail was probably lost. Please resend your mail to another member of the arbitration team in that case.<br />
<br />
<br />
= Unacceptable Behavior =<br />
<br />
Unacceptable behaviors include: intimidating, harassing, abusive, discriminatory, derogatory or demeaning speech or actions by any participant in our community online, at all related events and in one-on-one communications carried out in the context of community business. Community event venues may be shared with members of the public; please be respectful to all patrons of these locations.<br />
<br />
Examples of behaviors we do not accept in our community: <br />
<br />
* harmful or prejudicial verbal or written comments related to gender, sexual orientation, race, religion, disability;<br />
* inappropriate use of nudity and/or sexual images in public spaces (including presentation slides);<br />
* deliberate intimidation, stalking or following;<br />
* harassing photography or recording;<br />
* sustained disruption of talks or other events;<br />
* inappropriate physical contact, and unwelcome sexual attention.<br />
<br />
Check your motives: Using this code of conduct aggressively against other people in the community might also be harassment. Behave.<br />
<br />
= Consequences of Unacceptable Behavior =<br />
<br />
Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated.<br />
<br />
Anyone asked to stop unacceptable behavior is expected to comply immediately.<br />
<br />
If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event). Community organizers can be part of the arbitration team, or organizers of events and online communities.<br />
<br />
= If You Witness or Are Subject to Unacceptable Behavior =<br />
<br />
If you are subject to or witness unacceptable behavior, or have any other concerns, please notify someone from the arbitration team immediately.<br />
<br />
<br />
= Addressing Grievances =<br />
<br />
If you feel you have been falsely or unfairly accused of violating this Code of Conduct, you should notify the arbitration team with a concise description of your grievance.<br />
<br />
<br />
= Scope =<br />
<br />
We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues—online and in-person—as well as in all one-on-one communications pertaining to community business.<br />
<br />
<br />
= Contact info =<br />
<br />
Our arbitration team consists of the following people<br />
* Marc Jones &lt;mjones@coreboot.org&gt;<br />
* Patrick Georgi &lt;patrick@coreboot.org&gt;<br />
* Ronald Minnich &lt;rminnich@coreboot.org&gt;<br />
* Stefan Reinauer &lt;stefan.reinauer@coreboot.org&gt;<br />
<br />
<br />
= License and attribution =<br />
<br />
This Code of Conduct is distributed under a Creative Commons Attribution-ShareAlike license. It is based on http://citizencodeofconduct.org/</div>Stepanhttp://www.coreboot.org/index.php?title=Code_of_Conduct&diff=15495Code of Conduct2015-01-20T22:13:24Z<p>Stepan: /* Unacceptable Behavior */</p>
<hr />
<div>This code of conduct outlines our rules and expectations for everybody participating in the coreboot community.<br />
<br />
<br />
= Mailing list and chat etiquette =<br />
<br />
We have a friendly and productive atmosphere on our mailing lists, development / code review tools and IRC chat rooms. Our principles evolve around the following:<br />
<br />
* It's not the user's fault if something goes wrong.<br />
* Attempt collaboration before conflict.<br />
* People who intentionally insult others (users, developers, corporations, other projects, or the coreboot project itself) will be dealt with. See policy below.<br />
* We are dealing with hardware with lots of undocumented pitfalls. It is quite possible that you did everything right, but coreboot or its tools still won’t work for you.<br />
<br />
Refrain from insulting anyone or the group they belong to. Remember that people might be sensitive to other things than you are.<br />
<br />
Most of our community members are not native English speakers, thus misunderstandings can (and do) happen. Always assume that others are friendly and may have picked less-than-stellar wording by accident.<br />
<br />
If you feel that you have been treated unfairly, we want to hear about it so we can handle the situation. Please contact our arbitration team directly: They will listen to you. If you don't get a response within a few days, your mail was probably lost. Please resend your mail to another member of the arbitration team in that case.<br />
<br />
<br />
= Unacceptable Behavior =<br />
<br />
Unacceptable behaviors include: intimidating, harassing, abusive, discriminatory, derogatory or demeaning speech or actions by any participant in our community online, at all related events and in one-on-one communications carried out in the context of community business. Community event venues may be shared with members of the public; please be respectful to all patrons of these locations.<br />
<br />
Examples of behaviors we do not accept in our community: <br />
<br />
* harmful or prejudicial verbal or written comments related to gender, sexual orientation, race, religion, disability;<br />
* inappropriate use of nudity and/or sexual images in public spaces (including presentation slides);<br />
* deliberate intimidation, stalking or following;<br />
* harassing photography or recording;<br />
* sustained disruption of talks or other events;<br />
* inappropriate physical contact, and unwelcome sexual attention.<br />
<br />
Check your motives: Using this code of conduct aggressively against other people in the community might also be harassment. Behave.<br />
<br />
= Consequences of Unacceptable Behavior =<br />
<br />
Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated.<br />
<br />
Anyone asked to stop unacceptable behavior is expected to comply immediately.<br />
<br />
If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event).<br />
<br />
<br />
= If You Witness or Are Subject to Unacceptable Behavior =<br />
<br />
If you are subject to or witness unacceptable behavior, or have any other concerns, please notify someone from the arbitration team immediately.<br />
<br />
<br />
= Addressing Grievances =<br />
<br />
If you feel you have been falsely or unfairly accused of violating this Code of Conduct, you should notify the arbitration team with a concise description of your grievance.<br />
<br />
<br />
= Scope =<br />
<br />
We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues—online and in-person—as well as in all one-on-one communications pertaining to community business.<br />
<br />
<br />
= Contact info =<br />
<br />
Our arbitration team consists of the following people<br />
* Marc Jones &lt;mjones@coreboot.org&gt;<br />
* Patrick Georgi &lt;patrick@coreboot.org&gt;<br />
* Ronald Minnich &lt;rminnich@coreboot.org&gt;<br />
* Stefan Reinauer &lt;stefan.reinauer@coreboot.org&gt;<br />
<br />
<br />
= License and attribution =<br />
<br />
This Code of Conduct is distributed under a Creative Commons Attribution-ShareAlike license. It is based on http://citizencodeofconduct.org/</div>Stepanhttp://www.coreboot.org/index.php?title=Code_of_Conduct&diff=15113Code of Conduct2015-01-09T00:39:49Z<p>Stepan: Protected &quot;Code of Conduct&quot; ([Edit=Allow only administrators] (indefinite) [Move=Allow only administrators] (indefinite))</p>
<hr />
<div>This code of conduct outlines our rules and expectations for everybody participating in the coreboot community.<br />
<br />
<br />
= Mailing list and chat etiquette =<br />
<br />
We have a friendly and productive atmosphere on our mailing lists, development / code review tools and IRC chat rooms. Our principles evolve around the following:<br />
<br />
* It's not the user's fault if something goes wrong.<br />
* Attempt collaboration before conflict.<br />
* People who intentionally insult others (users, developers, corporations, other projects, or the coreboot project itself) will be dealt with. See policy below.<br />
* We are dealing with hardware with lots of undocumented pitfalls. It is quite possible that you did everything right, but coreboot or its tools still won’t work for you.<br />
<br />
Refrain from insulting anyone or the group they belong to. Remember that people might be sensitive to other things than you are.<br />
<br />
Most of our community members are not native English speakers, thus misunderstandings can (and do) happen. Always assume that others are friendly and may have picked less-than-stellar wording by accident.<br />
<br />
If you feel that you have been treated unfairly, we want to hear about it so we can handle the situation. Please contact our arbitration team directly: They will listen to you. If you don't get a response within a few days, your mail was probably lost. Please resend your mail to another member of the arbitration team in that case.<br />
<br />
<br />
= Unacceptable Behavior =<br />
<br />
Unacceptable behaviors include: intimidating, harassing, abusive, discriminatory, derogatory or demeaning speech or actions by any participant in our community online, at all related events and in one-on-one communications carried out in the context of community business. Community event venues may be shared with members of the public; please be respectful to all patrons of these locations.<br />
<br />
Harassment includes: harmful or prejudicial verbal or written comments related to gender, sexual orientation, race, religion, disability; inappropriate use of nudity and/or sexual images in public spaces (including presentation slides); deliberate intimidation, stalking or following; harassing photography or recording; sustained disruption of talks or other events; inappropriate physical contact, and unwelcome sexual attention.<br />
<br />
Check your motives: Using this code of conduct aggressively against other people in the community might also be harassment. Behave.<br />
<br />
<br />
= Consequences of Unacceptable Behavior =<br />
<br />
Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated.<br />
<br />
Anyone asked to stop unacceptable behavior is expected to comply immediately.<br />
<br />
If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event).<br />
<br />
<br />
= If You Witness or Are Subject to Unacceptable Behavior =<br />
<br />
If you are subject to or witness unacceptable behavior, or have any other concerns, please notify someone from the arbitration team immediately.<br />
<br />
<br />
= Addressing Grievances =<br />
<br />
If you feel you have been falsely or unfairly accused of violating this Code of Conduct, you should notify the arbitration team with a concise description of your grievance.<br />
<br />
<br />
= Scope =<br />
<br />
We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues—online and in-person—as well as in all one-on-one communications pertaining to community business.<br />
<br />
<br />
= Contact info =<br />
<br />
Our arbitration team consists of the following people<br />
* Marc Jones &lt;mjones@coreboot.org&gt;<br />
* Patrick Georgi &lt;patrick@coreboot.org&gt;<br />
* Ronald Minnich &lt;rminnich@coreboot.org&gt;<br />
* Stefan Reinauer &lt;stefan.reinauer@coreboot.org&gt;<br />
<br />
<br />
= License and attribution =<br />
<br />
This Code of Conduct is distributed under a Creative Commons Attribution-ShareAlike license.</div>Stepanhttp://www.coreboot.org/index.php?title=Code_of_Conduct&diff=15112Code of Conduct2015-01-09T00:38:37Z<p>Stepan: </p>
<hr />
<div>This code of conduct outlines our rules and expectations for everybody participating in the coreboot community.<br />
<br />
<br />
= Mailing list and chat etiquette =<br />
<br />
We have a friendly and productive atmosphere on our mailing lists, development / code review tools and IRC chat rooms. Our principles evolve around the following:<br />
<br />
* It's not the user's fault if something goes wrong.<br />
* Attempt collaboration before conflict.<br />
* People who intentionally insult others (users, developers, corporations, other projects, or the coreboot project itself) will be dealt with. See policy below.<br />
* We are dealing with hardware with lots of undocumented pitfalls. It is quite possible that you did everything right, but coreboot or its tools still won’t work for you.<br />
<br />
Refrain from insulting anyone or the group they belong to. Remember that people might be sensitive to other things than you are.<br />
<br />
Most of our community members are not native English speakers, thus misunderstandings can (and do) happen. Always assume that others are friendly and may have picked less-than-stellar wording by accident.<br />
<br />
If you feel that you have been treated unfairly, we want to hear about it so we can handle the situation. Please contact our arbitration team directly: They will listen to you. If you don't get a response within a few days, your mail was probably lost. Please resend your mail to another member of the arbitration team in that case.<br />
<br />
<br />
= Unacceptable Behavior =<br />
<br />
Unacceptable behaviors include: intimidating, harassing, abusive, discriminatory, derogatory or demeaning speech or actions by any participant in our community online, at all related events and in one-on-one communications carried out in the context of community business. Community event venues may be shared with members of the public; please be respectful to all patrons of these locations.<br />
<br />
Harassment includes: harmful or prejudicial verbal or written comments related to gender, sexual orientation, race, religion, disability; inappropriate use of nudity and/or sexual images in public spaces (including presentation slides); deliberate intimidation, stalking or following; harassing photography or recording; sustained disruption of talks or other events; inappropriate physical contact, and unwelcome sexual attention.<br />
<br />
Check your motives: Using this code of conduct aggressively against other people in the community might also be harassment. Behave.<br />
<br />
<br />
= Consequences of Unacceptable Behavior =<br />
<br />
Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated.<br />
<br />
Anyone asked to stop unacceptable behavior is expected to comply immediately.<br />
<br />
If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event).<br />
<br />
<br />
= If You Witness or Are Subject to Unacceptable Behavior =<br />
<br />
If you are subject to or witness unacceptable behavior, or have any other concerns, please notify someone from the arbitration team immediately.<br />
<br />
<br />
= Addressing Grievances =<br />
<br />
If you feel you have been falsely or unfairly accused of violating this Code of Conduct, you should notify the arbitration team with a concise description of your grievance.<br />
<br />
<br />
= Scope =<br />
<br />
We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues—online and in-person—as well as in all one-on-one communications pertaining to community business.<br />
<br />
<br />
= Contact info =<br />
<br />
Our arbitration team consists of the following people<br />
* Marc Jones &lt;mjones@coreboot.org&gt;<br />
* Patrick Georgi &lt;patrick@coreboot.org&gt;<br />
* Ronald Minnich &lt;rminnich@coreboot.org&gt;<br />
* Stefan Reinauer &lt;stefan.reinauer@coreboot.org&gt;<br />
<br />
<br />
= License and attribution =<br />
<br />
This Code of Conduct is distributed under a Creative Commons Attribution-ShareAlike license.</div>Stepanhttp://www.coreboot.org/index.php?title=Code_of_Conduct&diff=15111Code of Conduct2015-01-09T00:37:41Z<p>Stepan: /* If You Witness or Are Subject to Unacceptable Behavior */</p>
<hr />
<div>Coreboot Code of Conduct<br />
<br />
<br />
This code of conduct outlines our rules and expectations for everybody participating in the coreboot community.<br />
<br />
<br />
= Mailing list and chat etiquette =<br />
<br />
We have a friendly and productive atmosphere on our mailing lists, development / code review tools and IRC chat rooms. Our principles evolve around the following:<br />
<br />
* It's not the user's fault if something goes wrong.<br />
* Attempt collaboration before conflict.<br />
* People who intentionally insult others (users, developers, corporations, other projects, or the coreboot project itself) will be dealt with. See policy below.<br />
* We are dealing with hardware with lots of undocumented pitfalls. It is quite possible that you did everything right, but coreboot or its tools still won’t work for you.<br />
<br />
Refrain from insulting anyone or the group they belong to. Remember that people might be sensitive to other things than you are.<br />
<br />
Most of our community members are not native English speakers, thus misunderstandings can (and do) happen. Always assume that others are friendly and may have picked less-than-stellar wording by accident.<br />
<br />
If you feel that you have been treated unfairly, we want to hear about it so we can handle the situation. Please contact our arbitration team directly: They will listen to you. If you don't get a response within a few days, your mail was probably lost. Please resend your mail to another member of the arbitration team in that case.<br />
<br />
= Unacceptable Behavior =<br />
Unacceptable behaviors include: intimidating, harassing, abusive, discriminatory, derogatory or demeaning speech or actions by any participant in our community online, at all related events and in one-on-one communications carried out in the context of community business. Community event venues may be shared with members of the public; please be respectful to all patrons of these locations.<br />
<br />
Harassment includes: harmful or prejudicial verbal or written comments related to gender, sexual orientation, race, religion, disability; inappropriate use of nudity and/or sexual images in public spaces (including presentation slides); deliberate intimidation, stalking or following; harassing photography or recording; sustained disruption of talks or other events; inappropriate physical contact, and unwelcome sexual attention.<br />
<br />
Check your motives: Using this code of conduct aggressively against other people in the community might also be harassment. Behave.<br />
<br />
= Consequences of Unacceptable Behavior =<br />
<br />
Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated.<br />
<br />
Anyone asked to stop unacceptable behavior is expected to comply immediately.<br />
<br />
If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event).<br />
<br />
= If You Witness or Are Subject to Unacceptable Behavior =<br />
<br />
If you are subject to or witness unacceptable behavior, or have any other concerns, please notify someone from the arbitration team immediately.<br />
<br />
= Addressing Grievances =<br />
If you feel you have been falsely or unfairly accused of violating this Code of Conduct, you should notify the arbitration team with a concise description of your grievance.<br />
<br />
<br />
= Scope =<br />
We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues—online and in-person—as well as in all one-on-one communications pertaining to community business.<br />
<br />
= Contact info =<br />
<br />
Our arbitration team consists of the following people<br />
* Marc Jones &lt;mjones@coreboot.org&gt;<br />
* Patrick Georgi &lt;patrick@coreboot.org&gt;<br />
* Ronald Minnich &lt;rminnich@coreboot.org&gt;<br />
* Stefan Reinauer &lt;stefan.reinauer@coreboot.org&gt;<br />
<br />
<br />
= License and attribution =<br />
This Code of Conduct is distributed under a Creative Commons Attribution-ShareAlike license.</div>Stepanhttp://www.coreboot.org/index.php?title=Code_of_Conduct&diff=15110Code of Conduct2015-01-09T00:37:25Z<p>Stepan: /* Consequences of Unacceptable Behavior */</p>
<hr />
<div>Coreboot Code of Conduct<br />
<br />
<br />
This code of conduct outlines our rules and expectations for everybody participating in the coreboot community.<br />
<br />
<br />
= Mailing list and chat etiquette =<br />
<br />
We have a friendly and productive atmosphere on our mailing lists, development / code review tools and IRC chat rooms. Our principles evolve around the following:<br />
<br />
* It's not the user's fault if something goes wrong.<br />
* Attempt collaboration before conflict.<br />
* People who intentionally insult others (users, developers, corporations, other projects, or the coreboot project itself) will be dealt with. See policy below.<br />
* We are dealing with hardware with lots of undocumented pitfalls. It is quite possible that you did everything right, but coreboot or its tools still won’t work for you.<br />
<br />
Refrain from insulting anyone or the group they belong to. Remember that people might be sensitive to other things than you are.<br />
<br />
Most of our community members are not native English speakers, thus misunderstandings can (and do) happen. Always assume that others are friendly and may have picked less-than-stellar wording by accident.<br />
<br />
If you feel that you have been treated unfairly, we want to hear about it so we can handle the situation. Please contact our arbitration team directly: They will listen to you. If you don't get a response within a few days, your mail was probably lost. Please resend your mail to another member of the arbitration team in that case.<br />
<br />
= Unacceptable Behavior =<br />
Unacceptable behaviors include: intimidating, harassing, abusive, discriminatory, derogatory or demeaning speech or actions by any participant in our community online, at all related events and in one-on-one communications carried out in the context of community business. Community event venues may be shared with members of the public; please be respectful to all patrons of these locations.<br />
<br />
Harassment includes: harmful or prejudicial verbal or written comments related to gender, sexual orientation, race, religion, disability; inappropriate use of nudity and/or sexual images in public spaces (including presentation slides); deliberate intimidation, stalking or following; harassing photography or recording; sustained disruption of talks or other events; inappropriate physical contact, and unwelcome sexual attention.<br />
<br />
Check your motives: Using this code of conduct aggressively against other people in the community might also be harassment. Behave.<br />
<br />
= Consequences of Unacceptable Behavior =<br />
<br />
Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated.<br />
<br />
Anyone asked to stop unacceptable behavior is expected to comply immediately.<br />
<br />
If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event).<br />
<br />
= If You Witness or Are Subject to Unacceptable Behavior =<br />
If you are subject to or witness unacceptable behavior, or have any other concerns, please notify someone from the arbitration team immediately.<br />
<br />
<br />
= Addressing Grievances =<br />
If you feel you have been falsely or unfairly accused of violating this Code of Conduct, you should notify the arbitration team with a concise description of your grievance.<br />
<br />
<br />
= Scope =<br />
We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues—online and in-person—as well as in all one-on-one communications pertaining to community business.<br />
<br />
= Contact info =<br />
<br />
Our arbitration team consists of the following people<br />
* Marc Jones &lt;mjones@coreboot.org&gt;<br />
* Patrick Georgi &lt;patrick@coreboot.org&gt;<br />
* Ronald Minnich &lt;rminnich@coreboot.org&gt;<br />
* Stefan Reinauer &lt;stefan.reinauer@coreboot.org&gt;<br />
<br />
<br />
= License and attribution =<br />
This Code of Conduct is distributed under a Creative Commons Attribution-ShareAlike license.</div>Stepanhttp://www.coreboot.org/index.php?title=Code_of_Conduct&diff=15109Code of Conduct2015-01-09T00:36:55Z<p>Stepan: /* Unacceptable Behavior */</p>
<hr />
<div>Coreboot Code of Conduct<br />
<br />
<br />
This code of conduct outlines our rules and expectations for everybody participating in the coreboot community.<br />
<br />
<br />
= Mailing list and chat etiquette =<br />
<br />
We have a friendly and productive atmosphere on our mailing lists, development / code review tools and IRC chat rooms. Our principles evolve around the following:<br />
<br />
* It's not the user's fault if something goes wrong.<br />
* Attempt collaboration before conflict.<br />
* People who intentionally insult others (users, developers, corporations, other projects, or the coreboot project itself) will be dealt with. See policy below.<br />
* We are dealing with hardware with lots of undocumented pitfalls. It is quite possible that you did everything right, but coreboot or its tools still won’t work for you.<br />
<br />
Refrain from insulting anyone or the group they belong to. Remember that people might be sensitive to other things than you are.<br />
<br />
Most of our community members are not native English speakers, thus misunderstandings can (and do) happen. Always assume that others are friendly and may have picked less-than-stellar wording by accident.<br />
<br />
If you feel that you have been treated unfairly, we want to hear about it so we can handle the situation. Please contact our arbitration team directly: They will listen to you. If you don't get a response within a few days, your mail was probably lost. Please resend your mail to another member of the arbitration team in that case.<br />
<br />
= Unacceptable Behavior =<br />
Unacceptable behaviors include: intimidating, harassing, abusive, discriminatory, derogatory or demeaning speech or actions by any participant in our community online, at all related events and in one-on-one communications carried out in the context of community business. Community event venues may be shared with members of the public; please be respectful to all patrons of these locations.<br />
<br />
Harassment includes: harmful or prejudicial verbal or written comments related to gender, sexual orientation, race, religion, disability; inappropriate use of nudity and/or sexual images in public spaces (including presentation slides); deliberate intimidation, stalking or following; harassing photography or recording; sustained disruption of talks or other events; inappropriate physical contact, and unwelcome sexual attention.<br />
<br />
Check your motives: Using this code of conduct aggressively against other people in the community might also be harassment. Behave.<br />
<br />
= Consequences of Unacceptable Behavior =<br />
Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated.<br />
Anyone asked to stop unacceptable behavior is expected to comply immediately.<br />
If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event).<br />
<br />
= If You Witness or Are Subject to Unacceptable Behavior =<br />
If you are subject to or witness unacceptable behavior, or have any other concerns, please notify someone from the arbitration team immediately.<br />
<br />
<br />
= Addressing Grievances =<br />
If you feel you have been falsely or unfairly accused of violating this Code of Conduct, you should notify the arbitration team with a concise description of your grievance.<br />
<br />
<br />
= Scope =<br />
We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues—online and in-person—as well as in all one-on-one communications pertaining to community business.<br />
<br />
= Contact info =<br />
<br />
Our arbitration team consists of the following people<br />
* Marc Jones &lt;mjones@coreboot.org&gt;<br />
* Patrick Georgi &lt;patrick@coreboot.org&gt;<br />
* Ronald Minnich &lt;rminnich@coreboot.org&gt;<br />
* Stefan Reinauer &lt;stefan.reinauer@coreboot.org&gt;<br />
<br />
<br />
= License and attribution =<br />
This Code of Conduct is distributed under a Creative Commons Attribution-ShareAlike license.</div>Stepanhttp://www.coreboot.org/index.php?title=Code_of_Conduct&diff=15108Code of Conduct2015-01-09T00:36:17Z<p>Stepan: /* Mailing list and chat etiquette */</p>
<hr />
<div>Coreboot Code of Conduct<br />
<br />
<br />
This code of conduct outlines our rules and expectations for everybody participating in the coreboot community.<br />
<br />
<br />
= Mailing list and chat etiquette =<br />
<br />
We have a friendly and productive atmosphere on our mailing lists, development / code review tools and IRC chat rooms. Our principles evolve around the following:<br />
<br />
* It's not the user's fault if something goes wrong.<br />
* Attempt collaboration before conflict.<br />
* People who intentionally insult others (users, developers, corporations, other projects, or the coreboot project itself) will be dealt with. See policy below.<br />
* We are dealing with hardware with lots of undocumented pitfalls. It is quite possible that you did everything right, but coreboot or its tools still won’t work for you.<br />
<br />
Refrain from insulting anyone or the group they belong to. Remember that people might be sensitive to other things than you are.<br />
<br />
Most of our community members are not native English speakers, thus misunderstandings can (and do) happen. Always assume that others are friendly and may have picked less-than-stellar wording by accident.<br />
<br />
If you feel that you have been treated unfairly, we want to hear about it so we can handle the situation. Please contact our arbitration team directly: They will listen to you. If you don't get a response within a few days, your mail was probably lost. Please resend your mail to another member of the arbitration team in that case.<br />
<br />
= Unacceptable Behavior =<br />
Unacceptable behaviors include: intimidating, harassing, abusive, discriminatory, derogatory or demeaning speech or actions by any participant in our community online, at all related events and in one-on-one communications carried out in the context of community business. Community event venues may be shared with members of the public; please be respectful to all patrons of these locations.<br />
Harassment includes: harmful or prejudicial verbal or written comments related to gender, sexual orientation, race, religion, disability; inappropriate use of nudity and/or sexual images in public spaces (including presentation slides); deliberate intimidation, stalking or following; harassing photography or recording; sustained disruption of talks or other events; inappropriate physical contact, and unwelcome sexual attention.<br />
<br />
Check your motives: Using this code of conduct aggressively against other people in the community might also be harassment. Behave.<br />
<br />
= Consequences of Unacceptable Behavior =<br />
Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated.<br />
Anyone asked to stop unacceptable behavior is expected to comply immediately.<br />
If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event).<br />
<br />
= If You Witness or Are Subject to Unacceptable Behavior =<br />
If you are subject to or witness unacceptable behavior, or have any other concerns, please notify someone from the arbitration team immediately.<br />
<br />
<br />
= Addressing Grievances =<br />
If you feel you have been falsely or unfairly accused of violating this Code of Conduct, you should notify the arbitration team with a concise description of your grievance.<br />
<br />
<br />
= Scope =<br />
We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues—online and in-person—as well as in all one-on-one communications pertaining to community business.<br />
<br />
= Contact info =<br />
<br />
Our arbitration team consists of the following people<br />
* Marc Jones &lt;mjones@coreboot.org&gt;<br />
* Patrick Georgi &lt;patrick@coreboot.org&gt;<br />
* Ronald Minnich &lt;rminnich@coreboot.org&gt;<br />
* Stefan Reinauer &lt;stefan.reinauer@coreboot.org&gt;<br />
<br />
<br />
= License and attribution =<br />
This Code of Conduct is distributed under a Creative Commons Attribution-ShareAlike license.</div>Stepanhttp://www.coreboot.org/index.php?title=Code_of_Conduct&diff=15107Code of Conduct2015-01-09T00:35:36Z<p>Stepan: /* Mailing list and chat etiquette */</p>
<hr />
<div>Coreboot Code of Conduct<br />
<br />
<br />
This code of conduct outlines our rules and expectations for everybody participating in the coreboot community.<br />
<br />
<br />
= Mailing list and chat etiquette =<br />
<br />
We have a friendly and productive atmosphere on our mailing lists, development / code review tools and IRC chat rooms. Our principles evolve around the following:<br />
<br />
* It's not the user's fault if something goes wrong.<br />
* Attempt collaboration before conflict.<br />
* People who intentionally insult others (users, developers, corporations, other projects, or the coreboot project itself) will be dealt with. See policy below.<br />
* We are dealing with hardware with lots of undocumented pitfalls. It is quite possible that you did everything right, but coreboot or its tools still won’t work for you.<br />
<br />
Refrain from insulting anyone or the group they belong to. Remember that people might be sensitive to other things than you are.<br />
Most of our community members are not native English speakers, thus misunderstandings can (and do) happen. Always assume that others are friendly and may have picked less-than-stellar wording by accident.<br />
If you feel that you have been treated unfairly, we want to hear about it so we can handle the situation. Please contact our arbitration team directly: They will listen to you. If you don't get a response within a few days, your mail was probably lost. Please resend your mail to another member of the arbitration team in that case.<br />
<br />
= Unacceptable Behavior =<br />
Unacceptable behaviors include: intimidating, harassing, abusive, discriminatory, derogatory or demeaning speech or actions by any participant in our community online, at all related events and in one-on-one communications carried out in the context of community business. Community event venues may be shared with members of the public; please be respectful to all patrons of these locations.<br />
Harassment includes: harmful or prejudicial verbal or written comments related to gender, sexual orientation, race, religion, disability; inappropriate use of nudity and/or sexual images in public spaces (including presentation slides); deliberate intimidation, stalking or following; harassing photography or recording; sustained disruption of talks or other events; inappropriate physical contact, and unwelcome sexual attention.<br />
<br />
Check your motives: Using this code of conduct aggressively against other people in the community might also be harassment. Behave.<br />
<br />
= Consequences of Unacceptable Behavior =<br />
Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated.<br />
Anyone asked to stop unacceptable behavior is expected to comply immediately.<br />
If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event).<br />
<br />
= If You Witness or Are Subject to Unacceptable Behavior =<br />
If you are subject to or witness unacceptable behavior, or have any other concerns, please notify someone from the arbitration team immediately.<br />
<br />
<br />
= Addressing Grievances =<br />
If you feel you have been falsely or unfairly accused of violating this Code of Conduct, you should notify the arbitration team with a concise description of your grievance.<br />
<br />
<br />
= Scope =<br />
We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues—online and in-person—as well as in all one-on-one communications pertaining to community business.<br />
<br />
= Contact info =<br />
<br />
Our arbitration team consists of the following people<br />
* Marc Jones &lt;mjones@coreboot.org&gt;<br />
* Patrick Georgi &lt;patrick@coreboot.org&gt;<br />
* Ronald Minnich &lt;rminnich@coreboot.org&gt;<br />
* Stefan Reinauer &lt;stefan.reinauer@coreboot.org&gt;<br />
<br />
<br />
= License and attribution =<br />
This Code of Conduct is distributed under a Creative Commons Attribution-ShareAlike license.</div>Stepanhttp://www.coreboot.org/index.php?title=Code_of_Conduct&diff=15106Code of Conduct2015-01-09T00:34:42Z<p>Stepan: /* Consequences of Unacceptable Behavior */</p>
<hr />
<div>Coreboot Code of Conduct<br />
<br />
<br />
This code of conduct outlines our rules and expectations for everybody participating in the coreboot community.<br />
<br />
<br />
= Mailing list and chat etiquette =<br />
<br />
We have a friendly and productive atmosphere on our mailing lists, development / code review tools and IRC chat rooms. Our principles evolve around the following:<br />
<br />
* It's not the user's fault if something goes wrong.<br />
* Attempt collaboration before conflict.<br />
* People who intentionally insult others (users, developers, corporations, other projects, or the coreboot project itself) will be dealt with. See policy below.<br />
* We are dealing with hardware with lots of undocumented pitfalls. It is quite possible that you did everything right, but coreboot or its tools still won’t work for you.<br />
<br />
<br />
Refrain from insulting anyone or the group they belong to. Remember that people might be sensitive to other things than you are.<br />
Most of our community members are not native English speakers, thus misunderstandings can (and do) happen. Always assume that others are friendly and may have picked less-than-stellar wording by accident.<br />
If you feel that you have been treated unfairly, we want to hear about it so we can handle the situation. Please contact our arbitration team directly: They will listen to you. If you don't get a response within a few days, your mail was probably lost. Please resend your mail to another member of the arbitration team in that case.<br />
<br />
<br />
= Unacceptable Behavior =<br />
Unacceptable behaviors include: intimidating, harassing, abusive, discriminatory, derogatory or demeaning speech or actions by any participant in our community online, at all related events and in one-on-one communications carried out in the context of community business. Community event venues may be shared with members of the public; please be respectful to all patrons of these locations.<br />
Harassment includes: harmful or prejudicial verbal or written comments related to gender, sexual orientation, race, religion, disability; inappropriate use of nudity and/or sexual images in public spaces (including presentation slides); deliberate intimidation, stalking or following; harassing photography or recording; sustained disruption of talks or other events; inappropriate physical contact, and unwelcome sexual attention.<br />
<br />
Check your motives: Using this code of conduct aggressively against other people in the community might also be harassment. Behave.<br />
<br />
= Consequences of Unacceptable Behavior =<br />
Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated.<br />
Anyone asked to stop unacceptable behavior is expected to comply immediately.<br />
If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event).<br />
<br />
= If You Witness or Are Subject to Unacceptable Behavior =<br />
If you are subject to or witness unacceptable behavior, or have any other concerns, please notify someone from the arbitration team immediately.<br />
<br />
<br />
= Addressing Grievances =<br />
If you feel you have been falsely or unfairly accused of violating this Code of Conduct, you should notify the arbitration team with a concise description of your grievance.<br />
<br />
<br />
= Scope =<br />
We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues—online and in-person—as well as in all one-on-one communications pertaining to community business.<br />
<br />
= Contact info =<br />
<br />
Our arbitration team consists of the following people<br />
* Marc Jones &lt;mjones@coreboot.org&gt;<br />
* Patrick Georgi &lt;patrick@coreboot.org&gt;<br />
* Ronald Minnich &lt;rminnich@coreboot.org&gt;<br />
* Stefan Reinauer &lt;stefan.reinauer@coreboot.org&gt;<br />
<br />
<br />
= License and attribution =<br />
This Code of Conduct is distributed under a Creative Commons Attribution-ShareAlike license.</div>Stepanhttp://www.coreboot.org/index.php?title=Code_of_Conduct&diff=15105Code of Conduct2015-01-09T00:28:17Z<p>Stepan: </p>
<hr />
<div>Coreboot Code of Conduct<br />
<br />
<br />
This code of conduct outlines our rules and expectations for everybody participating in the coreboot community.<br />
<br />
<br />
= Mailing list and chat etiquette =<br />
<br />
We have a friendly and productive atmosphere on our mailing lists, development / code review tools and IRC chat rooms. Our principles evolve around the following:<br />
<br />
* It's not the user's fault if something goes wrong.<br />
* Attempt collaboration before conflict.<br />
* People who intentionally insult others (users, developers, corporations, other projects, or the coreboot project itself) will be dealt with. See policy below.<br />
* We are dealing with hardware with lots of undocumented pitfalls. It is quite possible that you did everything right, but coreboot or its tools still won’t work for you.<br />
<br />
<br />
Refrain from insulting anyone or the group they belong to. Remember that people might be sensitive to other things than you are.<br />
Most of our community members are not native English speakers, thus misunderstandings can (and do) happen. Always assume that others are friendly and may have picked less-than-stellar wording by accident.<br />
If you feel that you have been treated unfairly, we want to hear about it so we can handle the situation. Please contact our arbitration team directly: They will listen to you. If you don't get a response within a few days, your mail was probably lost. Please resend your mail to another member of the arbitration team in that case.<br />
<br />
<br />
= Unacceptable Behavior =<br />
Unacceptable behaviors include: intimidating, harassing, abusive, discriminatory, derogatory or demeaning speech or actions by any participant in our community online, at all related events and in one-on-one communications carried out in the context of community business. Community event venues may be shared with members of the public; please be respectful to all patrons of these locations.<br />
Harassment includes: harmful or prejudicial verbal or written comments related to gender, sexual orientation, race, religion, disability; inappropriate use of nudity and/or sexual images in public spaces (including presentation slides); deliberate intimidation, stalking or following; harassing photography or recording; sustained disruption of talks or other events; inappropriate physical contact, and unwelcome sexual attention.<br />
<br />
Check your motives: Using this code of conduct aggressively against other people in the community might also be harassment. Behave.<br />
<br />
= Consequences of Unacceptable Behavior =<br />
Unacceptable? ?behavior? ?from? ?any? ?community? ?member,? ?including? ?sponsors? ?and? ?those? ?with? ?decision-making? ?authority,? ?will? ?not? ?be? ?tolerated.<br />
Anyone? ?asked? ?to? ?stop? ?unacceptable? ?behavior? ?is? ?expected? ?to? ?comply? ?immediately.<br />
If? ?a? ?community? ?member? ?engages? ?in? ?unacceptable? ?behavior,? ?the? ?community? ?organizers? ?may? ?take? ?any? ?action? ?they? ?deem? ?appropriate,? ?up? ?to? ?and? ?including? ?a? ?temporary? ?ban? ?or? ?permanent? ?expulsion? ?from? ?the? ?community? ?without? ?warning? (?and? ?without? ?refund? ?in? ?the? ?case? ?of? ?a? ?paid? ?event?)?.<br />
?If? ?You? ?Witness? ?or? ?Are? ?Subject? ?to? ?Unacceptable? ?Behavior<br />
If? ?you? ?are? ?subject? ?to? ?or? ?witness? ?unacceptable? ?behavior,? ?or? ?have? ?any? ?other? ?concerns,? ?please? ?notify? ?someone from the arbitration team immediately.<br />
Addressing? ?Grievances<br />
If? ?you? ?feel? ?you? ?have? ?been? ?falsely? ?or? ?unfairly? ?accused? ?of? ?violating? ?this? ?Code? ?of? ?Conduct,? ?you? ?should? ?notify? ?the arbitration team ?with? ?a? ?concise? ?description? ?of? ?your? ?grievance.? ?<br />
Scope<br />
We? ?expect? ?all? ?community? ?participants? (?contributors,? ?paid? ?or? ?otherwise?; ?sponsors?; ?and? ?other? ?guests?) ?to? ?abide? ?by? ?this? ?Code? ?of? ?Conduct? ?in? ?all? ?community? ?venues?—?online? ?and? ?in-person?—?as? ?well? ?as? ?in? ?all? ?one-on-one? ?communications? ?pertaining? ?to? ?community? ?business.<br />
<br />
= Contact info =<br />
<br />
Our arbitration team consists of the following people<br />
* Marc Jones &lt;mjones@coreboot.org&gt;<br />
* Patrick Georgi &lt;patrick@coreboot.org&gt;<br />
* Ronald Minnich &lt;rminnich@coreboot.org&gt;<br />
* Stefan Reinauer &lt;stefan.reinauer@coreboot.org&gt;<br />
<br />
<br />
= License and attribution =<br />
This Code of Conduct is distributed under a Creative Commons Attribution-ShareAlike license.</div>Stepanhttp://www.coreboot.org/index.php?title=Code_of_Conduct&diff=15104Code of Conduct2015-01-09T00:13:00Z<p>Stepan: </p>
<hr />
<div>Coreboot Code of Conduct<br />
<br />
<br />
This code of conduct outlines our rules and expectations for everybody participating in the coreboot community.<br />
<br />
<br />
Mailing list and chat etiquette<br />
<br />
<br />
We have a friendly and productive atmosphere on our mailing lists, development / code review tools and IRC chat rooms. Our principles evolve around the following:<br />
<br />
<br />
* It's not the user's fault if something goes wrong.<br />
* Attempt? ?collaboration? ?before? ?conflict.<br />
* People who intentionally insult others (users, developers, corporations, other projects, or the coreboot project itself) will be dealt with. See policy below.<br />
* We are dealing with hardware with lots of undocumented pitfalls. It is quite possible that you did everything right, but coreboot or its tools still won’t work for you.<br />
<br />
<br />
Refrain from insulting anyone or the group they belong to. Remember that people might be sensitive to other things than you are.<br />
Most of our community members are not native English speakers, thus misunderstandings can (and do) happen. Always assume that others are friendly and may have picked less-than-stellar wording by accident.<br />
If you feel that you have been treated unfairly, we want to hear about it so we can handle the situation. Please contact our arbitration team directly: They will listen to you. If you don't get a response within a few days, your mail was probably lost. Please resend your mail to another member of the arbitration team in that case.<br />
<br />
<br />
Unacceptable? ?Behavior<br />
Unacceptable? ?behaviors? ?include:? ?intimidating,? ?harassing,? ?abusive,? ?discriminatory,? ?derogatory? ?or? ?demeaning? ?speech? ?or? ?actions? ?by? ?any? ?participant? ?in? ?our? ?community? ?online,? ?at? ?all? ?related? ?events? ?and? ?in? ?one-on-one? ?communications? ?carried? ?out? ?in? ?the? ?context? ?of? ?community? ?business.? ?Community? ?event? ?venues? ?may? ?be? ?shared? ?with? ?members? ?of? ?the? ?public?; ?please? ?be? ?respectful? ?to? ?all? ?patrons? ?of? ?these? ?locations.<br />
Harassment? ?includes:? ?harmful? ?or? ?prejudicial? ?verbal? ?or? ?written? ?comments? ?related? ?to? ?gender,? ?sexual? ?orientation,? ?race,? ?religion,? ?disability?; ?inappropriate? ?use? ?of? ?nudity? ?and/or? ?sexual? ?images? ?in? ?public? ?spaces? (?including? ?presentation? ?slides?); ?deliberate? ?intimidation,? ?stalking? ?or? ?following?; ?harassing? ?photography? ?or? ?recording?; ?sustained? ?disruption? ?of? ?talks? ?or? ?other? ?events?; ?inappropriate? ?physical? ?contact,? ?and? ?unwelcome? ?sexual? ?attention.<br />
Check your motives: Using this code of conduct aggressively against other people in the community might also be harassment. Behave.<br />
Consequences? ?of? ?Unacceptable? ?Behavior<br />
Unacceptable? ?behavior? ?from? ?any? ?community? ?member,? ?including? ?sponsors? ?and? ?those? ?with? ?decision-making? ?authority,? ?will? ?not? ?be? ?tolerated.<br />
Anyone? ?asked? ?to? ?stop? ?unacceptable? ?behavior? ?is? ?expected? ?to? ?comply? ?immediately.<br />
If? ?a? ?community? ?member? ?engages? ?in? ?unacceptable? ?behavior,? ?the? ?community? ?organizers? ?may? ?take? ?any? ?action? ?they? ?deem? ?appropriate,? ?up? ?to? ?and? ?including? ?a? ?temporary? ?ban? ?or? ?permanent? ?expulsion? ?from? ?the? ?community? ?without? ?warning? (?and? ?without? ?refund? ?in? ?the? ?case? ?of? ?a? ?paid? ?event?)?.<br />
?If? ?You? ?Witness? ?or? ?Are? ?Subject? ?to? ?Unacceptable? ?Behavior<br />
If? ?you? ?are? ?subject? ?to? ?or? ?witness? ?unacceptable? ?behavior,? ?or? ?have? ?any? ?other? ?concerns,? ?please? ?notify? ?someone from the arbitration team immediately.<br />
Addressing? ?Grievances<br />
If? ?you? ?feel? ?you? ?have? ?been? ?falsely? ?or? ?unfairly? ?accused? ?of? ?violating? ?this? ?Code? ?of? ?Conduct,? ?you? ?should? ?notify? ?the arbitration team ?with? ?a? ?concise? ?description? ?of? ?your? ?grievance.? ?<br />
Scope<br />
We? ?expect? ?all? ?community? ?participants? (?contributors,? ?paid? ?or? ?otherwise?; ?sponsors?; ?and? ?other? ?guests?) ?to? ?abide? ?by? ?this? ?Code? ?of? ?Conduct? ?in? ?all? ?community? ?venues?—?online? ?and? ?in-person?—?as? ?well? ?as? ?in? ?all? ?one-on-one? ?communications? ?pertaining? ?to? ?community? ?business.<br />
Contact? ?info<br />
Our arbitration team consists of the following people<br />
* Marc Jones &lt;mjones@coreboot.org&gt;<br />
* Patrick Georgi &lt;patrick@coreboot.org&gt;<br />
* Ronald Minnich &lt;rminnich@coreboot.org&gt;<br />
* Stefan Reinauer &lt;stefan.reinauer@coreboot.org&gt;<br />
<br />
<br />
?License? ?and? ?attribution<br />
This? ?Code? ?of? ?Conduct? ?is? ?distributed? ?under? ?a? ?Creative? ?Commons? ?Attribution-ShareAlike? ?license.</div>Stepanhttp://www.coreboot.org/index.php?title=Code_of_Conduct&diff=15103Code of Conduct2015-01-09T00:12:27Z<p>Stepan: Replaced content with &quot;This code of conduct outlines our rules and expectations for everybody participating in the coreboot community.&quot;</p>
<hr />
<div>This code of conduct outlines our rules and expectations for everybody participating in the coreboot community.</div>Stepanhttp://www.coreboot.org/index.php?title=Code_of_Conduct&diff=15102Code of Conduct2015-01-09T00:12:05Z<p>Stepan: </p>
<hr />
<div>Coreboot Code of Conduct<br />
<br />
This code of conduct outlines our rules and expectations for everybody participating in the coreboot community.<br />
<br />
Mailing list and chat etiquette<br />
<br />
We have a friendly and productive atmosphere on our mailing lists, development / code review tools and IRC chat rooms. Our principles evolve around the following:<br />
<br />
It's not the user's fault if something goes wrong.<br />
Attempt? ?collaboration? ?before? ?conflict.<br />
People who intentionally insult others (users, developers, corporations, other projects, or the coreboot project itself) will be dealt with. See policy below.<br />
We are dealing with hardware with lots of undocumented pitfalls. It is quite possible that you did everything right, but coreboot or its tools still won’t work for you.<br />
<br />
Refrain from insulting anyone or the group they belong to. Remember that people might be sensitive to other things than you are.<br />
Most of our community members are not native English speakers, thus misunderstandings can (and do) happen. Always assume that others are friendly and may have picked less-than-stellar wording by accident.<br />
If you feel that you have been treated unfairly, we want to hear about it so we can handle the situation. Please contact our arbitration team directly: They will listen to you. If you don't get a response within a few days, your mail was probably lost. Please resend your mail to another member of the arbitration team in that case.<br />
<br />
Unacceptable? ?Behavior<br />
Unacceptable? ?behaviors? ?include:? ?intimidating,? ?harassing,? ?abusive,? ?discriminatory,? ?derogatory? ?or? ?demeaning? ?speech? ?or? ?actions? ?by? ?any? ?participant? ?in? ?our? ?community? ?online,? ?at? ?all? ?related? ?events? ?and? ?in? ?one-on-one? ?communications? ?carried? ?out? ?in? ?the? ?context? ?of? ?community? ?business.? ?Community? ?event? ?venues? ?may? ?be? ?shared? ?with? ?members? ?of? ?the? ?public?; ?please? ?be? ?respectful? ?to? ?all? ?patrons? ?of? ?these? ?locations.<br />
Harassment? ?includes:? ?harmful? ?or? ?prejudicial? ?verbal? ?or? ?written? ?comments? ?related? ?to? ?gender,? ?sexual? ?orientation,? ?race,? ?religion,? ?disability?; ?inappropriate? ?use? ?of? ?nudity? ?and/or? ?sexual? ?images? ?in? ?public? ?spaces? (?including? ?presentation? ?slides?); ?deliberate? ?intimidation,? ?stalking? ?or? ?following?; ?harassing? ?photography? ?or? ?recording?; ?sustained? ?disruption? ?of? ?talks? ?or? ?other? ?events?; ?inappropriate? ?physical? ?contact,? ?and? ?unwelcome? ?sexual? ?attention.<br />
Check your motives: Using this code of conduct aggressively against other people in the community might also be harassment. Behave.<br />
Consequences? ?of? ?Unacceptable? ?Behavior<br />
Unacceptable? ?behavior? ?from? ?any? ?community? ?member,? ?including? ?sponsors? ?and? ?those? ?with? ?decision-making? ?authority,? ?will? ?not? ?be? ?tolerated.<br />
Anyone? ?asked? ?to? ?stop? ?unacceptable? ?behavior? ?is? ?expected? ?to? ?comply? ?immediately.<br />
If? ?a? ?community? ?member? ?engages? ?in? ?unacceptable? ?behavior,? ?the? ?community? ?organizers? ?may? ?take? ?any? ?action? ?they? ?deem? ?appropriate,? ?up? ?to? ?and? ?including? ?a? ?temporary? ?ban? ?or? ?permanent? ?expulsion? ?from? ?the? ?community? ?without? ?warning? (?and? ?without? ?refund? ?in? ?the? ?case? ?of? ?a? ?paid? ?event?)?.<br />
?If? ?You? ?Witness? ?or? ?Are? ?Subject? ?to? ?Unacceptable? ?Behavior<br />
If? ?you? ?are? ?subject? ?to? ?or? ?witness? ?unacceptable? ?behavior,? ?or? ?have? ?any? ?other? ?concerns,? ?please? ?notify? ?someone from the arbitration team immediately.<br />
Addressing? ?Grievances<br />
If? ?you? ?feel? ?you? ?have? ?been? ?falsely? ?or? ?unfairly? ?accused? ?of? ?violating? ?this? ?Code? ?of? ?Conduct,? ?you? ?should? ?notify? ?the arbitration team ?with? ?a? ?concise? ?description? ?of? ?your? ?grievance.? ?<br />
Scope<br />
We? ?expect? ?all? ?community? ?participants? (?contributors,? ?paid? ?or? ?otherwise?; ?sponsors?; ?and? ?other? ?guests?) ?to? ?abide? ?by? ?this? ?Code? ?of? ?Conduct? ?in? ?all? ?community? ?venues?—?online? ?and? ?in-person?—?as? ?well? ?as? ?in? ?all? ?one-on-one? ?communications? ?pertaining? ?to? ?community? ?business.<br />
Contact? ?info<br />
Our arbitration team consists of the following people<br />
Marc Jones &lt;mjones@coreboot.org&gt;<br />
Patrick Georgi &lt;patrick@coreboot.org&gt;<br />
Ronald Minnich &lt;rminnich@coreboot.org&gt;<br />
Stefan Reinauer &lt;stefan.reinauer@coreboot.org&gt;<br />
<br />
?License? ?and? ?attribution<br />
This? ?Code? ?of? ?Conduct? ?is? ?distributed? ?under? ?a? ?Creative? ?Commons? ?Attribution-ShareAlike? ?license.</div>Stepanhttp://www.coreboot.org/index.php?title=Code_of_Conduct&diff=15101Code of Conduct2015-01-09T00:11:37Z<p>Stepan: </p>
<hr />
<div>Coreboot Code of Conduct<br />
<br />
This code of conduct outlines our rules and expectations for everybody participating in the coreboot community.<br />
<br />
= Mailing list and chat etiquette =<br />
<br />
We have a friendly and productive atmosphere on our mailing lists, development / code review tools and IRC chat rooms. Our principles evolve around the following:<br />
<br />
* It's not the user's fault if something goes wrong.<br />
* Attempt? ?collaboration? ?before? ?conflict.<br />
* People who intentionally insult others (users, developers, corporations, other projects, or the coreboot project itself) will be dealt with. See policy below.<br />
* We are dealing with hardware with lots of undocumented pitfalls. It is quite possible that you did everything right, but coreboot or its tools still won’t work for you.<br />
<br />
Refrain from insulting anyone or the group they belong to. Remember that people might be sensitive to other things than you are.<br />
Most of our community members are not native English speakers, thus misunderstandings can (and do) happen. Always assume that others are friendly and may have picked less-than-stellar wording by accident.<br />
If you feel that you have been treated unfairly, we want to hear about it so we can handle the situation. Please contact our arbitration team directly: They will listen to you. If you don't get a response within a few days, your mail was probably lost. Please resend your mail to another member of the arbitration team in that case.<br />
<br />
= Unacceptable? ?Behavior =<br />
Unacceptable? ?behaviors? ?include:? ?intimidating,? ?harassing,? ?abusive,? ?discriminatory,? ?derogatory? ?or? ?demeaning? ?speech? ?or? ?actions? ?by? ?any? ?participant? ?in? ?our? ?community? ?online,? ?at? ?all? ?related? ?events? ?and? ?in? ?one-on-one? ?communications? ?carried? ?out? ?in? ?the? ?context? ?of? ?community? ?business.? ?Community? ?event? ?venues? ?may? ?be? ?shared? ?with? ?members? ?of? ?the? ?public?; ?please? ?be? ?respectful? ?to? ?all? ?patrons? ?of? ?these? ?locations.<br />
Harassment? ?includes:? ?harmful? ?or? ?prejudicial? ?verbal? ?or? ?written? ?comments? ?related? ?to? ?gender,? ?sexual? ?orientation,? ?race,? ?religion,? ?disability?; ?inappropriate? ?use? ?of? ?nudity? ?and/or? ?sexual? ?images? ?in? ?public? ?spaces? (?including? ?presentation? ?slides?); ?deliberate? ?intimidation,? ?stalking? ?or? ?following?; ?harassing? ?photography? ?or? ?recording?; ?sustained? ?disruption? ?of? ?talks? ?or? ?other? ?events?; ?inappropriate? ?physical? ?contact,? ?and? ?unwelcome? ?sexual? ?attention.<br />
Check your motives: Using this code of conduct aggressively against other people in the community might also be harassment. Behave.<br />
= Consequences? ?of? ?Unacceptable? ?Behavior =<br />
Unacceptable? ?behavior? ?from? ?any? ?community? ?member,? ?including? ?sponsors? ?and? ?those? ?with? ?decision-making? ?authority,? ?will? ?not? ?be? ?tolerated.<br />
Anyone? ?asked? ?to? ?stop? ?unacceptable? ?behavior? ?is? ?expected? ?to? ?comply? ?immediately.<br />
If? ?a? ?community? ?member? ?engages? ?in? ?unacceptable? ?behavior,? ?the? ?community? ?organizers? ?may? ?take? ?any? ?action? ?they? ?deem? ?appropriate,? ?up? ?to? ?and? ?including? ?a? ?temporary? ?ban? ?or? ?permanent? ?expulsion? ?from? ?the? ?community? ?without? ?warning? (?and? ?without? ?refund? ?in? ?the? ?case? ?of? ?a? ?paid? ?event?)?.<br />
?= If? ?You? ?Witness? ?or? ?Are? ?Subject? ?to? ?Unacceptable? ?Behavior =<br />
If? ?you? ?are? ?subject? ?to? ?or? ?witness? ?unacceptable? ?behavior,? ?or? ?have? ?any? ?other? ?concerns,? ?please? ?notify? ?someone from the arbitration team immediately.<br />
= Addressing? ?Grievances =<br />
If? ?you? ?feel? ?you? ?have? ?been? ?falsely? ?or? ?unfairly? ?accused? ?of? ?violating? ?this? ?Code? ?of? ?Conduct,? ?you? ?should? ?notify? ?the arbitration team ?with? ?a? ?concise? ?description? ?of? ?your? ?grievance.? ?<br />
Scope<br />
We? ?expect? ?all? ?community? ?participants? (?contributors,? ?paid? ?or? ?otherwise?; ?sponsors?; ?and? ?other? ?guests?) ?to? ?abide? ?by? ?this? ?Code? ?of? ?Conduct? ?in? ?all? ?community? ?venues?—?online? ?and? ?in-person?—?as? ?well? ?as? ?in? ?all? ?one-on-one? ?communications? ?pertaining? ?to? ?community? ?business.<br />
= Contact? ?info =<br />
Our arbitration team consists of the following people<br />
* Marc Jones &lt;mjones@coreboot.org&gt;<br />
* Patrick Georgi &lt;patrick@coreboot.org&gt;<br />
* Ronald Minnich &lt;rminnich@coreboot.org&gt;<br />
* Stefan Reinauer &lt;stefan.reinauer@coreboot.org&gt;<br />
<br />
= ?License? ?and? ?attribution =<br />
This? ?Code? ?of? ?Conduct? ?is? ?distributed? ?under? ?a? ?Creative? ?Commons? ?Attribution-ShareAlike? ?license.</div>Stepanhttp://www.coreboot.org/index.php?title=Code_of_Conduct&diff=15100Code of Conduct2015-01-09T00:11:07Z<p>Stepan: </p>
<hr />
<div>Coreboot Code of Conduct<br />
<br />
This code of conduct outlines our rules and expectations for everybody participating in the coreboot community.<br />
<br />
= Mailing list and chat etiquette =<br />
<br />
We have a friendly and productive atmosphere on our mailing lists, development / code review tools and IRC chat rooms. Our principles evolve around the following:<br />
<br />
* It's not the user's fault if something goes wrong.<br />
* Attempt? ?collaboration? ?before? ?conflict.<br />
* People who intentionally insult others (users, developers, corporations, other projects, or the coreboot project itself) will be dealt with. See policy below.<br />
* We are dealing with hardware with lots of undocumented pitfalls. It is quite possible that you did everything right, but coreboot or its tools still won’t work for you.<br />
<br />
Refrain from insulting anyone or the group they belong to. Remember that people might be sensitive to other things than you are.<br />
Most of our community members are not native English speakers, thus misunderstandings can (and do) happen. Always assume that others are friendly and may have picked less-than-stellar wording by accident.<br />
If you feel that you have been treated unfairly, we want to hear about it so we can handle the situation. Please contact our arbitration team directly: They will listen to you. If you don't get a response within a few days, your mail was probably lost. Please resend your mail to another member of the arbitration team in that case.<br />
<br />
= Unacceptable? ?Behavior =<br />
Unacceptable? ?behaviors? ?include:? ?intimidating,? ?harassing,? ?abusive,? ?discriminatory,? ?derogatory? ?or? ?demeaning? ?speech? ?or? ?actions? ?by? ?any? ?participant? ?in? ?our? ?community? ?online,? ?at? ?all? ?related? ?events? ?and? ?in? ?one-on-one? ?communications? ?carried? ?out? ?in? ?the? ?context? ?of? ?community? ?business.? ?Community? ?event? ?venues? ?may? ?be? ?shared? ?with? ?members? ?of? ?the? ?public?; ?please? ?be? ?respectful? ?to? ?all? ?patrons? ?of? ?these? ?locations.<br />
Harassment? ?includes:? ?harmful? ?or? ?prejudicial? ?verbal? ?or? ?written? ?comments? ?related? ?to? ?gender,? ?sexual? ?orientation,? ?race,? ?religion,? ?disability?; ?inappropriate? ?use? ?of? ?nudity? ?and/or? ?sexual? ?images? ?in? ?public? ?spaces? (?including? ?presentation? ?slides?); ?deliberate? ?intimidation,? ?stalking? ?or? ?following?; ?harassing? ?photography? ?or? ?recording?; ?sustained? ?disruption? ?of? ?talks? ?or? ?other? ?events?; ?inappropriate? ?physical? ?contact,? ?and? ?unwelcome? ?sexual? ?attention.<br />
Check your motives: Using this code of conduct aggressively against other people in the community might also be harassment. Behave.<br />
= Consequences? ?of? ?Unacceptable? ?Behavior =<br />
Unacceptable? ?behavior? ?from? ?any? ?community? ?member,? ?including? ?sponsors? ?and? ?those? ?with? ?decision-making? ?authority,? ?will? ?not? ?be? ?tolerated.<br />
Anyone? ?asked? ?to? ?stop? ?unacceptable? ?behavior? ?is? ?expected? ?to? ?comply? ?immediately.<br />
If? ?a? ?community? ?member? ?engages? ?in? ?unacceptable? ?behavior,? ?the? ?community? ?organizers? ?may? ?take? ?any? ?action? ?they? ?deem? ?appropriate,? ?up? ?to? ?and? ?including? ?a? ?temporary? ?ban? ?or? ?permanent? ?expulsion? ?from? ?the? ?community? ?without? ?warning? (?and? ?without? ?refund? ?in? ?the? ?case? ?of? ?a? ?paid? ?event?)?.<br />
?= If? ?You? ?Witness? ?or? ?Are? ?Subject? ?to? ?Unacceptable? ?Behavior =<br />
If? ?you? ?are? ?subject? ?to? ?or? ?witness? ?unacceptable? ?behavior,? ?or? ?have? ?any? ?other? ?concerns,? ?please? ?notify? ?someone from the arbitration team immediately.<br />
= Addressing? ?Grievances =<br />
If? ?you? ?feel? ?you? ?have? ?been? ?falsely? ?or? ?unfairly? ?accused? ?of? ?violating? ?this? ?Code? ?of? ?Conduct,? ?you? ?should? ?notify? ?the arbitration team ?with? ?a? ?concise? ?description? ?of? ?your? ?grievance.? ?<br />
Scope<br />
We? ?expect? ?all? ?community? ?participants? (?contributors,? ?paid? ?or? ?otherwise?; ?sponsors?; ?and? ?other? ?guests?) ?to? ?abide? ?by? ?this? ?Code? ?of? ?Conduct? ?in? ?all? ?community? ?venues?—?online? ?and? ?in-person?—?as? ?well? ?as? ?in? ?all? ?one-on-one? ?communications? ?pertaining? ?to? ?community? ?business.<br />
= Contact? ?info =<br />
Our arbitration team consists of the following people<br />
* Marc Jones &lt;mjones@coreboot.org&gt;<br />
* Patrick Georgi &lt;patrick@coreboot.org&gt;<br />
* Ronald Minnich &lt;rminnich@coreboot.org&gt;<br />
* Stefan Reinauer &lt;stefan.reinauer@coreboot.org&gt;<br />
<br />
= ?License? ?and? ?attribution =<br />
This? ?Code? ?of? ?Conduct? ?is? ?distributed? ?under? ?a? ?Creative? ?Commons? ?Attribution-ShareAlike? ?license.</div>Stepanhttp://www.coreboot.org/index.php?title=Code_of_Conduct&diff=15099Code of Conduct2015-01-09T00:08:42Z<p>Stepan: Created page with &quot;This code of conduct outlines our rules and expectations for everybody participating in the coreboot community. = Mailing list and chat etiquette = We have a friendly and pr...&quot;</p>
<hr />
<div>This code of conduct outlines our rules and expectations for everybody participating in the coreboot community.<br />
<br />
= Mailing list and chat etiquette =<br />
<br />
We have a friendly and productive atmosphere on our mailing lists, development / code review tools and IRC chat rooms. Our principles evolve around the following:<br />
<br />
It's not the user's fault if something goes wrong.<br />
Attempt? ?collaboration? ?before? ?conflict.<br />
People who intentionally insult others (users, developers, corporations, other projects, or the coreboot project itself) will be dealt with. See policy below.<br />
We are dealing with hardware with lots of undocumented pitfalls. It is quite possible that you did everything right, but coreboot or its tools still won’t work for you.<br />
<br />
Refrain from insulting anyone or the group they belong to. Remember that people might be sensitive to other things than you are.<br />
Most of our community members are not native English speakers, thus misunderstandings can (and do) happen. Always assume that others are friendly and may have picked less-than-stellar wording by accident.<br />
If you feel that you have been treated unfairly, we want to hear about it so we can handle the situation. Please contact our arbitration team directly: They will listen to you. If you don't get a response within a few days, your mail was probably lost. Please resend your mail to another member of the arbitration team in that case.<br />
<br />
= Unacceptable? ?Behavior =<br />
Unacceptable? ?behaviors? ?include:? ?intimidating,? ?harassing,? ?abusive,? ?discriminatory,? ?derogatory? ?or? ?demeaning? ?speech? ?or? ?actions? ?by? ?any? ?participant? ?in? ?our? ?community? ?online,? ?at? ?all? ?related? ?events? ?and? ?in? ?one-on-one? ?communications? ?carried? ?out? ?in? ?the? ?context? ?of? ?community? ?business.? ?Community? ?event? ?venues? ?may? ?be? ?shared? ?with? ?members? ?of? ?the? ?public?; ?please? ?be? ?respectful? ?to? ?all? ?patrons? ?of? ?these? ?locations.<br />
Harassment? ?includes:? ?harmful? ?or? ?prejudicial? ?verbal? ?or? ?written? ?comments? ?related? ?to? ?gender,? ?sexual? ?orientation,? ?race,? ?religion,? ?disability?; ?inappropriate? ?use? ?of? ?nudity? ?and/or? ?sexual? ?images? ?in? ?public? ?spaces? (?including? ?presentation? ?slides?); ?deliberate? ?intimidation,? ?stalking? ?or? ?following?; ?harassing? ?photography? ?or? ?recording?; ?sustained? ?disruption? ?of? ?talks? ?or? ?other? ?events?; ?inappropriate? ?physical? ?contact,? ?and? ?unwelcome? ?sexual? ?attention.<br />
Check your motives: Using this code of conduct aggressively against other people in the community might also be harassment. Behave.<br />
= Consequences? ?of? ?Unacceptable? ?Behavior =<br />
Unacceptable? ?behavior? ?from? ?any? ?community? ?member,? ?including? ?sponsors? ?and? ?those? ?with? ?decision-making? ?authority,? ?will? ?not? ?be? ?tolerated.<br />
Anyone? ?asked? ?to? ?stop? ?unacceptable? ?behavior? ?is? ?expected? ?to? ?comply? ?immediately.<br />
If? ?a? ?community? ?member? ?engages? ?in? ?unacceptable? ?behavior,? ?the? ?community? ?organizers? ?may? ?take? ?any? ?action? ?they? ?deem? ?appropriate,? ?up? ?to? ?and? ?including? ?a? ?temporary? ?ban? ?or? ?permanent? ?expulsion? ?from? ?the? ?community? ?without? ?warning? (?and? ?without? ?refund? ?in? ?the? ?case? ?of? ?a? ?paid? ?event?)?.<br />
?= If? ?You? ?Witness? ?or? ?Are? ?Subject? ?to? ?Unacceptable? ?Behavior =<br />
If? ?you? ?are? ?subject? ?to? ?or? ?witness? ?unacceptable? ?behavior,? ?or? ?have? ?any? ?other? ?concerns,? ?please? ?notify? ?someone from the arbitration team immediately.<br />
= Addressing? ?Grievances =<br />
If? ?you? ?feel? ?you? ?have? ?been? ?falsely? ?or? ?unfairly? ?accused? ?of? ?violating? ?this? ?Code? ?of? ?Conduct,? ?you? ?should? ?notify? ?the arbitration team ?with? ?a? ?concise? ?description? ?of? ?your? ?grievance.? ?<br />
Scope<br />
We? ?expect? ?all? ?community? ?participants? (?contributors,? ?paid? ?or? ?otherwise?; ?sponsors?; ?and? ?other? ?guests?) ?to? ?abide? ?by? ?this? ?Code? ?of? ?Conduct? ?in? ?all? ?community? ?venues?—?online? ?and? ?in-person?—?as? ?well? ?as? ?in? ?all? ?one-on-one? ?communications? ?pertaining? ?to? ?community? ?business.<br />
= Contact? ?info =<br />
Our arbitration team consists of the following people<br />
* Marc Jones &lt;mjones@coreboot.org&gt;<br />
* Patrick Georgi &lt;patrick@coreboot.org&gt;<br />
* Ronald Minnich &lt;rminnich@coreboot.org&gt;<br />
* Stefan Reinauer &lt;stefan.reinauer@coreboot.org&gt;<br />
<br />
?= License? ?and? ?attribution =<br />
This? ?Code? ?of? ?Conduct? ?is? ?distributed? ?under? ?a? ?Creative? ?Commons? ?Attribution-ShareAlike? ?license.</div>Stepanhttp://www.coreboot.org/index.php?title=Coding_Style&diff=12317Coding Style2013-12-05T18:57:23Z<p>Stepan: /* You've made a mess of it */</p>
<hr />
<div>This is a short document describing the preferred coding style for the<br />
coreboot project. It is in many ways exactly the same as the Linux kernel<br />
coding style. In fact, most of this document has been copied from the<br />
[http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/Documentation/CodingStyle?id=HEAD Linux kernel coding style]<br />
<br />
Please at least consider the points made here.<br />
<br />
First off, I'd suggest printing out a copy of the GNU coding standards,<br />
and NOT read it. Burn them, it's a great symbolic gesture.<br />
<br />
Anyway, here goes:<br />
<br />
<br />
== Indentation ==<br />
<br />
Tabs are 8 characters, and thus indentations are also 8 characters.<br />
There are heretic movements that try to make indentations 4 (or even 2!)<br />
characters deep, and that is akin to trying to define the value of PI to<br />
be 3.<br />
<br />
Rationale: The whole idea behind indentation is to clearly define where<br />
a block of control starts and ends. Especially when you've been looking<br />
at your screen for 20 straight hours, you'll find it a lot easier to see<br />
how the indentation works if you have large indentations.<br />
<br />
Now, some people will claim that having 8-character indentations makes<br />
the code move too far to the right, and makes it hard to read on a<br />
80-character terminal screen. The answer to that is that if you need<br />
more than 3 levels of indentation, you're screwed anyway, and should fix<br />
your program.<br />
<br />
In short, 8-char indents make things easier to read, and have the added<br />
benefit of warning you when you're nesting your functions too deep.<br />
Heed that warning.<br />
<br />
The preferred way to ease multiple indentation levels in a switch statement is<br />
to align the &quot;switch&quot; and its subordinate &quot;case&quot; labels in the same column<br />
instead of &quot;double-indenting&quot; the &quot;case&quot; labels. E.g.:<br />
<br />
switch (suffix) {<br />
case 'G':<br />
case 'g':<br />
mem &lt;&lt;= 30;<br />
break;<br />
case 'M':<br />
case 'm':<br />
mem &lt;&lt;= 20;<br />
break;<br />
case 'K':<br />
case 'k':<br />
mem &lt;&lt;= 10;<br />
/* fall through */<br />
default:<br />
break;<br />
}<br />
<br />
<br />
Don't put multiple statements on a single line unless you have<br />
something to hide:<br />
<br />
if (condition) do_this;<br />
do_something_everytime;<br />
<br />
Don't put multiple assignments on a single line either. Kernel coding style<br />
is super simple. Avoid tricky expressions.<br />
<br />
Outside of comments, documentation and except in Kconfig, spaces are never<br />
used for indentation, and the above example is deliberately broken.<br />
<br />
Get a decent editor and don't leave whitespace at the end of lines.<br />
<br />
== Breaking long lines and strings ==<br />
<br />
Coding style is all about readability and maintainability using commonly<br />
available tools.<br />
<br />
The limit on the length of lines is 80 columns and this is a strongly<br />
preferred limit.<br />
<br />
Statements longer than 80 columns will be broken into sensible chunks, unless<br />
exceeding 80 columns significantly increases readability and does not hide<br />
information. Descendants are always substantially shorter than the parent and<br />
are placed substantially to the right. The same applies to function headers<br />
with a long argument list. However, never break user-visible strings such as<br />
printk messages, because that breaks the ability to grep for them.<br />
<br />
<br />
== Placing Braces and Spaces ==<br />
<br />
The other issue that always comes up in C styling is the placement of<br />
braces. Unlike the indent size, there are few technical reasons to<br />
choose one placement strategy over the other, but the preferred way, as<br />
shown to us by the prophets Kernighan and Ritchie, is to put the opening<br />
brace last on the line, and put the closing brace first, thusly:<br />
<br />
if (x is true) {<br />
we do y<br />
}<br />
<br />
This applies to all non-function statement blocks (if, switch, for,<br />
while, do). E.g.:<br />
<br />
switch (action) {<br />
case KOBJ_ADD:<br />
return &quot;add&quot;;<br />
case KOBJ_REMOVE:<br />
return &quot;remove&quot;;<br />
case KOBJ_CHANGE:<br />
return &quot;change&quot;;<br />
default:<br />
return NULL;<br />
}<br />
<br />
However, there is one special case, namely functions: they have the<br />
opening brace at the beginning of the next line, thus:<br />
<br />
int function(int x)<br />
{<br />
body of function<br />
}<br />
<br />
Heretic people all over the world have claimed that this inconsistency<br />
is ... well ... inconsistent, but all right-thinking people know that<br />
(a) K&amp;R are _right_ and (b) K&amp;R are right. Besides, functions are<br />
special anyway (you can't nest them in C).<br />
<br />
Note that the closing brace is empty on a line of its own, _except_ in<br />
the cases where it is followed by a continuation of the same statement,<br />
ie a &quot;while&quot; in a do-statement or an &quot;else&quot; in an if-statement, like<br />
this:<br />
<br />
do {<br />
body of do-loop<br />
} while (condition);<br />
<br />
and<br />
<br />
if (x == y) {<br />
..<br />
} else if (x &gt; y) {<br />
...<br />
} else {<br />
....<br />
}<br />
<br />
Rationale: K&amp;R.<br />
<br />
Also, note that this brace-placement also minimizes the number of empty<br />
(or almost empty) lines, without any loss of readability. Thus, as the<br />
supply of new-lines on your screen is not a renewable resource (think<br />
25-line terminal screens here), you have more empty lines to put<br />
comments on.<br />
<br />
Do not unnecessarily use braces where a single statement will do.<br />
<br />
if (condition)<br />
action();<br />
<br />
and<br />
<br />
if (condition)<br />
do_this();<br />
else<br />
do_that();<br />
<br />
This does not apply if only one branch of a conditional statement is a single<br />
statement; in the latter case use braces in both branches:<br />
<br />
if (condition) {<br />
do_this();<br />
do_that();<br />
} else {<br />
otherwise();<br />
}<br />
<br />
=== Spaces ===<br />
<br />
Linux kernel style for use of spaces depends (mostly) on<br />
function-versus-keyword usage. Use a space after (most) keywords. The<br />
notable exceptions are sizeof, typeof, alignof, and __attribute__, which look<br />
somewhat like functions (and are usually used with parentheses in Linux,<br />
although they are not required in the language, as in: &quot;sizeof info&quot; after<br />
&quot;struct fileinfo info;&quot; is declared).<br />
<br />
So use a space after these keywords:<br />
if, switch, case, for, do, while<br />
but not with sizeof, typeof, alignof, or __attribute__. E.g.,<br />
s = sizeof(struct file);<br />
<br />
Do not add spaces around (inside) parenthesized expressions. This example is<br />
*bad*:<br />
<br />
s = sizeof( struct file );<br />
<br />
When declaring pointer data or a function that returns a pointer type, the<br />
preferred use of '*' is adjacent to the data name or function name and not<br />
adjacent to the type name. Examples:<br />
<br />
char *linux_banner;<br />
unsigned long long memparse(char *ptr, char **retptr);<br />
char *match_strdup(substring_t *s);<br />
<br />
Use one space around (on each side of) most binary and ternary operators,<br />
such as any of these:<br />
<br />
= + - &lt; &gt; * / % | &amp; ^ &lt;= &gt;= == != ? :<br />
<br />
but no space after unary operators:<br />
&amp; * + - ~ ! sizeof typeof alignof __attribute__ defined<br />
<br />
no space before the postfix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
no space after the prefix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
and no space around the '.' and &quot;-&gt;&quot; structure member operators.<br />
<br />
Do not leave trailing whitespace at the ends of lines. Some editors with<br />
&quot;smart&quot; indentation will insert whitespace at the beginning of new lines as<br />
appropriate, so you can start typing the next line of code right away.<br />
However, some such editors do not remove the whitespace if you end up not<br />
putting a line of code there, such as if you leave a blank line. As a result,<br />
you end up with lines containing trailing whitespace.<br />
<br />
Git will warn you about patches that introduce trailing whitespace, and can<br />
optionally strip the trailing whitespace for you; however, if applying a series<br />
of patches, this may make later patches in the series fail by changing their<br />
context lines.<br />
<br />
== Naming ==<br />
<br />
C is a Spartan language, and so should your naming be. Unlike Modula-2<br />
and Pascal programmers, C programmers do not use cute names like<br />
ThisVariableIsATemporaryCounter. A C programmer would call that<br />
variable &quot;tmp&quot;, which is much easier to write, and not the least more<br />
difficult to understand.<br />
<br />
HOWEVER, while mixed-case names are frowned upon, descriptive names for<br />
global variables are a must. To call a global function &quot;foo&quot; is a<br />
shooting offense.<br />
<br />
GLOBAL variables (to be used only if you _really_ need them) need to<br />
have descriptive names, as do global functions. If you have a function<br />
that counts the number of active users, you should call that<br />
&quot;count_active_users()&quot; or similar, you should _not_ call it &quot;cntusr()&quot;.<br />
<br />
Encoding the type of a function into the name (so-called Hungarian<br />
notation) is brain damaged - the compiler knows the types anyway and can<br />
check those, and it only confuses the programmer. No wonder MicroSoft<br />
makes buggy programs.<br />
<br />
LOCAL variable names should be short, and to the point. If you have<br />
some random integer loop counter, it should probably be called &quot;i&quot;.<br />
Calling it &quot;loop_counter&quot; is non-productive, if there is no chance of it<br />
being mis-understood. Similarly, &quot;tmp&quot; can be just about any type of<br />
variable that is used to hold a temporary value.<br />
<br />
If you are afraid to mix up your local variable names, you have another<br />
problem, which is called the function-growth-hormone-imbalance syndrome.<br />
See chapter 6 (Functions).<br />
<br />
<br />
== Typedefs ==<br />
<br />
Please don't use things like &quot;vps_t&quot;.<br />
<br />
It's a _mistake_ to use typedef for structures and pointers. When you see a<br />
<br />
vps_t a;<br />
<br />
in the source, what does it mean?<br />
<br />
In contrast, if it says<br />
<br />
struct virtual_container *a;<br />
<br />
you can actually tell what &quot;a&quot; is.<br />
<br />
Lots of people think that typedefs &quot;help readability&quot;. Not so. They are<br />
useful only for:<br />
<br />
(a) totally opaque objects (where the typedef is actively used to _hide_ what the object is).<br />
<br />
Example: &quot;pte_t&quot; etc. opaque objects that you can only access using<br />
the proper accessor functions.<br />
<br />
NOTE! Opaqueness and &quot;accessor functions&quot; are not good in themselves.<br />
The reason we have them for things like pte_t etc. is that there<br />
really is absolutely _zero_ portably accessible information there.<br />
<br />
(b) Clear integer types, where the abstraction _helps_ avoid confusion<br />
whether it is &quot;int&quot; or &quot;long&quot;.<br />
<br />
u8/u16/u32 are perfectly fine typedefs, although they fit into<br />
category (d) better than here.<br />
<br />
NOTE! Again - there needs to be a _reason_ for this. If something is<br />
&quot;unsigned long&quot;, then there's no reason to do<br />
<br />
typedef unsigned long myflags_t;<br />
<br />
but if there is a clear reason for why it under certain circumstances<br />
might be an &quot;unsigned int&quot; and under other configurations might be<br />
&quot;unsigned long&quot;, then by all means go ahead and use a typedef.<br />
<br />
(c) when you use sparse to literally create a _new_ type for<br />
type-checking.<br />
<br />
(d) New types which are identical to standard C99 types, in certain<br />
exceptional circumstances.<br />
<br />
Although it would only take a short amount of time for the eyes and<br />
brain to become accustomed to the standard types like 'uint32_t',<br />
some people object to their use anyway.<br />
<br />
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their<br />
signed equivalents which are identical to standard types are<br />
permitted -- although they are not mandatory in new code of your<br />
own.<br />
<br />
When editing existing code which already uses one or the other set<br />
of types, you should conform to the existing choices in that code.<br />
<br />
(e) Types safe for use in userspace.<br />
<br />
In certain structures which are visible to userspace, we cannot<br />
require C99 types and cannot use the 'u32' form above. Thus, we<br />
use __u32 and similar types in all structures which are shared<br />
with userspace.<br />
<br />
Maybe there are other cases too, but the rule should basically be to NEVER<br />
EVER use a typedef unless you can clearly match one of those rules.<br />
<br />
<br />
In general, a pointer, or a struct that has elements that can reasonably<br />
be directly accessed should _never_ be a typedef.<br />
<br />
== Functions ==<br />
<br />
Functions should be short and sweet, and do just one thing. They should<br />
fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,<br />
as we all know), and do one thing and do that well.<br />
<br />
The maximum length of a function is inversely proportional to the<br />
complexity and indentation level of that function. So, if you have a<br />
conceptually simple function that is just one long (but simple)<br />
case-statement, where you have to do lots of small things for a lot of<br />
different cases, it's OK to have a longer function.<br />
<br />
However, if you have a complex function, and you suspect that a<br />
less-than-gifted first-year high-school student might not even<br />
understand what the function is all about, you should adhere to the<br />
maximum limits all the more closely. Use helper functions with<br />
descriptive names (you can ask the compiler to in-line them if you think<br />
it's performance-critical, and it will probably do a better job of it<br />
than you would have done).<br />
<br />
Another measure of the function is the number of local variables. They<br />
shouldn't exceed 5-10, or you're doing something wrong. Re-think the<br />
function, and split it into smaller pieces. A human brain can<br />
generally easily keep track of about 7 different things, anything more<br />
and it gets confused. You know you're brilliant, but maybe you'd like<br />
to understand what you did 2 weeks from now.<br />
<br />
In source files, separate functions with one blank line. If the function is<br />
exported, the EXPORT* macro for it should follow immediately after the closing<br />
function brace line. E.g.:<br />
<br />
int system_is_up(void)<br />
{<br />
return system_state == SYSTEM_RUNNING;<br />
}<br />
EXPORT_SYMBOL(system_is_up);<br />
<br />
In function prototypes, include parameter names with their data types.<br />
Although this is not required by the C language, it is preferred in Linux<br />
because it is a simple way to add valuable information for the reader.<br />
<br />
== Centralized exiting of functions ==<br />
<br />
Albeit deprecated by some people, the equivalent of the goto statement is<br />
used frequently by compilers in form of the unconditional jump instruction.<br />
<br />
The goto statement comes in handy when a function exits from multiple<br />
locations and some common work such as cleanup has to be done. If there is no<br />
cleanup needed then just return directly.<br />
<br />
The rationale is:<br />
<br />
* unconditional statements are easier to understand and follow<br />
* nesting is reduced<br />
* errors by not updating individual exit points when making modifications are prevented<br />
* saves the compiler work to optimize redundant code away ;)<br />
<br />
int fun(int a)<br />
{<br />
int result = 0;<br />
char *buffer = kmalloc(SIZE);<br />
<br />
if (buffer == NULL)<br />
return -ENOMEM;<br />
<br />
if (condition1) {<br />
while (loop1) {<br />
...<br />
}<br />
result = 1;<br />
goto out;<br />
}<br />
...<br />
out:<br />
kfree(buffer);<br />
return result;<br />
}<br />
<br />
== Commenting ==<br />
<br />
Comments are good, but there is also a danger of over-commenting. NEVER<br />
try to explain HOW your code works in a comment: it's much better to<br />
write the code so that the _working_ is obvious, and it's a waste of<br />
time to explain badly written code.<br />
<br />
Generally, you want your comments to tell WHAT your code does, not HOW.<br />
Also, try to avoid putting comments inside a function body: if the<br />
function is so complex that you need to separately comment parts of it,<br />
you should probably go back to chapter 6 for a while. You can make<br />
small comments to note or warn about something particularly clever (or<br />
ugly), but try to avoid excess. Instead, put the comments at the head<br />
of the function, telling people what it does, and possibly WHY it does<br />
it.<br />
<br />
When commenting the kernel API functions, please use the kernel-doc format.<br />
See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc<br />
for details.<br />
<br />
coreboot style for comments is the C89 &quot;/* ... */&quot; style.<br />
You may use C99-style &quot;// ...&quot; comments.<br />
<br />
The preferred style for long (multi-line) comments is:<br />
<br />
/*<br />
* This is the preferred style for multi-line<br />
* comments in the Linux kernel source code.<br />
* Please use it consistently.<br />
*<br />
* Description: A column of asterisks on the left side,<br />
* with beginning and ending almost-blank lines.<br />
*/<br />
<br />
For files in net/ and drivers/net/ the preferred style for long (multi-line)<br />
comments is a little different.<br />
<br />
/* The preferred comment style for files in net/ and drivers/net<br />
* looks like this.<br />
*<br />
* It is nearly the same as the generally preferred comment style,<br />
* but there is no initial almost-blank line.<br />
*/<br />
<br />
It's also important to comment data, whether they are basic types or derived<br />
types. To this end, use just one data declaration per line (no commas for<br />
multiple data declarations). This leaves you room for a small comment on each<br />
item, explaining its use.<br />
<br />
== You've made a mess of it ==<br />
<br />
That's OK, we all do. You've probably been told by your long-time Unix<br />
user helper that &quot;GNU emacs&quot; automatically formats the C sources for<br />
you, and you've noticed that yes, it does do that, but the defaults it<br />
uses are less than desirable (in fact, they are worse than random<br />
typing - an infinite number of monkeys typing into GNU emacs would never<br />
make a good program).<br />
<br />
So, you can either get rid of GNU emacs, or change it to use saner<br />
values. To do the latter, you can stick the following in your .emacs file:<br />
<br />
(defun c-lineup-arglist-tabs-only (ignored)<br />
&quot;Line up argument lists by tabs, not spaces&quot;<br />
(let* ((anchor (c-langelem-pos c-syntactic-element))<br />
(column (c-langelem-2nd-pos c-syntactic-element))<br />
(offset (- (1+ column) anchor))<br />
(steps (floor offset c-basic-offset)))<br />
(* (max steps 1)<br />
c-basic-offset)))<br />
<br />
(add-hook 'c-mode-common-hook<br />
(lambda ()<br />
;; Add kernel style<br />
(c-add-style<br />
&quot;linux-tabs-only&quot;<br />
'(&quot;linux&quot; (c-offsets-alist<br />
(arglist-cont-nonempty<br />
c-lineup-gcc-asm-reg<br />
c-lineup-arglist-tabs-only))))))<br />
<br />
(add-hook 'c-mode-hook<br />
(lambda ()<br />
(let ((filename (buffer-file-name)))<br />
;; Enable kernel mode for the appropriate files<br />
(when (and filename<br />
(string-match (expand-file-name &quot;~/src/linux-trees&quot;)<br />
filename))<br />
(setq indent-tabs-mode t)<br />
(c-set-style &quot;linux-tabs-only&quot;)))))<br />
<br />
This will make emacs go better with the kernel coding style for C<br />
files below ~/src/linux-trees.<br />
<br />
But even if you fail in getting emacs to do sane formatting, not<br />
everything is lost: use &quot;indent&quot;.<br />
<br />
Now, again, GNU indent has the same brain-dead settings that GNU emacs<br />
has, which is why you need to give it a few command line options.<br />
However, that's not too bad, because even the makers of GNU indent<br />
recognize the authority of K&amp;R (the GNU people aren't evil, they are<br />
just severely misguided in this matter), so you just give indent the<br />
options &quot;-kr -i8&quot; (stands for &quot;K&amp;R, 8 character indents&quot;), or use<br />
&quot;scripts/Lindent&quot;, which indents in the latest style.<br />
<br />
&quot;indent&quot; has a lot of options, and especially when it comes to comment<br />
re-formatting you may want to take a look at the man page. But<br />
remember: &quot;indent&quot; is not a fix for bad programming.<br />
<br />
== Kconfig configuration files ==<br />
<br />
For all of the Kconfig* configuration files throughout the source tree,<br />
the indentation is somewhat different. Lines under a &quot;config&quot; definition<br />
are indented with one tab, while help text is indented an additional two<br />
spaces. Example:<br />
<br />
config AUDIT<br />
bool &quot;Auditing support&quot;<br />
depends on NET<br />
help<br />
Enable auditing infrastructure that can be used with another<br />
kernel subsystem, such as SELinux (which requires this for<br />
logging of avc messages output). Does not do system-call<br />
auditing without CONFIG_AUDITSYSCALL.<br />
<br />
Seriously dangerous features (such as write support for certain<br />
filesystems) should advertise this prominently in their prompt string:<br />
<br />
config ADFS_FS_RW<br />
bool &quot;ADFS write support (DANGEROUS)&quot;<br />
depends on ADFS_FS<br />
...<br />
<br />
For full documentation on the configuration files, see the file<br />
Documentation/kbuild/kconfig-language.txt.<br />
<br />
== Data structures ==<br />
<br />
Data structures that have visibility outside the single-threaded<br />
environment they are created and destroyed in should always have<br />
reference counts. In the kernel, garbage collection doesn't exist (and<br />
outside the kernel garbage collection is slow and inefficient), which<br />
means that you absolutely _have_ to reference count all your uses.<br />
<br />
Reference counting means that you can avoid locking, and allows multiple<br />
users to have access to the data structure in parallel - and not having<br />
to worry about the structure suddenly going away from under them just<br />
because they slept or did something else for a while.<br />
<br />
Note that locking is _not_ a replacement for reference counting.<br />
Locking is used to keep data structures coherent, while reference<br />
counting is a memory management technique. Usually both are needed, and<br />
they are not to be confused with each other.<br />
<br />
Many data structures can indeed have two levels of reference counting,<br />
when there are users of different &quot;classes&quot;. The subclass count counts<br />
the number of subclass users, and decrements the global count just once<br />
when the subclass count goes to zero.<br />
<br />
Examples of this kind of &quot;multi-level-reference-counting&quot; can be found in<br />
memory management (&quot;struct mm_struct&quot;: mm_users and mm_count), and in<br />
filesystem code (&quot;struct super_block&quot;: s_count and s_active).<br />
<br />
Remember: if another thread can find your data structure, and you don't<br />
have a reference count on it, you almost certainly have a bug.<br />
<br />
<br />
== Macros, Enums and RTL ==<br />
<br />
Names of macros defining constants and labels in enums are capitalized.<br />
<br />
#define CONSTANT 0x12345<br />
<br />
Enums are preferred when defining several related constants.<br />
<br />
CAPITALIZED macro names are appreciated but macros resembling functions<br />
may be named in lower case.<br />
<br />
Generally, inline functions are preferable to macros resembling functions.<br />
<br />
Macros with multiple statements should be enclosed in a do - while block:<br />
<br />
#define macrofun(a, b, c) \<br />
do { \<br />
if (a == 5) \<br />
do_this(b, c); \<br />
} while (0)<br />
<br />
Things to avoid when using macros:<br />
<br />
1) macros that affect control flow:<br />
<br />
#define FOO(x) \<br />
do { \<br />
if (blah(x) &lt; 0) \<br />
return -EBUGGERED; \<br />
} while(0)<br />
<br />
is a _very_ bad idea. It looks like a function call but exits the &quot;calling&quot;<br />
function; don't break the internal parsers of those who will read the code.<br />
<br />
2) macros that depend on having a local variable with a magic name:<br />
<br />
#define FOO(val) bar(index, val)<br />
<br />
might look like a good thing, but it's confusing as hell when one reads the<br />
code and it's prone to breakage from seemingly innocent changes.<br />
<br />
3) macros with arguments that are used as l-values: FOO(x) = y; will<br />
bite you if somebody e.g. turns FOO into an inline function.<br />
<br />
4) forgetting about precedence: macros defining constants using expressions<br />
must enclose the expression in parentheses. Beware of similar issues with<br />
macros using parameters.<br />
<br />
#define CONSTANT 0x4000<br />
#define CONSTEXP (CONSTANT | 3)<br />
<br />
The cpp manual deals with macros exhaustively. The gcc internals manual also<br />
covers RTL which is used frequently with assembly language in the kernel.<br />
<br />
== Printing kernel messages ==<br />
<br />
Kernel developers like to be seen as literate. Do mind the spelling<br />
of kernel messages to make a good impression. Do not use crippled<br />
words like &quot;dont&quot;; use &quot;do not&quot; or &quot;don't&quot; instead. Make the messages<br />
concise, clear, and unambiguous.<br />
<br />
Kernel messages do not have to be terminated with a period.<br />
<br />
Printing numbers in parentheses (%d) adds no value and should be avoided.<br />
<br />
There are a number of driver model diagnostic macros in &lt;linux/device.h&gt;<br />
which you should use to make sure messages are matched to the right device<br />
and driver, and are tagged with the right level: dev_err(), dev_warn(),<br />
dev_info(), and so forth. For messages that aren't associated with a<br />
particular device, &lt;linux/printk.h&gt; defines pr_debug() and pr_info().<br />
<br />
Coming up with good debugging messages can be quite a challenge; and once<br />
you have them, they can be a huge help for remote troubleshooting. Such<br />
messages should be compiled out when the DEBUG symbol is not defined (that<br />
is, by default they are not included). When you use dev_dbg() or pr_debug(),<br />
that's automatic. Many subsystems have Kconfig options to turn on -DDEBUG.<br />
A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to the<br />
ones already enabled by DEBUG.<br />
<br />
<br />
== Allocating memory ==<br />
<br />
The kernel provides the following general purpose memory allocators:<br />
kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and<br />
vzalloc(). Please refer to the API documentation for further information<br />
about them.<br />
<br />
The preferred form for passing a size of a struct is the following:<br />
<br />
p = kmalloc(sizeof(*p), ...);<br />
<br />
The alternative form where struct name is spelled out hurts readability and<br />
introduces an opportunity for a bug when the pointer variable type is changed<br />
but the corresponding sizeof that is passed to a memory allocator is not.<br />
<br />
Casting the return value which is a void pointer is redundant. The conversion<br />
from void pointer to any other pointer type is guaranteed by the C programming<br />
language.<br />
<br />
The preferred form for allocating an array is the following:<br />
<br />
p = kmalloc_array(n, sizeof(...), ...);<br />
<br />
The preferred form for allocating a zeroed array is the following:<br />
<br />
p = kcalloc(n, sizeof(...), ...);<br />
<br />
Both forms check for overflow on the allocation size n * sizeof(...),<br />
and return NULL if that occurred.<br />
<br />
== The inline disease ==<br />
<br />
There appears to be a common misperception that gcc has a magic &quot;make me<br />
faster&quot; speedup option called &quot;inline&quot;. While the use of inlines can be<br />
appropriate (for example as a means of replacing macros, see Chapter 12), it<br />
very often is not. Abundant use of the inline keyword leads to a much bigger<br />
kernel, which in turn slows the system as a whole down, due to a bigger<br />
icache footprint for the CPU and simply because there is less memory<br />
available for the pagecache. Just think about it; a pagecache miss causes a<br />
disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles<br />
that can go into these 5 milliseconds.<br />
<br />
A reasonable rule of thumb is to not put inline at functions that have more<br />
than 3 lines of code in them. An exception to this rule are the cases where<br />
a parameter is known to be a compiletime constant, and as a result of this<br />
constantness you *know* the compiler will be able to optimize most of your<br />
function away at compile time. For a good example of this later case, see<br />
the kmalloc() inline function.<br />
<br />
Often people argue that adding inline to functions that are static and used<br />
only once is always a win since there is no space tradeoff. While this is<br />
technically correct, gcc is capable of inlining these automatically without<br />
help, and the maintenance issue of removing the inline when a second user<br />
appears outweighs the potential value of the hint that tells gcc to do<br />
something it would have done anyway.<br />
<br />
<br />
== Function return values and names ==<br />
<br />
Functions can return values of many different kinds, and one of the<br />
most common is a value indicating whether the function succeeded or<br />
failed. Such a value can be represented as an error-code integer<br />
(-Exxx = failure, 0 = success) or a &quot;succeeded&quot; boolean (0 = failure,<br />
non-zero = success).<br />
<br />
Mixing up these two sorts of representations is a fertile source of<br />
difficult-to-find bugs. If the C language included a strong distinction<br />
between integers and booleans then the compiler would find these mistakes<br />
for us... but it doesn't. To help prevent such bugs, always follow this<br />
convention:<br />
<br />
If the name of a function is an action or an imperative command,<br />
the function should return an error-code integer. If the name<br />
is a predicate, the function should return a &quot;succeeded&quot; boolean.<br />
<br />
For example, &quot;add work&quot; is a command, and the add_work() function returns 0<br />
for success or -EBUSY for failure. In the same way, &quot;PCI device present&quot; is<br />
a predicate, and the pci_dev_present() function returns 1 if it succeeds in<br />
finding a matching device or 0 if it doesn't.<br />
<br />
All EXPORTed functions must respect this convention, and so should all<br />
public functions. Private (static) functions need not, but it is<br />
recommended that they do.<br />
<br />
Functions whose return value is the actual result of a computation, rather<br />
than an indication of whether the computation succeeded, are not subject to<br />
this rule. Generally they indicate failure by returning some out-of-range<br />
result. Typical examples would be functions that return pointers; they use<br />
NULL or the ERR_PTR mechanism to report failure.<br />
<br />
<br />
== Don't re-invent the kernel macros ==<br />
<br />
The header file include/linux/kernel.h contains a number of macros that<br />
you should use, rather than explicitly coding some variant of them yourself.<br />
For example, if you need to calculate the length of an array, take advantage<br />
of the macro<br />
<br />
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))<br />
<br />
Similarly, if you need to calculate the size of some structure member, use<br />
<br />
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)-&gt;f))<br />
<br />
There are also min() and max() macros that do strict type checking if you<br />
need them. Feel free to peruse that header file to see what else is already<br />
defined that you shouldn't reproduce in your code.<br />
<br />
<br />
== Editor modelines and other cruft ==<br />
<br />
Some editors can interpret configuration information embedded in source files,<br />
indicated with special markers. For example, emacs interprets lines marked<br />
like this:<br />
<br />
-*- mode: c -*-<br />
<br />
Or like this:<br />
<br />
/*<br />
Local Variables:<br />
compile-command: &quot;gcc -DMAGIC_DEBUG_FLAG foo.c&quot;<br />
End:<br />
*/<br />
<br />
Vim interprets markers that look like this:<br />
<br />
/* vim:set sw=8 noet */<br />
<br />
Do not include any of these in source files. People have their own personal<br />
editor configurations, and your source files should not override them. This<br />
includes markers for indentation and mode configuration. People may use their<br />
own custom mode, or may have some other magic method for making indentation<br />
work correctly.<br />
<br />
== Inline assembly ==<br />
<br />
In architecture-specific code, you may need to use inline assembly to interface<br />
with CPU or platform functionality. Don't hesitate to do so when necessary.<br />
However, don't use inline assembly gratuitously when C can do the job. You can<br />
and should poke hardware from C when possible.<br />
<br />
Consider writing simple helper functions that wrap common bits of inline<br />
assembly, rather than repeatedly writing them with slight variations. Remember<br />
that inline assembly can use C parameters.<br />
<br />
Large, non-trivial assembly functions should go in .S files, with corresponding<br />
C prototypes defined in C header files. The C prototypes for assembly<br />
functions should use &quot;asmlinkage&quot;.<br />
<br />
You may need to mark your asm statement as volatile, to prevent GCC from<br />
removing it if GCC doesn't notice any side effects. You don't always need to<br />
do so, though, and doing so unnecessarily can limit optimization.<br />
<br />
When writing a single inline assembly statement containing multiple<br />
instructions, put each instruction on a separate line in a separate quoted<br />
string, and end each string except the last with \n\t to properly indent the<br />
next instruction in the assembly output:<br />
<br />
asm (&quot;magic %reg1, #42\n\t&quot;<br />
&quot;more_magic %reg2, %reg3&quot;<br />
: /* outputs */ : /* inputs */ : /* clobbers */);<br />
<br />
== References ==<br />
<br />
The C Programming Language, Second Edition<br />
by Brian W. Kernighan and Dennis M. Ritchie.<br />
Prentice Hall, Inc., 1988.<br />
ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).<br />
URL: http://cm.bell-labs.com/cm/cs/cbook/<br />
<br />
The Practice of Programming<br />
by Brian W. Kernighan and Rob Pike.<br />
Addison-Wesley, Inc., 1999.<br />
ISBN 0-201-61586-X.<br />
URL: http://cm.bell-labs.com/cm/cs/tpop/<br />
<br />
GNU manuals - where in compliance with K&amp;R and this text - for cpp, gcc,<br />
gcc internals and indent, all available from http://www.gnu.org/manual/<br />
<br />
WG14 is the international standardization working group for the programming<br />
language C, URL: http://www.open-std.org/JTC1/SC22/WG14/<br />
<br />
Kernel CodingStyle, by greg@kroah.com at OLS 2002:<br />
http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/</div>Stepanhttp://www.coreboot.org/index.php?title=Coding_Style&diff=12316Coding Style2013-12-05T18:56:06Z<p>Stepan: /* Kconfig configuration files */</p>
<hr />
<div>This is a short document describing the preferred coding style for the<br />
coreboot project. It is in many ways exactly the same as the Linux kernel<br />
coding style. In fact, most of this document has been copied from the<br />
[http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/Documentation/CodingStyle?id=HEAD Linux kernel coding style]<br />
<br />
Please at least consider the points made here.<br />
<br />
First off, I'd suggest printing out a copy of the GNU coding standards,<br />
and NOT read it. Burn them, it's a great symbolic gesture.<br />
<br />
Anyway, here goes:<br />
<br />
<br />
== Indentation ==<br />
<br />
Tabs are 8 characters, and thus indentations are also 8 characters.<br />
There are heretic movements that try to make indentations 4 (or even 2!)<br />
characters deep, and that is akin to trying to define the value of PI to<br />
be 3.<br />
<br />
Rationale: The whole idea behind indentation is to clearly define where<br />
a block of control starts and ends. Especially when you've been looking<br />
at your screen for 20 straight hours, you'll find it a lot easier to see<br />
how the indentation works if you have large indentations.<br />
<br />
Now, some people will claim that having 8-character indentations makes<br />
the code move too far to the right, and makes it hard to read on a<br />
80-character terminal screen. The answer to that is that if you need<br />
more than 3 levels of indentation, you're screwed anyway, and should fix<br />
your program.<br />
<br />
In short, 8-char indents make things easier to read, and have the added<br />
benefit of warning you when you're nesting your functions too deep.<br />
Heed that warning.<br />
<br />
The preferred way to ease multiple indentation levels in a switch statement is<br />
to align the &quot;switch&quot; and its subordinate &quot;case&quot; labels in the same column<br />
instead of &quot;double-indenting&quot; the &quot;case&quot; labels. E.g.:<br />
<br />
switch (suffix) {<br />
case 'G':<br />
case 'g':<br />
mem &lt;&lt;= 30;<br />
break;<br />
case 'M':<br />
case 'm':<br />
mem &lt;&lt;= 20;<br />
break;<br />
case 'K':<br />
case 'k':<br />
mem &lt;&lt;= 10;<br />
/* fall through */<br />
default:<br />
break;<br />
}<br />
<br />
<br />
Don't put multiple statements on a single line unless you have<br />
something to hide:<br />
<br />
if (condition) do_this;<br />
do_something_everytime;<br />
<br />
Don't put multiple assignments on a single line either. Kernel coding style<br />
is super simple. Avoid tricky expressions.<br />
<br />
Outside of comments, documentation and except in Kconfig, spaces are never<br />
used for indentation, and the above example is deliberately broken.<br />
<br />
Get a decent editor and don't leave whitespace at the end of lines.<br />
<br />
== Breaking long lines and strings ==<br />
<br />
Coding style is all about readability and maintainability using commonly<br />
available tools.<br />
<br />
The limit on the length of lines is 80 columns and this is a strongly<br />
preferred limit.<br />
<br />
Statements longer than 80 columns will be broken into sensible chunks, unless<br />
exceeding 80 columns significantly increases readability and does not hide<br />
information. Descendants are always substantially shorter than the parent and<br />
are placed substantially to the right. The same applies to function headers<br />
with a long argument list. However, never break user-visible strings such as<br />
printk messages, because that breaks the ability to grep for them.<br />
<br />
<br />
== Placing Braces and Spaces ==<br />
<br />
The other issue that always comes up in C styling is the placement of<br />
braces. Unlike the indent size, there are few technical reasons to<br />
choose one placement strategy over the other, but the preferred way, as<br />
shown to us by the prophets Kernighan and Ritchie, is to put the opening<br />
brace last on the line, and put the closing brace first, thusly:<br />
<br />
if (x is true) {<br />
we do y<br />
}<br />
<br />
This applies to all non-function statement blocks (if, switch, for,<br />
while, do). E.g.:<br />
<br />
switch (action) {<br />
case KOBJ_ADD:<br />
return &quot;add&quot;;<br />
case KOBJ_REMOVE:<br />
return &quot;remove&quot;;<br />
case KOBJ_CHANGE:<br />
return &quot;change&quot;;<br />
default:<br />
return NULL;<br />
}<br />
<br />
However, there is one special case, namely functions: they have the<br />
opening brace at the beginning of the next line, thus:<br />
<br />
int function(int x)<br />
{<br />
body of function<br />
}<br />
<br />
Heretic people all over the world have claimed that this inconsistency<br />
is ... well ... inconsistent, but all right-thinking people know that<br />
(a) K&amp;R are _right_ and (b) K&amp;R are right. Besides, functions are<br />
special anyway (you can't nest them in C).<br />
<br />
Note that the closing brace is empty on a line of its own, _except_ in<br />
the cases where it is followed by a continuation of the same statement,<br />
ie a &quot;while&quot; in a do-statement or an &quot;else&quot; in an if-statement, like<br />
this:<br />
<br />
do {<br />
body of do-loop<br />
} while (condition);<br />
<br />
and<br />
<br />
if (x == y) {<br />
..<br />
} else if (x &gt; y) {<br />
...<br />
} else {<br />
....<br />
}<br />
<br />
Rationale: K&amp;R.<br />
<br />
Also, note that this brace-placement also minimizes the number of empty<br />
(or almost empty) lines, without any loss of readability. Thus, as the<br />
supply of new-lines on your screen is not a renewable resource (think<br />
25-line terminal screens here), you have more empty lines to put<br />
comments on.<br />
<br />
Do not unnecessarily use braces where a single statement will do.<br />
<br />
if (condition)<br />
action();<br />
<br />
and<br />
<br />
if (condition)<br />
do_this();<br />
else<br />
do_that();<br />
<br />
This does not apply if only one branch of a conditional statement is a single<br />
statement; in the latter case use braces in both branches:<br />
<br />
if (condition) {<br />
do_this();<br />
do_that();<br />
} else {<br />
otherwise();<br />
}<br />
<br />
=== Spaces ===<br />
<br />
Linux kernel style for use of spaces depends (mostly) on<br />
function-versus-keyword usage. Use a space after (most) keywords. The<br />
notable exceptions are sizeof, typeof, alignof, and __attribute__, which look<br />
somewhat like functions (and are usually used with parentheses in Linux,<br />
although they are not required in the language, as in: &quot;sizeof info&quot; after<br />
&quot;struct fileinfo info;&quot; is declared).<br />
<br />
So use a space after these keywords:<br />
if, switch, case, for, do, while<br />
but not with sizeof, typeof, alignof, or __attribute__. E.g.,<br />
s = sizeof(struct file);<br />
<br />
Do not add spaces around (inside) parenthesized expressions. This example is<br />
*bad*:<br />
<br />
s = sizeof( struct file );<br />
<br />
When declaring pointer data or a function that returns a pointer type, the<br />
preferred use of '*' is adjacent to the data name or function name and not<br />
adjacent to the type name. Examples:<br />
<br />
char *linux_banner;<br />
unsigned long long memparse(char *ptr, char **retptr);<br />
char *match_strdup(substring_t *s);<br />
<br />
Use one space around (on each side of) most binary and ternary operators,<br />
such as any of these:<br />
<br />
= + - &lt; &gt; * / % | &amp; ^ &lt;= &gt;= == != ? :<br />
<br />
but no space after unary operators:<br />
&amp; * + - ~ ! sizeof typeof alignof __attribute__ defined<br />
<br />
no space before the postfix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
no space after the prefix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
and no space around the '.' and &quot;-&gt;&quot; structure member operators.<br />
<br />
Do not leave trailing whitespace at the ends of lines. Some editors with<br />
&quot;smart&quot; indentation will insert whitespace at the beginning of new lines as<br />
appropriate, so you can start typing the next line of code right away.<br />
However, some such editors do not remove the whitespace if you end up not<br />
putting a line of code there, such as if you leave a blank line. As a result,<br />
you end up with lines containing trailing whitespace.<br />
<br />
Git will warn you about patches that introduce trailing whitespace, and can<br />
optionally strip the trailing whitespace for you; however, if applying a series<br />
of patches, this may make later patches in the series fail by changing their<br />
context lines.<br />
<br />
== Naming ==<br />
<br />
C is a Spartan language, and so should your naming be. Unlike Modula-2<br />
and Pascal programmers, C programmers do not use cute names like<br />
ThisVariableIsATemporaryCounter. A C programmer would call that<br />
variable &quot;tmp&quot;, which is much easier to write, and not the least more<br />
difficult to understand.<br />
<br />
HOWEVER, while mixed-case names are frowned upon, descriptive names for<br />
global variables are a must. To call a global function &quot;foo&quot; is a<br />
shooting offense.<br />
<br />
GLOBAL variables (to be used only if you _really_ need them) need to<br />
have descriptive names, as do global functions. If you have a function<br />
that counts the number of active users, you should call that<br />
&quot;count_active_users()&quot; or similar, you should _not_ call it &quot;cntusr()&quot;.<br />
<br />
Encoding the type of a function into the name (so-called Hungarian<br />
notation) is brain damaged - the compiler knows the types anyway and can<br />
check those, and it only confuses the programmer. No wonder MicroSoft<br />
makes buggy programs.<br />
<br />
LOCAL variable names should be short, and to the point. If you have<br />
some random integer loop counter, it should probably be called &quot;i&quot;.<br />
Calling it &quot;loop_counter&quot; is non-productive, if there is no chance of it<br />
being mis-understood. Similarly, &quot;tmp&quot; can be just about any type of<br />
variable that is used to hold a temporary value.<br />
<br />
If you are afraid to mix up your local variable names, you have another<br />
problem, which is called the function-growth-hormone-imbalance syndrome.<br />
See chapter 6 (Functions).<br />
<br />
<br />
== Typedefs ==<br />
<br />
Please don't use things like &quot;vps_t&quot;.<br />
<br />
It's a _mistake_ to use typedef for structures and pointers. When you see a<br />
<br />
vps_t a;<br />
<br />
in the source, what does it mean?<br />
<br />
In contrast, if it says<br />
<br />
struct virtual_container *a;<br />
<br />
you can actually tell what &quot;a&quot; is.<br />
<br />
Lots of people think that typedefs &quot;help readability&quot;. Not so. They are<br />
useful only for:<br />
<br />
(a) totally opaque objects (where the typedef is actively used to _hide_ what the object is).<br />
<br />
Example: &quot;pte_t&quot; etc. opaque objects that you can only access using<br />
the proper accessor functions.<br />
<br />
NOTE! Opaqueness and &quot;accessor functions&quot; are not good in themselves.<br />
The reason we have them for things like pte_t etc. is that there<br />
really is absolutely _zero_ portably accessible information there.<br />
<br />
(b) Clear integer types, where the abstraction _helps_ avoid confusion<br />
whether it is &quot;int&quot; or &quot;long&quot;.<br />
<br />
u8/u16/u32 are perfectly fine typedefs, although they fit into<br />
category (d) better than here.<br />
<br />
NOTE! Again - there needs to be a _reason_ for this. If something is<br />
&quot;unsigned long&quot;, then there's no reason to do<br />
<br />
typedef unsigned long myflags_t;<br />
<br />
but if there is a clear reason for why it under certain circumstances<br />
might be an &quot;unsigned int&quot; and under other configurations might be<br />
&quot;unsigned long&quot;, then by all means go ahead and use a typedef.<br />
<br />
(c) when you use sparse to literally create a _new_ type for<br />
type-checking.<br />
<br />
(d) New types which are identical to standard C99 types, in certain<br />
exceptional circumstances.<br />
<br />
Although it would only take a short amount of time for the eyes and<br />
brain to become accustomed to the standard types like 'uint32_t',<br />
some people object to their use anyway.<br />
<br />
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their<br />
signed equivalents which are identical to standard types are<br />
permitted -- although they are not mandatory in new code of your<br />
own.<br />
<br />
When editing existing code which already uses one or the other set<br />
of types, you should conform to the existing choices in that code.<br />
<br />
(e) Types safe for use in userspace.<br />
<br />
In certain structures which are visible to userspace, we cannot<br />
require C99 types and cannot use the 'u32' form above. Thus, we<br />
use __u32 and similar types in all structures which are shared<br />
with userspace.<br />
<br />
Maybe there are other cases too, but the rule should basically be to NEVER<br />
EVER use a typedef unless you can clearly match one of those rules.<br />
<br />
<br />
In general, a pointer, or a struct that has elements that can reasonably<br />
be directly accessed should _never_ be a typedef.<br />
<br />
== Functions ==<br />
<br />
Functions should be short and sweet, and do just one thing. They should<br />
fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,<br />
as we all know), and do one thing and do that well.<br />
<br />
The maximum length of a function is inversely proportional to the<br />
complexity and indentation level of that function. So, if you have a<br />
conceptually simple function that is just one long (but simple)<br />
case-statement, where you have to do lots of small things for a lot of<br />
different cases, it's OK to have a longer function.<br />
<br />
However, if you have a complex function, and you suspect that a<br />
less-than-gifted first-year high-school student might not even<br />
understand what the function is all about, you should adhere to the<br />
maximum limits all the more closely. Use helper functions with<br />
descriptive names (you can ask the compiler to in-line them if you think<br />
it's performance-critical, and it will probably do a better job of it<br />
than you would have done).<br />
<br />
Another measure of the function is the number of local variables. They<br />
shouldn't exceed 5-10, or you're doing something wrong. Re-think the<br />
function, and split it into smaller pieces. A human brain can<br />
generally easily keep track of about 7 different things, anything more<br />
and it gets confused. You know you're brilliant, but maybe you'd like<br />
to understand what you did 2 weeks from now.<br />
<br />
In source files, separate functions with one blank line. If the function is<br />
exported, the EXPORT* macro for it should follow immediately after the closing<br />
function brace line. E.g.:<br />
<br />
int system_is_up(void)<br />
{<br />
return system_state == SYSTEM_RUNNING;<br />
}<br />
EXPORT_SYMBOL(system_is_up);<br />
<br />
In function prototypes, include parameter names with their data types.<br />
Although this is not required by the C language, it is preferred in Linux<br />
because it is a simple way to add valuable information for the reader.<br />
<br />
== Centralized exiting of functions ==<br />
<br />
Albeit deprecated by some people, the equivalent of the goto statement is<br />
used frequently by compilers in form of the unconditional jump instruction.<br />
<br />
The goto statement comes in handy when a function exits from multiple<br />
locations and some common work such as cleanup has to be done. If there is no<br />
cleanup needed then just return directly.<br />
<br />
The rationale is:<br />
<br />
* unconditional statements are easier to understand and follow<br />
* nesting is reduced<br />
* errors by not updating individual exit points when making modifications are prevented<br />
* saves the compiler work to optimize redundant code away ;)<br />
<br />
int fun(int a)<br />
{<br />
int result = 0;<br />
char *buffer = kmalloc(SIZE);<br />
<br />
if (buffer == NULL)<br />
return -ENOMEM;<br />
<br />
if (condition1) {<br />
while (loop1) {<br />
...<br />
}<br />
result = 1;<br />
goto out;<br />
}<br />
...<br />
out:<br />
kfree(buffer);<br />
return result;<br />
}<br />
<br />
== Commenting ==<br />
<br />
Comments are good, but there is also a danger of over-commenting. NEVER<br />
try to explain HOW your code works in a comment: it's much better to<br />
write the code so that the _working_ is obvious, and it's a waste of<br />
time to explain badly written code.<br />
<br />
Generally, you want your comments to tell WHAT your code does, not HOW.<br />
Also, try to avoid putting comments inside a function body: if the<br />
function is so complex that you need to separately comment parts of it,<br />
you should probably go back to chapter 6 for a while. You can make<br />
small comments to note or warn about something particularly clever (or<br />
ugly), but try to avoid excess. Instead, put the comments at the head<br />
of the function, telling people what it does, and possibly WHY it does<br />
it.<br />
<br />
When commenting the kernel API functions, please use the kernel-doc format.<br />
See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc<br />
for details.<br />
<br />
coreboot style for comments is the C89 &quot;/* ... */&quot; style.<br />
You may use C99-style &quot;// ...&quot; comments.<br />
<br />
The preferred style for long (multi-line) comments is:<br />
<br />
/*<br />
* This is the preferred style for multi-line<br />
* comments in the Linux kernel source code.<br />
* Please use it consistently.<br />
*<br />
* Description: A column of asterisks on the left side,<br />
* with beginning and ending almost-blank lines.<br />
*/<br />
<br />
For files in net/ and drivers/net/ the preferred style for long (multi-line)<br />
comments is a little different.<br />
<br />
/* The preferred comment style for files in net/ and drivers/net<br />
* looks like this.<br />
*<br />
* It is nearly the same as the generally preferred comment style,<br />
* but there is no initial almost-blank line.<br />
*/<br />
<br />
It's also important to comment data, whether they are basic types or derived<br />
types. To this end, use just one data declaration per line (no commas for<br />
multiple data declarations). This leaves you room for a small comment on each<br />
item, explaining its use.<br />
<br />
== You've made a mess of it ==<br />
<br />
That's OK, we all do. You've probably been told by your long-time Unix<br />
user helper that &quot;GNU emacs&quot; automatically formats the C sources for<br />
you, and you've noticed that yes, it does do that, but the defaults it<br />
uses are less than desirable (in fact, they are worse than random<br />
typing - an infinite number of monkeys typing into GNU emacs would never<br />
make a good program).<br />
<br />
So, you can either get rid of GNU emacs, or change it to use saner<br />
values. To do the latter, you can stick the following in your .emacs file:<br />
<br />
(defun c-lineup-arglist-tabs-only (ignored)<br />
&quot;Line up argument lists by tabs, not spaces&quot;<br />
(let* ((anchor (c-langelem-pos c-syntactic-element))<br />
(column (c-langelem-2nd-pos c-syntactic-element))<br />
(offset (- (1+ column) anchor))<br />
(steps (floor offset c-basic-offset)))<br />
(* (max steps 1)<br />
c-basic-offset)))<br />
<br />
(add-hook 'c-mode-common-hook<br />
(lambda ()<br />
;; Add kernel style<br />
(c-add-style<br />
&quot;linux-tabs-only&quot;<br />
'(&quot;linux&quot; (c-offsets-alist<br />
(arglist-cont-nonempty<br />
c-lineup-gcc-asm-reg<br />
c-lineup-arglist-tabs-only))))))<br />
<br />
(add-hook 'c-mode-hook<br />
(lambda ()<br />
(let ((filename (buffer-file-name)))<br />
;; Enable kernel mode for the appropriate files<br />
(when (and filename<br />
(string-match (expand-file-name &quot;~/src/linux-trees&quot;)<br />
filename))<br />
(setq indent-tabs-mode t)<br />
(c-set-style &quot;linux-tabs-only&quot;)))))<br />
<br />
This will make emacs go better with the kernel coding style for C<br />
files below ~/src/linux-trees.<br />
<br />
But even if you fail in getting emacs to do sane formatting, not<br />
everything is lost: use &quot;indent&quot;.<br />
<br />
Now, again, GNU indent has the same brain-dead settings that GNU emacs<br />
has, which is why you need to give it a few command line options.<br />
However, that's not too bad, because even the makers of GNU indent<br />
recognize the authority of K&amp;R (the GNU people aren't evil, they are<br />
just severely misguided in this matter), so you just give indent the<br />
options &quot;-kr -i8&quot; (stands for &quot;K&amp;R, 8 character indents&quot;), or use<br />
&quot;scripts/Lindent&quot;, which indents in the latest style.<br />
<br />
&quot;indent&quot; has a lot of options, and especially when it comes to comment<br />
re-formatting you may want to take a look at the man page. But<br />
remember: &quot;indent&quot; is not a fix for bad programming.<br />
<br />
<br />
== Kconfig configuration files ==<br />
<br />
For all of the Kconfig* configuration files throughout the source tree,<br />
the indentation is somewhat different. Lines under a &quot;config&quot; definition<br />
are indented with one tab, while help text is indented an additional two<br />
spaces. Example:<br />
<br />
config AUDIT<br />
bool &quot;Auditing support&quot;<br />
depends on NET<br />
help<br />
Enable auditing infrastructure that can be used with another<br />
kernel subsystem, such as SELinux (which requires this for<br />
logging of avc messages output). Does not do system-call<br />
auditing without CONFIG_AUDITSYSCALL.<br />
<br />
Seriously dangerous features (such as write support for certain<br />
filesystems) should advertise this prominently in their prompt string:<br />
<br />
config ADFS_FS_RW<br />
bool &quot;ADFS write support (DANGEROUS)&quot;<br />
depends on ADFS_FS<br />
...<br />
<br />
For full documentation on the configuration files, see the file<br />
Documentation/kbuild/kconfig-language.txt.<br />
<br />
== Data structures ==<br />
<br />
Data structures that have visibility outside the single-threaded<br />
environment they are created and destroyed in should always have<br />
reference counts. In the kernel, garbage collection doesn't exist (and<br />
outside the kernel garbage collection is slow and inefficient), which<br />
means that you absolutely _have_ to reference count all your uses.<br />
<br />
Reference counting means that you can avoid locking, and allows multiple<br />
users to have access to the data structure in parallel - and not having<br />
to worry about the structure suddenly going away from under them just<br />
because they slept or did something else for a while.<br />
<br />
Note that locking is _not_ a replacement for reference counting.<br />
Locking is used to keep data structures coherent, while reference<br />
counting is a memory management technique. Usually both are needed, and<br />
they are not to be confused with each other.<br />
<br />
Many data structures can indeed have two levels of reference counting,<br />
when there are users of different &quot;classes&quot;. The subclass count counts<br />
the number of subclass users, and decrements the global count just once<br />
when the subclass count goes to zero.<br />
<br />
Examples of this kind of &quot;multi-level-reference-counting&quot; can be found in<br />
memory management (&quot;struct mm_struct&quot;: mm_users and mm_count), and in<br />
filesystem code (&quot;struct super_block&quot;: s_count and s_active).<br />
<br />
Remember: if another thread can find your data structure, and you don't<br />
have a reference count on it, you almost certainly have a bug.<br />
<br />
<br />
== Macros, Enums and RTL ==<br />
<br />
Names of macros defining constants and labels in enums are capitalized.<br />
<br />
#define CONSTANT 0x12345<br />
<br />
Enums are preferred when defining several related constants.<br />
<br />
CAPITALIZED macro names are appreciated but macros resembling functions<br />
may be named in lower case.<br />
<br />
Generally, inline functions are preferable to macros resembling functions.<br />
<br />
Macros with multiple statements should be enclosed in a do - while block:<br />
<br />
#define macrofun(a, b, c) \<br />
do { \<br />
if (a == 5) \<br />
do_this(b, c); \<br />
} while (0)<br />
<br />
Things to avoid when using macros:<br />
<br />
1) macros that affect control flow:<br />
<br />
#define FOO(x) \<br />
do { \<br />
if (blah(x) &lt; 0) \<br />
return -EBUGGERED; \<br />
} while(0)<br />
<br />
is a _very_ bad idea. It looks like a function call but exits the &quot;calling&quot;<br />
function; don't break the internal parsers of those who will read the code.<br />
<br />
2) macros that depend on having a local variable with a magic name:<br />
<br />
#define FOO(val) bar(index, val)<br />
<br />
might look like a good thing, but it's confusing as hell when one reads the<br />
code and it's prone to breakage from seemingly innocent changes.<br />
<br />
3) macros with arguments that are used as l-values: FOO(x) = y; will<br />
bite you if somebody e.g. turns FOO into an inline function.<br />
<br />
4) forgetting about precedence: macros defining constants using expressions<br />
must enclose the expression in parentheses. Beware of similar issues with<br />
macros using parameters.<br />
<br />
#define CONSTANT 0x4000<br />
#define CONSTEXP (CONSTANT | 3)<br />
<br />
The cpp manual deals with macros exhaustively. The gcc internals manual also<br />
covers RTL which is used frequently with assembly language in the kernel.<br />
<br />
== Printing kernel messages ==<br />
<br />
Kernel developers like to be seen as literate. Do mind the spelling<br />
of kernel messages to make a good impression. Do not use crippled<br />
words like &quot;dont&quot;; use &quot;do not&quot; or &quot;don't&quot; instead. Make the messages<br />
concise, clear, and unambiguous.<br />
<br />
Kernel messages do not have to be terminated with a period.<br />
<br />
Printing numbers in parentheses (%d) adds no value and should be avoided.<br />
<br />
There are a number of driver model diagnostic macros in &lt;linux/device.h&gt;<br />
which you should use to make sure messages are matched to the right device<br />
and driver, and are tagged with the right level: dev_err(), dev_warn(),<br />
dev_info(), and so forth. For messages that aren't associated with a<br />
particular device, &lt;linux/printk.h&gt; defines pr_debug() and pr_info().<br />
<br />
Coming up with good debugging messages can be quite a challenge; and once<br />
you have them, they can be a huge help for remote troubleshooting. Such<br />
messages should be compiled out when the DEBUG symbol is not defined (that<br />
is, by default they are not included). When you use dev_dbg() or pr_debug(),<br />
that's automatic. Many subsystems have Kconfig options to turn on -DDEBUG.<br />
A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to the<br />
ones already enabled by DEBUG.<br />
<br />
<br />
== Allocating memory ==<br />
<br />
The kernel provides the following general purpose memory allocators:<br />
kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and<br />
vzalloc(). Please refer to the API documentation for further information<br />
about them.<br />
<br />
The preferred form for passing a size of a struct is the following:<br />
<br />
p = kmalloc(sizeof(*p), ...);<br />
<br />
The alternative form where struct name is spelled out hurts readability and<br />
introduces an opportunity for a bug when the pointer variable type is changed<br />
but the corresponding sizeof that is passed to a memory allocator is not.<br />
<br />
Casting the return value which is a void pointer is redundant. The conversion<br />
from void pointer to any other pointer type is guaranteed by the C programming<br />
language.<br />
<br />
The preferred form for allocating an array is the following:<br />
<br />
p = kmalloc_array(n, sizeof(...), ...);<br />
<br />
The preferred form for allocating a zeroed array is the following:<br />
<br />
p = kcalloc(n, sizeof(...), ...);<br />
<br />
Both forms check for overflow on the allocation size n * sizeof(...),<br />
and return NULL if that occurred.<br />
<br />
== The inline disease ==<br />
<br />
There appears to be a common misperception that gcc has a magic &quot;make me<br />
faster&quot; speedup option called &quot;inline&quot;. While the use of inlines can be<br />
appropriate (for example as a means of replacing macros, see Chapter 12), it<br />
very often is not. Abundant use of the inline keyword leads to a much bigger<br />
kernel, which in turn slows the system as a whole down, due to a bigger<br />
icache footprint for the CPU and simply because there is less memory<br />
available for the pagecache. Just think about it; a pagecache miss causes a<br />
disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles<br />
that can go into these 5 milliseconds.<br />
<br />
A reasonable rule of thumb is to not put inline at functions that have more<br />
than 3 lines of code in them. An exception to this rule are the cases where<br />
a parameter is known to be a compiletime constant, and as a result of this<br />
constantness you *know* the compiler will be able to optimize most of your<br />
function away at compile time. For a good example of this later case, see<br />
the kmalloc() inline function.<br />
<br />
Often people argue that adding inline to functions that are static and used<br />
only once is always a win since there is no space tradeoff. While this is<br />
technically correct, gcc is capable of inlining these automatically without<br />
help, and the maintenance issue of removing the inline when a second user<br />
appears outweighs the potential value of the hint that tells gcc to do<br />
something it would have done anyway.<br />
<br />
<br />
== Function return values and names ==<br />
<br />
Functions can return values of many different kinds, and one of the<br />
most common is a value indicating whether the function succeeded or<br />
failed. Such a value can be represented as an error-code integer<br />
(-Exxx = failure, 0 = success) or a &quot;succeeded&quot; boolean (0 = failure,<br />
non-zero = success).<br />
<br />
Mixing up these two sorts of representations is a fertile source of<br />
difficult-to-find bugs. If the C language included a strong distinction<br />
between integers and booleans then the compiler would find these mistakes<br />
for us... but it doesn't. To help prevent such bugs, always follow this<br />
convention:<br />
<br />
If the name of a function is an action or an imperative command,<br />
the function should return an error-code integer. If the name<br />
is a predicate, the function should return a &quot;succeeded&quot; boolean.<br />
<br />
For example, &quot;add work&quot; is a command, and the add_work() function returns 0<br />
for success or -EBUSY for failure. In the same way, &quot;PCI device present&quot; is<br />
a predicate, and the pci_dev_present() function returns 1 if it succeeds in<br />
finding a matching device or 0 if it doesn't.<br />
<br />
All EXPORTed functions must respect this convention, and so should all<br />
public functions. Private (static) functions need not, but it is<br />
recommended that they do.<br />
<br />
Functions whose return value is the actual result of a computation, rather<br />
than an indication of whether the computation succeeded, are not subject to<br />
this rule. Generally they indicate failure by returning some out-of-range<br />
result. Typical examples would be functions that return pointers; they use<br />
NULL or the ERR_PTR mechanism to report failure.<br />
<br />
<br />
== Don't re-invent the kernel macros ==<br />
<br />
The header file include/linux/kernel.h contains a number of macros that<br />
you should use, rather than explicitly coding some variant of them yourself.<br />
For example, if you need to calculate the length of an array, take advantage<br />
of the macro<br />
<br />
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))<br />
<br />
Similarly, if you need to calculate the size of some structure member, use<br />
<br />
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)-&gt;f))<br />
<br />
There are also min() and max() macros that do strict type checking if you<br />
need them. Feel free to peruse that header file to see what else is already<br />
defined that you shouldn't reproduce in your code.<br />
<br />
<br />
== Editor modelines and other cruft ==<br />
<br />
Some editors can interpret configuration information embedded in source files,<br />
indicated with special markers. For example, emacs interprets lines marked<br />
like this:<br />
<br />
-*- mode: c -*-<br />
<br />
Or like this:<br />
<br />
/*<br />
Local Variables:<br />
compile-command: &quot;gcc -DMAGIC_DEBUG_FLAG foo.c&quot;<br />
End:<br />
*/<br />
<br />
Vim interprets markers that look like this:<br />
<br />
/* vim:set sw=8 noet */<br />
<br />
Do not include any of these in source files. People have their own personal<br />
editor configurations, and your source files should not override them. This<br />
includes markers for indentation and mode configuration. People may use their<br />
own custom mode, or may have some other magic method for making indentation<br />
work correctly.<br />
<br />
== Inline assembly ==<br />
<br />
In architecture-specific code, you may need to use inline assembly to interface<br />
with CPU or platform functionality. Don't hesitate to do so when necessary.<br />
However, don't use inline assembly gratuitously when C can do the job. You can<br />
and should poke hardware from C when possible.<br />
<br />
Consider writing simple helper functions that wrap common bits of inline<br />
assembly, rather than repeatedly writing them with slight variations. Remember<br />
that inline assembly can use C parameters.<br />
<br />
Large, non-trivial assembly functions should go in .S files, with corresponding<br />
C prototypes defined in C header files. The C prototypes for assembly<br />
functions should use &quot;asmlinkage&quot;.<br />
<br />
You may need to mark your asm statement as volatile, to prevent GCC from<br />
removing it if GCC doesn't notice any side effects. You don't always need to<br />
do so, though, and doing so unnecessarily can limit optimization.<br />
<br />
When writing a single inline assembly statement containing multiple<br />
instructions, put each instruction on a separate line in a separate quoted<br />
string, and end each string except the last with \n\t to properly indent the<br />
next instruction in the assembly output:<br />
<br />
asm (&quot;magic %reg1, #42\n\t&quot;<br />
&quot;more_magic %reg2, %reg3&quot;<br />
: /* outputs */ : /* inputs */ : /* clobbers */);<br />
<br />
== References ==<br />
<br />
The C Programming Language, Second Edition<br />
by Brian W. Kernighan and Dennis M. Ritchie.<br />
Prentice Hall, Inc., 1988.<br />
ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).<br />
URL: http://cm.bell-labs.com/cm/cs/cbook/<br />
<br />
The Practice of Programming<br />
by Brian W. Kernighan and Rob Pike.<br />
Addison-Wesley, Inc., 1999.<br />
ISBN 0-201-61586-X.<br />
URL: http://cm.bell-labs.com/cm/cs/tpop/<br />
<br />
GNU manuals - where in compliance with K&amp;R and this text - for cpp, gcc,<br />
gcc internals and indent, all available from http://www.gnu.org/manual/<br />
<br />
WG14 is the international standardization working group for the programming<br />
language C, URL: http://www.open-std.org/JTC1/SC22/WG14/<br />
<br />
Kernel CodingStyle, by greg@kroah.com at OLS 2002:<br />
http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/</div>Stepanhttp://www.coreboot.org/index.php?title=Coding_Style&diff=12315Coding Style2013-12-05T18:55:27Z<p>Stepan: /* Macros, Enums and RTL */</p>
<hr />
<div>This is a short document describing the preferred coding style for the<br />
coreboot project. It is in many ways exactly the same as the Linux kernel<br />
coding style. In fact, most of this document has been copied from the<br />
[http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/Documentation/CodingStyle?id=HEAD Linux kernel coding style]<br />
<br />
Please at least consider the points made here.<br />
<br />
First off, I'd suggest printing out a copy of the GNU coding standards,<br />
and NOT read it. Burn them, it's a great symbolic gesture.<br />
<br />
Anyway, here goes:<br />
<br />
<br />
== Indentation ==<br />
<br />
Tabs are 8 characters, and thus indentations are also 8 characters.<br />
There are heretic movements that try to make indentations 4 (or even 2!)<br />
characters deep, and that is akin to trying to define the value of PI to<br />
be 3.<br />
<br />
Rationale: The whole idea behind indentation is to clearly define where<br />
a block of control starts and ends. Especially when you've been looking<br />
at your screen for 20 straight hours, you'll find it a lot easier to see<br />
how the indentation works if you have large indentations.<br />
<br />
Now, some people will claim that having 8-character indentations makes<br />
the code move too far to the right, and makes it hard to read on a<br />
80-character terminal screen. The answer to that is that if you need<br />
more than 3 levels of indentation, you're screwed anyway, and should fix<br />
your program.<br />
<br />
In short, 8-char indents make things easier to read, and have the added<br />
benefit of warning you when you're nesting your functions too deep.<br />
Heed that warning.<br />
<br />
The preferred way to ease multiple indentation levels in a switch statement is<br />
to align the &quot;switch&quot; and its subordinate &quot;case&quot; labels in the same column<br />
instead of &quot;double-indenting&quot; the &quot;case&quot; labels. E.g.:<br />
<br />
switch (suffix) {<br />
case 'G':<br />
case 'g':<br />
mem &lt;&lt;= 30;<br />
break;<br />
case 'M':<br />
case 'm':<br />
mem &lt;&lt;= 20;<br />
break;<br />
case 'K':<br />
case 'k':<br />
mem &lt;&lt;= 10;<br />
/* fall through */<br />
default:<br />
break;<br />
}<br />
<br />
<br />
Don't put multiple statements on a single line unless you have<br />
something to hide:<br />
<br />
if (condition) do_this;<br />
do_something_everytime;<br />
<br />
Don't put multiple assignments on a single line either. Kernel coding style<br />
is super simple. Avoid tricky expressions.<br />
<br />
Outside of comments, documentation and except in Kconfig, spaces are never<br />
used for indentation, and the above example is deliberately broken.<br />
<br />
Get a decent editor and don't leave whitespace at the end of lines.<br />
<br />
== Breaking long lines and strings ==<br />
<br />
Coding style is all about readability and maintainability using commonly<br />
available tools.<br />
<br />
The limit on the length of lines is 80 columns and this is a strongly<br />
preferred limit.<br />
<br />
Statements longer than 80 columns will be broken into sensible chunks, unless<br />
exceeding 80 columns significantly increases readability and does not hide<br />
information. Descendants are always substantially shorter than the parent and<br />
are placed substantially to the right. The same applies to function headers<br />
with a long argument list. However, never break user-visible strings such as<br />
printk messages, because that breaks the ability to grep for them.<br />
<br />
<br />
== Placing Braces and Spaces ==<br />
<br />
The other issue that always comes up in C styling is the placement of<br />
braces. Unlike the indent size, there are few technical reasons to<br />
choose one placement strategy over the other, but the preferred way, as<br />
shown to us by the prophets Kernighan and Ritchie, is to put the opening<br />
brace last on the line, and put the closing brace first, thusly:<br />
<br />
if (x is true) {<br />
we do y<br />
}<br />
<br />
This applies to all non-function statement blocks (if, switch, for,<br />
while, do). E.g.:<br />
<br />
switch (action) {<br />
case KOBJ_ADD:<br />
return &quot;add&quot;;<br />
case KOBJ_REMOVE:<br />
return &quot;remove&quot;;<br />
case KOBJ_CHANGE:<br />
return &quot;change&quot;;<br />
default:<br />
return NULL;<br />
}<br />
<br />
However, there is one special case, namely functions: they have the<br />
opening brace at the beginning of the next line, thus:<br />
<br />
int function(int x)<br />
{<br />
body of function<br />
}<br />
<br />
Heretic people all over the world have claimed that this inconsistency<br />
is ... well ... inconsistent, but all right-thinking people know that<br />
(a) K&amp;R are _right_ and (b) K&amp;R are right. Besides, functions are<br />
special anyway (you can't nest them in C).<br />
<br />
Note that the closing brace is empty on a line of its own, _except_ in<br />
the cases where it is followed by a continuation of the same statement,<br />
ie a &quot;while&quot; in a do-statement or an &quot;else&quot; in an if-statement, like<br />
this:<br />
<br />
do {<br />
body of do-loop<br />
} while (condition);<br />
<br />
and<br />
<br />
if (x == y) {<br />
..<br />
} else if (x &gt; y) {<br />
...<br />
} else {<br />
....<br />
}<br />
<br />
Rationale: K&amp;R.<br />
<br />
Also, note that this brace-placement also minimizes the number of empty<br />
(or almost empty) lines, without any loss of readability. Thus, as the<br />
supply of new-lines on your screen is not a renewable resource (think<br />
25-line terminal screens here), you have more empty lines to put<br />
comments on.<br />
<br />
Do not unnecessarily use braces where a single statement will do.<br />
<br />
if (condition)<br />
action();<br />
<br />
and<br />
<br />
if (condition)<br />
do_this();<br />
else<br />
do_that();<br />
<br />
This does not apply if only one branch of a conditional statement is a single<br />
statement; in the latter case use braces in both branches:<br />
<br />
if (condition) {<br />
do_this();<br />
do_that();<br />
} else {<br />
otherwise();<br />
}<br />
<br />
=== Spaces ===<br />
<br />
Linux kernel style for use of spaces depends (mostly) on<br />
function-versus-keyword usage. Use a space after (most) keywords. The<br />
notable exceptions are sizeof, typeof, alignof, and __attribute__, which look<br />
somewhat like functions (and are usually used with parentheses in Linux,<br />
although they are not required in the language, as in: &quot;sizeof info&quot; after<br />
&quot;struct fileinfo info;&quot; is declared).<br />
<br />
So use a space after these keywords:<br />
if, switch, case, for, do, while<br />
but not with sizeof, typeof, alignof, or __attribute__. E.g.,<br />
s = sizeof(struct file);<br />
<br />
Do not add spaces around (inside) parenthesized expressions. This example is<br />
*bad*:<br />
<br />
s = sizeof( struct file );<br />
<br />
When declaring pointer data or a function that returns a pointer type, the<br />
preferred use of '*' is adjacent to the data name or function name and not<br />
adjacent to the type name. Examples:<br />
<br />
char *linux_banner;<br />
unsigned long long memparse(char *ptr, char **retptr);<br />
char *match_strdup(substring_t *s);<br />
<br />
Use one space around (on each side of) most binary and ternary operators,<br />
such as any of these:<br />
<br />
= + - &lt; &gt; * / % | &amp; ^ &lt;= &gt;= == != ? :<br />
<br />
but no space after unary operators:<br />
&amp; * + - ~ ! sizeof typeof alignof __attribute__ defined<br />
<br />
no space before the postfix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
no space after the prefix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
and no space around the '.' and &quot;-&gt;&quot; structure member operators.<br />
<br />
Do not leave trailing whitespace at the ends of lines. Some editors with<br />
&quot;smart&quot; indentation will insert whitespace at the beginning of new lines as<br />
appropriate, so you can start typing the next line of code right away.<br />
However, some such editors do not remove the whitespace if you end up not<br />
putting a line of code there, such as if you leave a blank line. As a result,<br />
you end up with lines containing trailing whitespace.<br />
<br />
Git will warn you about patches that introduce trailing whitespace, and can<br />
optionally strip the trailing whitespace for you; however, if applying a series<br />
of patches, this may make later patches in the series fail by changing their<br />
context lines.<br />
<br />
== Naming ==<br />
<br />
C is a Spartan language, and so should your naming be. Unlike Modula-2<br />
and Pascal programmers, C programmers do not use cute names like<br />
ThisVariableIsATemporaryCounter. A C programmer would call that<br />
variable &quot;tmp&quot;, which is much easier to write, and not the least more<br />
difficult to understand.<br />
<br />
HOWEVER, while mixed-case names are frowned upon, descriptive names for<br />
global variables are a must. To call a global function &quot;foo&quot; is a<br />
shooting offense.<br />
<br />
GLOBAL variables (to be used only if you _really_ need them) need to<br />
have descriptive names, as do global functions. If you have a function<br />
that counts the number of active users, you should call that<br />
&quot;count_active_users()&quot; or similar, you should _not_ call it &quot;cntusr()&quot;.<br />
<br />
Encoding the type of a function into the name (so-called Hungarian<br />
notation) is brain damaged - the compiler knows the types anyway and can<br />
check those, and it only confuses the programmer. No wonder MicroSoft<br />
makes buggy programs.<br />
<br />
LOCAL variable names should be short, and to the point. If you have<br />
some random integer loop counter, it should probably be called &quot;i&quot;.<br />
Calling it &quot;loop_counter&quot; is non-productive, if there is no chance of it<br />
being mis-understood. Similarly, &quot;tmp&quot; can be just about any type of<br />
variable that is used to hold a temporary value.<br />
<br />
If you are afraid to mix up your local variable names, you have another<br />
problem, which is called the function-growth-hormone-imbalance syndrome.<br />
See chapter 6 (Functions).<br />
<br />
<br />
== Typedefs ==<br />
<br />
Please don't use things like &quot;vps_t&quot;.<br />
<br />
It's a _mistake_ to use typedef for structures and pointers. When you see a<br />
<br />
vps_t a;<br />
<br />
in the source, what does it mean?<br />
<br />
In contrast, if it says<br />
<br />
struct virtual_container *a;<br />
<br />
you can actually tell what &quot;a&quot; is.<br />
<br />
Lots of people think that typedefs &quot;help readability&quot;. Not so. They are<br />
useful only for:<br />
<br />
(a) totally opaque objects (where the typedef is actively used to _hide_ what the object is).<br />
<br />
Example: &quot;pte_t&quot; etc. opaque objects that you can only access using<br />
the proper accessor functions.<br />
<br />
NOTE! Opaqueness and &quot;accessor functions&quot; are not good in themselves.<br />
The reason we have them for things like pte_t etc. is that there<br />
really is absolutely _zero_ portably accessible information there.<br />
<br />
(b) Clear integer types, where the abstraction _helps_ avoid confusion<br />
whether it is &quot;int&quot; or &quot;long&quot;.<br />
<br />
u8/u16/u32 are perfectly fine typedefs, although they fit into<br />
category (d) better than here.<br />
<br />
NOTE! Again - there needs to be a _reason_ for this. If something is<br />
&quot;unsigned long&quot;, then there's no reason to do<br />
<br />
typedef unsigned long myflags_t;<br />
<br />
but if there is a clear reason for why it under certain circumstances<br />
might be an &quot;unsigned int&quot; and under other configurations might be<br />
&quot;unsigned long&quot;, then by all means go ahead and use a typedef.<br />
<br />
(c) when you use sparse to literally create a _new_ type for<br />
type-checking.<br />
<br />
(d) New types which are identical to standard C99 types, in certain<br />
exceptional circumstances.<br />
<br />
Although it would only take a short amount of time for the eyes and<br />
brain to become accustomed to the standard types like 'uint32_t',<br />
some people object to their use anyway.<br />
<br />
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their<br />
signed equivalents which are identical to standard types are<br />
permitted -- although they are not mandatory in new code of your<br />
own.<br />
<br />
When editing existing code which already uses one or the other set<br />
of types, you should conform to the existing choices in that code.<br />
<br />
(e) Types safe for use in userspace.<br />
<br />
In certain structures which are visible to userspace, we cannot<br />
require C99 types and cannot use the 'u32' form above. Thus, we<br />
use __u32 and similar types in all structures which are shared<br />
with userspace.<br />
<br />
Maybe there are other cases too, but the rule should basically be to NEVER<br />
EVER use a typedef unless you can clearly match one of those rules.<br />
<br />
<br />
In general, a pointer, or a struct that has elements that can reasonably<br />
be directly accessed should _never_ be a typedef.<br />
<br />
== Functions ==<br />
<br />
Functions should be short and sweet, and do just one thing. They should<br />
fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,<br />
as we all know), and do one thing and do that well.<br />
<br />
The maximum length of a function is inversely proportional to the<br />
complexity and indentation level of that function. So, if you have a<br />
conceptually simple function that is just one long (but simple)<br />
case-statement, where you have to do lots of small things for a lot of<br />
different cases, it's OK to have a longer function.<br />
<br />
However, if you have a complex function, and you suspect that a<br />
less-than-gifted first-year high-school student might not even<br />
understand what the function is all about, you should adhere to the<br />
maximum limits all the more closely. Use helper functions with<br />
descriptive names (you can ask the compiler to in-line them if you think<br />
it's performance-critical, and it will probably do a better job of it<br />
than you would have done).<br />
<br />
Another measure of the function is the number of local variables. They<br />
shouldn't exceed 5-10, or you're doing something wrong. Re-think the<br />
function, and split it into smaller pieces. A human brain can<br />
generally easily keep track of about 7 different things, anything more<br />
and it gets confused. You know you're brilliant, but maybe you'd like<br />
to understand what you did 2 weeks from now.<br />
<br />
In source files, separate functions with one blank line. If the function is<br />
exported, the EXPORT* macro for it should follow immediately after the closing<br />
function brace line. E.g.:<br />
<br />
int system_is_up(void)<br />
{<br />
return system_state == SYSTEM_RUNNING;<br />
}<br />
EXPORT_SYMBOL(system_is_up);<br />
<br />
In function prototypes, include parameter names with their data types.<br />
Although this is not required by the C language, it is preferred in Linux<br />
because it is a simple way to add valuable information for the reader.<br />
<br />
== Centralized exiting of functions ==<br />
<br />
Albeit deprecated by some people, the equivalent of the goto statement is<br />
used frequently by compilers in form of the unconditional jump instruction.<br />
<br />
The goto statement comes in handy when a function exits from multiple<br />
locations and some common work such as cleanup has to be done. If there is no<br />
cleanup needed then just return directly.<br />
<br />
The rationale is:<br />
<br />
* unconditional statements are easier to understand and follow<br />
* nesting is reduced<br />
* errors by not updating individual exit points when making modifications are prevented<br />
* saves the compiler work to optimize redundant code away ;)<br />
<br />
int fun(int a)<br />
{<br />
int result = 0;<br />
char *buffer = kmalloc(SIZE);<br />
<br />
if (buffer == NULL)<br />
return -ENOMEM;<br />
<br />
if (condition1) {<br />
while (loop1) {<br />
...<br />
}<br />
result = 1;<br />
goto out;<br />
}<br />
...<br />
out:<br />
kfree(buffer);<br />
return result;<br />
}<br />
<br />
== Commenting ==<br />
<br />
Comments are good, but there is also a danger of over-commenting. NEVER<br />
try to explain HOW your code works in a comment: it's much better to<br />
write the code so that the _working_ is obvious, and it's a waste of<br />
time to explain badly written code.<br />
<br />
Generally, you want your comments to tell WHAT your code does, not HOW.<br />
Also, try to avoid putting comments inside a function body: if the<br />
function is so complex that you need to separately comment parts of it,<br />
you should probably go back to chapter 6 for a while. You can make<br />
small comments to note or warn about something particularly clever (or<br />
ugly), but try to avoid excess. Instead, put the comments at the head<br />
of the function, telling people what it does, and possibly WHY it does<br />
it.<br />
<br />
When commenting the kernel API functions, please use the kernel-doc format.<br />
See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc<br />
for details.<br />
<br />
coreboot style for comments is the C89 &quot;/* ... */&quot; style.<br />
You may use C99-style &quot;// ...&quot; comments.<br />
<br />
The preferred style for long (multi-line) comments is:<br />
<br />
/*<br />
* This is the preferred style for multi-line<br />
* comments in the Linux kernel source code.<br />
* Please use it consistently.<br />
*<br />
* Description: A column of asterisks on the left side,<br />
* with beginning and ending almost-blank lines.<br />
*/<br />
<br />
For files in net/ and drivers/net/ the preferred style for long (multi-line)<br />
comments is a little different.<br />
<br />
/* The preferred comment style for files in net/ and drivers/net<br />
* looks like this.<br />
*<br />
* It is nearly the same as the generally preferred comment style,<br />
* but there is no initial almost-blank line.<br />
*/<br />
<br />
It's also important to comment data, whether they are basic types or derived<br />
types. To this end, use just one data declaration per line (no commas for<br />
multiple data declarations). This leaves you room for a small comment on each<br />
item, explaining its use.<br />
<br />
== You've made a mess of it ==<br />
<br />
That's OK, we all do. You've probably been told by your long-time Unix<br />
user helper that &quot;GNU emacs&quot; automatically formats the C sources for<br />
you, and you've noticed that yes, it does do that, but the defaults it<br />
uses are less than desirable (in fact, they are worse than random<br />
typing - an infinite number of monkeys typing into GNU emacs would never<br />
make a good program).<br />
<br />
So, you can either get rid of GNU emacs, or change it to use saner<br />
values. To do the latter, you can stick the following in your .emacs file:<br />
<br />
(defun c-lineup-arglist-tabs-only (ignored)<br />
&quot;Line up argument lists by tabs, not spaces&quot;<br />
(let* ((anchor (c-langelem-pos c-syntactic-element))<br />
(column (c-langelem-2nd-pos c-syntactic-element))<br />
(offset (- (1+ column) anchor))<br />
(steps (floor offset c-basic-offset)))<br />
(* (max steps 1)<br />
c-basic-offset)))<br />
<br />
(add-hook 'c-mode-common-hook<br />
(lambda ()<br />
;; Add kernel style<br />
(c-add-style<br />
&quot;linux-tabs-only&quot;<br />
'(&quot;linux&quot; (c-offsets-alist<br />
(arglist-cont-nonempty<br />
c-lineup-gcc-asm-reg<br />
c-lineup-arglist-tabs-only))))))<br />
<br />
(add-hook 'c-mode-hook<br />
(lambda ()<br />
(let ((filename (buffer-file-name)))<br />
;; Enable kernel mode for the appropriate files<br />
(when (and filename<br />
(string-match (expand-file-name &quot;~/src/linux-trees&quot;)<br />
filename))<br />
(setq indent-tabs-mode t)<br />
(c-set-style &quot;linux-tabs-only&quot;)))))<br />
<br />
This will make emacs go better with the kernel coding style for C<br />
files below ~/src/linux-trees.<br />
<br />
But even if you fail in getting emacs to do sane formatting, not<br />
everything is lost: use &quot;indent&quot;.<br />
<br />
Now, again, GNU indent has the same brain-dead settings that GNU emacs<br />
has, which is why you need to give it a few command line options.<br />
However, that's not too bad, because even the makers of GNU indent<br />
recognize the authority of K&amp;R (the GNU people aren't evil, they are<br />
just severely misguided in this matter), so you just give indent the<br />
options &quot;-kr -i8&quot; (stands for &quot;K&amp;R, 8 character indents&quot;), or use<br />
&quot;scripts/Lindent&quot;, which indents in the latest style.<br />
<br />
&quot;indent&quot; has a lot of options, and especially when it comes to comment<br />
re-formatting you may want to take a look at the man page. But<br />
remember: &quot;indent&quot; is not a fix for bad programming.<br />
<br />
<br />
== Kconfig configuration files ==<br />
<br />
For all of the Kconfig* configuration files throughout the source tree,<br />
the indentation is somewhat different. Lines under a &quot;config&quot; definition<br />
are indented with one tab, while help text is indented an additional two<br />
spaces. Example:<br />
<br />
config AUDIT<br />
bool &quot;Auditing support&quot;<br />
depends on NET<br />
help<br />
Enable auditing infrastructure that can be used with another<br />
kernel subsystem, such as SELinux (which requires this for<br />
logging of avc messages output). Does not do system-call<br />
auditing without CONFIG_AUDITSYSCALL.<br />
<br />
Seriously dangerous features (such as write support for certain<br />
filesystems) should advertise this prominently in their prompt string:<br />
<br />
config ADFS_FS_RW<br />
bool &quot;ADFS write support (DANGEROUS)&quot;<br />
depends on ADFS_FS<br />
...<br />
<br />
For full documentation on the configuration files, see the file<br />
Documentation/kbuild/kconfig-language.txt.<br />
<br />
<br />
== Data structures ==<br />
<br />
Data structures that have visibility outside the single-threaded<br />
environment they are created and destroyed in should always have<br />
reference counts. In the kernel, garbage collection doesn't exist (and<br />
outside the kernel garbage collection is slow and inefficient), which<br />
means that you absolutely _have_ to reference count all your uses.<br />
<br />
Reference counting means that you can avoid locking, and allows multiple<br />
users to have access to the data structure in parallel - and not having<br />
to worry about the structure suddenly going away from under them just<br />
because they slept or did something else for a while.<br />
<br />
Note that locking is _not_ a replacement for reference counting.<br />
Locking is used to keep data structures coherent, while reference<br />
counting is a memory management technique. Usually both are needed, and<br />
they are not to be confused with each other.<br />
<br />
Many data structures can indeed have two levels of reference counting,<br />
when there are users of different &quot;classes&quot;. The subclass count counts<br />
the number of subclass users, and decrements the global count just once<br />
when the subclass count goes to zero.<br />
<br />
Examples of this kind of &quot;multi-level-reference-counting&quot; can be found in<br />
memory management (&quot;struct mm_struct&quot;: mm_users and mm_count), and in<br />
filesystem code (&quot;struct super_block&quot;: s_count and s_active).<br />
<br />
Remember: if another thread can find your data structure, and you don't<br />
have a reference count on it, you almost certainly have a bug.<br />
<br />
<br />
== Macros, Enums and RTL ==<br />
<br />
Names of macros defining constants and labels in enums are capitalized.<br />
<br />
#define CONSTANT 0x12345<br />
<br />
Enums are preferred when defining several related constants.<br />
<br />
CAPITALIZED macro names are appreciated but macros resembling functions<br />
may be named in lower case.<br />
<br />
Generally, inline functions are preferable to macros resembling functions.<br />
<br />
Macros with multiple statements should be enclosed in a do - while block:<br />
<br />
#define macrofun(a, b, c) \<br />
do { \<br />
if (a == 5) \<br />
do_this(b, c); \<br />
} while (0)<br />
<br />
Things to avoid when using macros:<br />
<br />
1) macros that affect control flow:<br />
<br />
#define FOO(x) \<br />
do { \<br />
if (blah(x) &lt; 0) \<br />
return -EBUGGERED; \<br />
} while(0)<br />
<br />
is a _very_ bad idea. It looks like a function call but exits the &quot;calling&quot;<br />
function; don't break the internal parsers of those who will read the code.<br />
<br />
2) macros that depend on having a local variable with a magic name:<br />
<br />
#define FOO(val) bar(index, val)<br />
<br />
might look like a good thing, but it's confusing as hell when one reads the<br />
code and it's prone to breakage from seemingly innocent changes.<br />
<br />
3) macros with arguments that are used as l-values: FOO(x) = y; will<br />
bite you if somebody e.g. turns FOO into an inline function.<br />
<br />
4) forgetting about precedence: macros defining constants using expressions<br />
must enclose the expression in parentheses. Beware of similar issues with<br />
macros using parameters.<br />
<br />
#define CONSTANT 0x4000<br />
#define CONSTEXP (CONSTANT | 3)<br />
<br />
The cpp manual deals with macros exhaustively. The gcc internals manual also<br />
covers RTL which is used frequently with assembly language in the kernel.<br />
<br />
== Printing kernel messages ==<br />
<br />
Kernel developers like to be seen as literate. Do mind the spelling<br />
of kernel messages to make a good impression. Do not use crippled<br />
words like &quot;dont&quot;; use &quot;do not&quot; or &quot;don't&quot; instead. Make the messages<br />
concise, clear, and unambiguous.<br />
<br />
Kernel messages do not have to be terminated with a period.<br />
<br />
Printing numbers in parentheses (%d) adds no value and should be avoided.<br />
<br />
There are a number of driver model diagnostic macros in &lt;linux/device.h&gt;<br />
which you should use to make sure messages are matched to the right device<br />
and driver, and are tagged with the right level: dev_err(), dev_warn(),<br />
dev_info(), and so forth. For messages that aren't associated with a<br />
particular device, &lt;linux/printk.h&gt; defines pr_debug() and pr_info().<br />
<br />
Coming up with good debugging messages can be quite a challenge; and once<br />
you have them, they can be a huge help for remote troubleshooting. Such<br />
messages should be compiled out when the DEBUG symbol is not defined (that<br />
is, by default they are not included). When you use dev_dbg() or pr_debug(),<br />
that's automatic. Many subsystems have Kconfig options to turn on -DDEBUG.<br />
A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to the<br />
ones already enabled by DEBUG.<br />
<br />
<br />
== Allocating memory ==<br />
<br />
The kernel provides the following general purpose memory allocators:<br />
kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and<br />
vzalloc(). Please refer to the API documentation for further information<br />
about them.<br />
<br />
The preferred form for passing a size of a struct is the following:<br />
<br />
p = kmalloc(sizeof(*p), ...);<br />
<br />
The alternative form where struct name is spelled out hurts readability and<br />
introduces an opportunity for a bug when the pointer variable type is changed<br />
but the corresponding sizeof that is passed to a memory allocator is not.<br />
<br />
Casting the return value which is a void pointer is redundant. The conversion<br />
from void pointer to any other pointer type is guaranteed by the C programming<br />
language.<br />
<br />
The preferred form for allocating an array is the following:<br />
<br />
p = kmalloc_array(n, sizeof(...), ...);<br />
<br />
The preferred form for allocating a zeroed array is the following:<br />
<br />
p = kcalloc(n, sizeof(...), ...);<br />
<br />
Both forms check for overflow on the allocation size n * sizeof(...),<br />
and return NULL if that occurred.<br />
<br />
== The inline disease ==<br />
<br />
There appears to be a common misperception that gcc has a magic &quot;make me<br />
faster&quot; speedup option called &quot;inline&quot;. While the use of inlines can be<br />
appropriate (for example as a means of replacing macros, see Chapter 12), it<br />
very often is not. Abundant use of the inline keyword leads to a much bigger<br />
kernel, which in turn slows the system as a whole down, due to a bigger<br />
icache footprint for the CPU and simply because there is less memory<br />
available for the pagecache. Just think about it; a pagecache miss causes a<br />
disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles<br />
that can go into these 5 milliseconds.<br />
<br />
A reasonable rule of thumb is to not put inline at functions that have more<br />
than 3 lines of code in them. An exception to this rule are the cases where<br />
a parameter is known to be a compiletime constant, and as a result of this<br />
constantness you *know* the compiler will be able to optimize most of your<br />
function away at compile time. For a good example of this later case, see<br />
the kmalloc() inline function.<br />
<br />
Often people argue that adding inline to functions that are static and used<br />
only once is always a win since there is no space tradeoff. While this is<br />
technically correct, gcc is capable of inlining these automatically without<br />
help, and the maintenance issue of removing the inline when a second user<br />
appears outweighs the potential value of the hint that tells gcc to do<br />
something it would have done anyway.<br />
<br />
<br />
== Function return values and names ==<br />
<br />
Functions can return values of many different kinds, and one of the<br />
most common is a value indicating whether the function succeeded or<br />
failed. Such a value can be represented as an error-code integer<br />
(-Exxx = failure, 0 = success) or a &quot;succeeded&quot; boolean (0 = failure,<br />
non-zero = success).<br />
<br />
Mixing up these two sorts of representations is a fertile source of<br />
difficult-to-find bugs. If the C language included a strong distinction<br />
between integers and booleans then the compiler would find these mistakes<br />
for us... but it doesn't. To help prevent such bugs, always follow this<br />
convention:<br />
<br />
If the name of a function is an action or an imperative command,<br />
the function should return an error-code integer. If the name<br />
is a predicate, the function should return a &quot;succeeded&quot; boolean.<br />
<br />
For example, &quot;add work&quot; is a command, and the add_work() function returns 0<br />
for success or -EBUSY for failure. In the same way, &quot;PCI device present&quot; is<br />
a predicate, and the pci_dev_present() function returns 1 if it succeeds in<br />
finding a matching device or 0 if it doesn't.<br />
<br />
All EXPORTed functions must respect this convention, and so should all<br />
public functions. Private (static) functions need not, but it is<br />
recommended that they do.<br />
<br />
Functions whose return value is the actual result of a computation, rather<br />
than an indication of whether the computation succeeded, are not subject to<br />
this rule. Generally they indicate failure by returning some out-of-range<br />
result. Typical examples would be functions that return pointers; they use<br />
NULL or the ERR_PTR mechanism to report failure.<br />
<br />
<br />
== Don't re-invent the kernel macros ==<br />
<br />
The header file include/linux/kernel.h contains a number of macros that<br />
you should use, rather than explicitly coding some variant of them yourself.<br />
For example, if you need to calculate the length of an array, take advantage<br />
of the macro<br />
<br />
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))<br />
<br />
Similarly, if you need to calculate the size of some structure member, use<br />
<br />
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)-&gt;f))<br />
<br />
There are also min() and max() macros that do strict type checking if you<br />
need them. Feel free to peruse that header file to see what else is already<br />
defined that you shouldn't reproduce in your code.<br />
<br />
<br />
== Editor modelines and other cruft ==<br />
<br />
Some editors can interpret configuration information embedded in source files,<br />
indicated with special markers. For example, emacs interprets lines marked<br />
like this:<br />
<br />
-*- mode: c -*-<br />
<br />
Or like this:<br />
<br />
/*<br />
Local Variables:<br />
compile-command: &quot;gcc -DMAGIC_DEBUG_FLAG foo.c&quot;<br />
End:<br />
*/<br />
<br />
Vim interprets markers that look like this:<br />
<br />
/* vim:set sw=8 noet */<br />
<br />
Do not include any of these in source files. People have their own personal<br />
editor configurations, and your source files should not override them. This<br />
includes markers for indentation and mode configuration. People may use their<br />
own custom mode, or may have some other magic method for making indentation<br />
work correctly.<br />
<br />
== Inline assembly ==<br />
<br />
In architecture-specific code, you may need to use inline assembly to interface<br />
with CPU or platform functionality. Don't hesitate to do so when necessary.<br />
However, don't use inline assembly gratuitously when C can do the job. You can<br />
and should poke hardware from C when possible.<br />
<br />
Consider writing simple helper functions that wrap common bits of inline<br />
assembly, rather than repeatedly writing them with slight variations. Remember<br />
that inline assembly can use C parameters.<br />
<br />
Large, non-trivial assembly functions should go in .S files, with corresponding<br />
C prototypes defined in C header files. The C prototypes for assembly<br />
functions should use &quot;asmlinkage&quot;.<br />
<br />
You may need to mark your asm statement as volatile, to prevent GCC from<br />
removing it if GCC doesn't notice any side effects. You don't always need to<br />
do so, though, and doing so unnecessarily can limit optimization.<br />
<br />
When writing a single inline assembly statement containing multiple<br />
instructions, put each instruction on a separate line in a separate quoted<br />
string, and end each string except the last with \n\t to properly indent the<br />
next instruction in the assembly output:<br />
<br />
asm (&quot;magic %reg1, #42\n\t&quot;<br />
&quot;more_magic %reg2, %reg3&quot;<br />
: /* outputs */ : /* inputs */ : /* clobbers */);<br />
<br />
== References ==<br />
<br />
The C Programming Language, Second Edition<br />
by Brian W. Kernighan and Dennis M. Ritchie.<br />
Prentice Hall, Inc., 1988.<br />
ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).<br />
URL: http://cm.bell-labs.com/cm/cs/cbook/<br />
<br />
The Practice of Programming<br />
by Brian W. Kernighan and Rob Pike.<br />
Addison-Wesley, Inc., 1999.<br />
ISBN 0-201-61586-X.<br />
URL: http://cm.bell-labs.com/cm/cs/tpop/<br />
<br />
GNU manuals - where in compliance with K&amp;R and this text - for cpp, gcc,<br />
gcc internals and indent, all available from http://www.gnu.org/manual/<br />
<br />
WG14 is the international standardization working group for the programming<br />
language C, URL: http://www.open-std.org/JTC1/SC22/WG14/<br />
<br />
Kernel CodingStyle, by greg@kroah.com at OLS 2002:<br />
http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/</div>Stepanhttp://www.coreboot.org/index.php?title=Coding_Style&diff=12314Coding Style2013-12-05T18:54:26Z<p>Stepan: /* Allocating memory */</p>
<hr />
<div>This is a short document describing the preferred coding style for the<br />
coreboot project. It is in many ways exactly the same as the Linux kernel<br />
coding style. In fact, most of this document has been copied from the<br />
[http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/Documentation/CodingStyle?id=HEAD Linux kernel coding style]<br />
<br />
Please at least consider the points made here.<br />
<br />
First off, I'd suggest printing out a copy of the GNU coding standards,<br />
and NOT read it. Burn them, it's a great symbolic gesture.<br />
<br />
Anyway, here goes:<br />
<br />
<br />
== Indentation ==<br />
<br />
Tabs are 8 characters, and thus indentations are also 8 characters.<br />
There are heretic movements that try to make indentations 4 (or even 2!)<br />
characters deep, and that is akin to trying to define the value of PI to<br />
be 3.<br />
<br />
Rationale: The whole idea behind indentation is to clearly define where<br />
a block of control starts and ends. Especially when you've been looking<br />
at your screen for 20 straight hours, you'll find it a lot easier to see<br />
how the indentation works if you have large indentations.<br />
<br />
Now, some people will claim that having 8-character indentations makes<br />
the code move too far to the right, and makes it hard to read on a<br />
80-character terminal screen. The answer to that is that if you need<br />
more than 3 levels of indentation, you're screwed anyway, and should fix<br />
your program.<br />
<br />
In short, 8-char indents make things easier to read, and have the added<br />
benefit of warning you when you're nesting your functions too deep.<br />
Heed that warning.<br />
<br />
The preferred way to ease multiple indentation levels in a switch statement is<br />
to align the &quot;switch&quot; and its subordinate &quot;case&quot; labels in the same column<br />
instead of &quot;double-indenting&quot; the &quot;case&quot; labels. E.g.:<br />
<br />
switch (suffix) {<br />
case 'G':<br />
case 'g':<br />
mem &lt;&lt;= 30;<br />
break;<br />
case 'M':<br />
case 'm':<br />
mem &lt;&lt;= 20;<br />
break;<br />
case 'K':<br />
case 'k':<br />
mem &lt;&lt;= 10;<br />
/* fall through */<br />
default:<br />
break;<br />
}<br />
<br />
<br />
Don't put multiple statements on a single line unless you have<br />
something to hide:<br />
<br />
if (condition) do_this;<br />
do_something_everytime;<br />
<br />
Don't put multiple assignments on a single line either. Kernel coding style<br />
is super simple. Avoid tricky expressions.<br />
<br />
Outside of comments, documentation and except in Kconfig, spaces are never<br />
used for indentation, and the above example is deliberately broken.<br />
<br />
Get a decent editor and don't leave whitespace at the end of lines.<br />
<br />
== Breaking long lines and strings ==<br />
<br />
Coding style is all about readability and maintainability using commonly<br />
available tools.<br />
<br />
The limit on the length of lines is 80 columns and this is a strongly<br />
preferred limit.<br />
<br />
Statements longer than 80 columns will be broken into sensible chunks, unless<br />
exceeding 80 columns significantly increases readability and does not hide<br />
information. Descendants are always substantially shorter than the parent and<br />
are placed substantially to the right. The same applies to function headers<br />
with a long argument list. However, never break user-visible strings such as<br />
printk messages, because that breaks the ability to grep for them.<br />
<br />
<br />
== Placing Braces and Spaces ==<br />
<br />
The other issue that always comes up in C styling is the placement of<br />
braces. Unlike the indent size, there are few technical reasons to<br />
choose one placement strategy over the other, but the preferred way, as<br />
shown to us by the prophets Kernighan and Ritchie, is to put the opening<br />
brace last on the line, and put the closing brace first, thusly:<br />
<br />
if (x is true) {<br />
we do y<br />
}<br />
<br />
This applies to all non-function statement blocks (if, switch, for,<br />
while, do). E.g.:<br />
<br />
switch (action) {<br />
case KOBJ_ADD:<br />
return &quot;add&quot;;<br />
case KOBJ_REMOVE:<br />
return &quot;remove&quot;;<br />
case KOBJ_CHANGE:<br />
return &quot;change&quot;;<br />
default:<br />
return NULL;<br />
}<br />
<br />
However, there is one special case, namely functions: they have the<br />
opening brace at the beginning of the next line, thus:<br />
<br />
int function(int x)<br />
{<br />
body of function<br />
}<br />
<br />
Heretic people all over the world have claimed that this inconsistency<br />
is ... well ... inconsistent, but all right-thinking people know that<br />
(a) K&amp;R are _right_ and (b) K&amp;R are right. Besides, functions are<br />
special anyway (you can't nest them in C).<br />
<br />
Note that the closing brace is empty on a line of its own, _except_ in<br />
the cases where it is followed by a continuation of the same statement,<br />
ie a &quot;while&quot; in a do-statement or an &quot;else&quot; in an if-statement, like<br />
this:<br />
<br />
do {<br />
body of do-loop<br />
} while (condition);<br />
<br />
and<br />
<br />
if (x == y) {<br />
..<br />
} else if (x &gt; y) {<br />
...<br />
} else {<br />
....<br />
}<br />
<br />
Rationale: K&amp;R.<br />
<br />
Also, note that this brace-placement also minimizes the number of empty<br />
(or almost empty) lines, without any loss of readability. Thus, as the<br />
supply of new-lines on your screen is not a renewable resource (think<br />
25-line terminal screens here), you have more empty lines to put<br />
comments on.<br />
<br />
Do not unnecessarily use braces where a single statement will do.<br />
<br />
if (condition)<br />
action();<br />
<br />
and<br />
<br />
if (condition)<br />
do_this();<br />
else<br />
do_that();<br />
<br />
This does not apply if only one branch of a conditional statement is a single<br />
statement; in the latter case use braces in both branches:<br />
<br />
if (condition) {<br />
do_this();<br />
do_that();<br />
} else {<br />
otherwise();<br />
}<br />
<br />
=== Spaces ===<br />
<br />
Linux kernel style for use of spaces depends (mostly) on<br />
function-versus-keyword usage. Use a space after (most) keywords. The<br />
notable exceptions are sizeof, typeof, alignof, and __attribute__, which look<br />
somewhat like functions (and are usually used with parentheses in Linux,<br />
although they are not required in the language, as in: &quot;sizeof info&quot; after<br />
&quot;struct fileinfo info;&quot; is declared).<br />
<br />
So use a space after these keywords:<br />
if, switch, case, for, do, while<br />
but not with sizeof, typeof, alignof, or __attribute__. E.g.,<br />
s = sizeof(struct file);<br />
<br />
Do not add spaces around (inside) parenthesized expressions. This example is<br />
*bad*:<br />
<br />
s = sizeof( struct file );<br />
<br />
When declaring pointer data or a function that returns a pointer type, the<br />
preferred use of '*' is adjacent to the data name or function name and not<br />
adjacent to the type name. Examples:<br />
<br />
char *linux_banner;<br />
unsigned long long memparse(char *ptr, char **retptr);<br />
char *match_strdup(substring_t *s);<br />
<br />
Use one space around (on each side of) most binary and ternary operators,<br />
such as any of these:<br />
<br />
= + - &lt; &gt; * / % | &amp; ^ &lt;= &gt;= == != ? :<br />
<br />
but no space after unary operators:<br />
&amp; * + - ~ ! sizeof typeof alignof __attribute__ defined<br />
<br />
no space before the postfix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
no space after the prefix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
and no space around the '.' and &quot;-&gt;&quot; structure member operators.<br />
<br />
Do not leave trailing whitespace at the ends of lines. Some editors with<br />
&quot;smart&quot; indentation will insert whitespace at the beginning of new lines as<br />
appropriate, so you can start typing the next line of code right away.<br />
However, some such editors do not remove the whitespace if you end up not<br />
putting a line of code there, such as if you leave a blank line. As a result,<br />
you end up with lines containing trailing whitespace.<br />
<br />
Git will warn you about patches that introduce trailing whitespace, and can<br />
optionally strip the trailing whitespace for you; however, if applying a series<br />
of patches, this may make later patches in the series fail by changing their<br />
context lines.<br />
<br />
== Naming ==<br />
<br />
C is a Spartan language, and so should your naming be. Unlike Modula-2<br />
and Pascal programmers, C programmers do not use cute names like<br />
ThisVariableIsATemporaryCounter. A C programmer would call that<br />
variable &quot;tmp&quot;, which is much easier to write, and not the least more<br />
difficult to understand.<br />
<br />
HOWEVER, while mixed-case names are frowned upon, descriptive names for<br />
global variables are a must. To call a global function &quot;foo&quot; is a<br />
shooting offense.<br />
<br />
GLOBAL variables (to be used only if you _really_ need them) need to<br />
have descriptive names, as do global functions. If you have a function<br />
that counts the number of active users, you should call that<br />
&quot;count_active_users()&quot; or similar, you should _not_ call it &quot;cntusr()&quot;.<br />
<br />
Encoding the type of a function into the name (so-called Hungarian<br />
notation) is brain damaged - the compiler knows the types anyway and can<br />
check those, and it only confuses the programmer. No wonder MicroSoft<br />
makes buggy programs.<br />
<br />
LOCAL variable names should be short, and to the point. If you have<br />
some random integer loop counter, it should probably be called &quot;i&quot;.<br />
Calling it &quot;loop_counter&quot; is non-productive, if there is no chance of it<br />
being mis-understood. Similarly, &quot;tmp&quot; can be just about any type of<br />
variable that is used to hold a temporary value.<br />
<br />
If you are afraid to mix up your local variable names, you have another<br />
problem, which is called the function-growth-hormone-imbalance syndrome.<br />
See chapter 6 (Functions).<br />
<br />
<br />
== Typedefs ==<br />
<br />
Please don't use things like &quot;vps_t&quot;.<br />
<br />
It's a _mistake_ to use typedef for structures and pointers. When you see a<br />
<br />
vps_t a;<br />
<br />
in the source, what does it mean?<br />
<br />
In contrast, if it says<br />
<br />
struct virtual_container *a;<br />
<br />
you can actually tell what &quot;a&quot; is.<br />
<br />
Lots of people think that typedefs &quot;help readability&quot;. Not so. They are<br />
useful only for:<br />
<br />
(a) totally opaque objects (where the typedef is actively used to _hide_ what the object is).<br />
<br />
Example: &quot;pte_t&quot; etc. opaque objects that you can only access using<br />
the proper accessor functions.<br />
<br />
NOTE! Opaqueness and &quot;accessor functions&quot; are not good in themselves.<br />
The reason we have them for things like pte_t etc. is that there<br />
really is absolutely _zero_ portably accessible information there.<br />
<br />
(b) Clear integer types, where the abstraction _helps_ avoid confusion<br />
whether it is &quot;int&quot; or &quot;long&quot;.<br />
<br />
u8/u16/u32 are perfectly fine typedefs, although they fit into<br />
category (d) better than here.<br />
<br />
NOTE! Again - there needs to be a _reason_ for this. If something is<br />
&quot;unsigned long&quot;, then there's no reason to do<br />
<br />
typedef unsigned long myflags_t;<br />
<br />
but if there is a clear reason for why it under certain circumstances<br />
might be an &quot;unsigned int&quot; and under other configurations might be<br />
&quot;unsigned long&quot;, then by all means go ahead and use a typedef.<br />
<br />
(c) when you use sparse to literally create a _new_ type for<br />
type-checking.<br />
<br />
(d) New types which are identical to standard C99 types, in certain<br />
exceptional circumstances.<br />
<br />
Although it would only take a short amount of time for the eyes and<br />
brain to become accustomed to the standard types like 'uint32_t',<br />
some people object to their use anyway.<br />
<br />
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their<br />
signed equivalents which are identical to standard types are<br />
permitted -- although they are not mandatory in new code of your<br />
own.<br />
<br />
When editing existing code which already uses one or the other set<br />
of types, you should conform to the existing choices in that code.<br />
<br />
(e) Types safe for use in userspace.<br />
<br />
In certain structures which are visible to userspace, we cannot<br />
require C99 types and cannot use the 'u32' form above. Thus, we<br />
use __u32 and similar types in all structures which are shared<br />
with userspace.<br />
<br />
Maybe there are other cases too, but the rule should basically be to NEVER<br />
EVER use a typedef unless you can clearly match one of those rules.<br />
<br />
<br />
In general, a pointer, or a struct that has elements that can reasonably<br />
be directly accessed should _never_ be a typedef.<br />
<br />
== Functions ==<br />
<br />
Functions should be short and sweet, and do just one thing. They should<br />
fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,<br />
as we all know), and do one thing and do that well.<br />
<br />
The maximum length of a function is inversely proportional to the<br />
complexity and indentation level of that function. So, if you have a<br />
conceptually simple function that is just one long (but simple)<br />
case-statement, where you have to do lots of small things for a lot of<br />
different cases, it's OK to have a longer function.<br />
<br />
However, if you have a complex function, and you suspect that a<br />
less-than-gifted first-year high-school student might not even<br />
understand what the function is all about, you should adhere to the<br />
maximum limits all the more closely. Use helper functions with<br />
descriptive names (you can ask the compiler to in-line them if you think<br />
it's performance-critical, and it will probably do a better job of it<br />
than you would have done).<br />
<br />
Another measure of the function is the number of local variables. They<br />
shouldn't exceed 5-10, or you're doing something wrong. Re-think the<br />
function, and split it into smaller pieces. A human brain can<br />
generally easily keep track of about 7 different things, anything more<br />
and it gets confused. You know you're brilliant, but maybe you'd like<br />
to understand what you did 2 weeks from now.<br />
<br />
In source files, separate functions with one blank line. If the function is<br />
exported, the EXPORT* macro for it should follow immediately after the closing<br />
function brace line. E.g.:<br />
<br />
int system_is_up(void)<br />
{<br />
return system_state == SYSTEM_RUNNING;<br />
}<br />
EXPORT_SYMBOL(system_is_up);<br />
<br />
In function prototypes, include parameter names with their data types.<br />
Although this is not required by the C language, it is preferred in Linux<br />
because it is a simple way to add valuable information for the reader.<br />
<br />
== Centralized exiting of functions ==<br />
<br />
Albeit deprecated by some people, the equivalent of the goto statement is<br />
used frequently by compilers in form of the unconditional jump instruction.<br />
<br />
The goto statement comes in handy when a function exits from multiple<br />
locations and some common work such as cleanup has to be done. If there is no<br />
cleanup needed then just return directly.<br />
<br />
The rationale is:<br />
<br />
* unconditional statements are easier to understand and follow<br />
* nesting is reduced<br />
* errors by not updating individual exit points when making modifications are prevented<br />
* saves the compiler work to optimize redundant code away ;)<br />
<br />
int fun(int a)<br />
{<br />
int result = 0;<br />
char *buffer = kmalloc(SIZE);<br />
<br />
if (buffer == NULL)<br />
return -ENOMEM;<br />
<br />
if (condition1) {<br />
while (loop1) {<br />
...<br />
}<br />
result = 1;<br />
goto out;<br />
}<br />
...<br />
out:<br />
kfree(buffer);<br />
return result;<br />
}<br />
<br />
== Commenting ==<br />
<br />
Comments are good, but there is also a danger of over-commenting. NEVER<br />
try to explain HOW your code works in a comment: it's much better to<br />
write the code so that the _working_ is obvious, and it's a waste of<br />
time to explain badly written code.<br />
<br />
Generally, you want your comments to tell WHAT your code does, not HOW.<br />
Also, try to avoid putting comments inside a function body: if the<br />
function is so complex that you need to separately comment parts of it,<br />
you should probably go back to chapter 6 for a while. You can make<br />
small comments to note or warn about something particularly clever (or<br />
ugly), but try to avoid excess. Instead, put the comments at the head<br />
of the function, telling people what it does, and possibly WHY it does<br />
it.<br />
<br />
When commenting the kernel API functions, please use the kernel-doc format.<br />
See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc<br />
for details.<br />
<br />
coreboot style for comments is the C89 &quot;/* ... */&quot; style.<br />
You may use C99-style &quot;// ...&quot; comments.<br />
<br />
The preferred style for long (multi-line) comments is:<br />
<br />
/*<br />
* This is the preferred style for multi-line<br />
* comments in the Linux kernel source code.<br />
* Please use it consistently.<br />
*<br />
* Description: A column of asterisks on the left side,<br />
* with beginning and ending almost-blank lines.<br />
*/<br />
<br />
For files in net/ and drivers/net/ the preferred style for long (multi-line)<br />
comments is a little different.<br />
<br />
/* The preferred comment style for files in net/ and drivers/net<br />
* looks like this.<br />
*<br />
* It is nearly the same as the generally preferred comment style,<br />
* but there is no initial almost-blank line.<br />
*/<br />
<br />
It's also important to comment data, whether they are basic types or derived<br />
types. To this end, use just one data declaration per line (no commas for<br />
multiple data declarations). This leaves you room for a small comment on each<br />
item, explaining its use.<br />
<br />
== You've made a mess of it ==<br />
<br />
That's OK, we all do. You've probably been told by your long-time Unix<br />
user helper that &quot;GNU emacs&quot; automatically formats the C sources for<br />
you, and you've noticed that yes, it does do that, but the defaults it<br />
uses are less than desirable (in fact, they are worse than random<br />
typing - an infinite number of monkeys typing into GNU emacs would never<br />
make a good program).<br />
<br />
So, you can either get rid of GNU emacs, or change it to use saner<br />
values. To do the latter, you can stick the following in your .emacs file:<br />
<br />
(defun c-lineup-arglist-tabs-only (ignored)<br />
&quot;Line up argument lists by tabs, not spaces&quot;<br />
(let* ((anchor (c-langelem-pos c-syntactic-element))<br />
(column (c-langelem-2nd-pos c-syntactic-element))<br />
(offset (- (1+ column) anchor))<br />
(steps (floor offset c-basic-offset)))<br />
(* (max steps 1)<br />
c-basic-offset)))<br />
<br />
(add-hook 'c-mode-common-hook<br />
(lambda ()<br />
;; Add kernel style<br />
(c-add-style<br />
&quot;linux-tabs-only&quot;<br />
'(&quot;linux&quot; (c-offsets-alist<br />
(arglist-cont-nonempty<br />
c-lineup-gcc-asm-reg<br />
c-lineup-arglist-tabs-only))))))<br />
<br />
(add-hook 'c-mode-hook<br />
(lambda ()<br />
(let ((filename (buffer-file-name)))<br />
;; Enable kernel mode for the appropriate files<br />
(when (and filename<br />
(string-match (expand-file-name &quot;~/src/linux-trees&quot;)<br />
filename))<br />
(setq indent-tabs-mode t)<br />
(c-set-style &quot;linux-tabs-only&quot;)))))<br />
<br />
This will make emacs go better with the kernel coding style for C<br />
files below ~/src/linux-trees.<br />
<br />
But even if you fail in getting emacs to do sane formatting, not<br />
everything is lost: use &quot;indent&quot;.<br />
<br />
Now, again, GNU indent has the same brain-dead settings that GNU emacs<br />
has, which is why you need to give it a few command line options.<br />
However, that's not too bad, because even the makers of GNU indent<br />
recognize the authority of K&amp;R (the GNU people aren't evil, they are<br />
just severely misguided in this matter), so you just give indent the<br />
options &quot;-kr -i8&quot; (stands for &quot;K&amp;R, 8 character indents&quot;), or use<br />
&quot;scripts/Lindent&quot;, which indents in the latest style.<br />
<br />
&quot;indent&quot; has a lot of options, and especially when it comes to comment<br />
re-formatting you may want to take a look at the man page. But<br />
remember: &quot;indent&quot; is not a fix for bad programming.<br />
<br />
<br />
== Kconfig configuration files ==<br />
<br />
For all of the Kconfig* configuration files throughout the source tree,<br />
the indentation is somewhat different. Lines under a &quot;config&quot; definition<br />
are indented with one tab, while help text is indented an additional two<br />
spaces. Example:<br />
<br />
config AUDIT<br />
bool &quot;Auditing support&quot;<br />
depends on NET<br />
help<br />
Enable auditing infrastructure that can be used with another<br />
kernel subsystem, such as SELinux (which requires this for<br />
logging of avc messages output). Does not do system-call<br />
auditing without CONFIG_AUDITSYSCALL.<br />
<br />
Seriously dangerous features (such as write support for certain<br />
filesystems) should advertise this prominently in their prompt string:<br />
<br />
config ADFS_FS_RW<br />
bool &quot;ADFS write support (DANGEROUS)&quot;<br />
depends on ADFS_FS<br />
...<br />
<br />
For full documentation on the configuration files, see the file<br />
Documentation/kbuild/kconfig-language.txt.<br />
<br />
<br />
== Data structures ==<br />
<br />
Data structures that have visibility outside the single-threaded<br />
environment they are created and destroyed in should always have<br />
reference counts. In the kernel, garbage collection doesn't exist (and<br />
outside the kernel garbage collection is slow and inefficient), which<br />
means that you absolutely _have_ to reference count all your uses.<br />
<br />
Reference counting means that you can avoid locking, and allows multiple<br />
users to have access to the data structure in parallel - and not having<br />
to worry about the structure suddenly going away from under them just<br />
because they slept or did something else for a while.<br />
<br />
Note that locking is _not_ a replacement for reference counting.<br />
Locking is used to keep data structures coherent, while reference<br />
counting is a memory management technique. Usually both are needed, and<br />
they are not to be confused with each other.<br />
<br />
Many data structures can indeed have two levels of reference counting,<br />
when there are users of different &quot;classes&quot;. The subclass count counts<br />
the number of subclass users, and decrements the global count just once<br />
when the subclass count goes to zero.<br />
<br />
Examples of this kind of &quot;multi-level-reference-counting&quot; can be found in<br />
memory management (&quot;struct mm_struct&quot;: mm_users and mm_count), and in<br />
filesystem code (&quot;struct super_block&quot;: s_count and s_active).<br />
<br />
Remember: if another thread can find your data structure, and you don't<br />
have a reference count on it, you almost certainly have a bug.<br />
<br />
<br />
== Macros, Enums and RTL ==<br />
<br />
Names of macros defining constants and labels in enums are capitalized.<br />
<br />
#define CONSTANT 0x12345<br />
<br />
Enums are preferred when defining several related constants.<br />
<br />
CAPITALIZED macro names are appreciated but macros resembling functions<br />
may be named in lower case.<br />
<br />
Generally, inline functions are preferable to macros resembling functions.<br />
<br />
Macros with multiple statements should be enclosed in a do - while block:<br />
<br />
#define macrofun(a, b, c) \<br />
do { \<br />
if (a == 5) \<br />
do_this(b, c); \<br />
} while (0)<br />
<br />
Things to avoid when using macros:<br />
<br />
1) macros that affect control flow:<br />
<br />
#define FOO(x) \<br />
do { \<br />
if (blah(x) &lt; 0) \<br />
return -EBUGGERED; \<br />
} while(0)<br />
<br />
is a _very_ bad idea. It looks like a function call but exits the &quot;calling&quot;<br />
function; don't break the internal parsers of those who will read the code.<br />
<br />
2) macros that depend on having a local variable with a magic name:<br />
<br />
#define FOO(val) bar(index, val)<br />
<br />
might look like a good thing, but it's confusing as hell when one reads the<br />
code and it's prone to breakage from seemingly innocent changes.<br />
<br />
3) macros with arguments that are used as l-values: FOO(x) = y; will<br />
bite you if somebody e.g. turns FOO into an inline function.<br />
<br />
4) forgetting about precedence: macros defining constants using expressions<br />
must enclose the expression in parentheses. Beware of similar issues with<br />
macros using parameters.<br />
<br />
#define CONSTANT 0x4000<br />
#define CONSTEXP (CONSTANT | 3)<br />
<br />
The cpp manual deals with macros exhaustively. The gcc internals manual also<br />
covers RTL which is used frequently with assembly language in the kernel.<br />
<br />
<br />
== Printing kernel messages ==<br />
<br />
Kernel developers like to be seen as literate. Do mind the spelling<br />
of kernel messages to make a good impression. Do not use crippled<br />
words like &quot;dont&quot;; use &quot;do not&quot; or &quot;don't&quot; instead. Make the messages<br />
concise, clear, and unambiguous.<br />
<br />
Kernel messages do not have to be terminated with a period.<br />
<br />
Printing numbers in parentheses (%d) adds no value and should be avoided.<br />
<br />
There are a number of driver model diagnostic macros in &lt;linux/device.h&gt;<br />
which you should use to make sure messages are matched to the right device<br />
and driver, and are tagged with the right level: dev_err(), dev_warn(),<br />
dev_info(), and so forth. For messages that aren't associated with a<br />
particular device, &lt;linux/printk.h&gt; defines pr_debug() and pr_info().<br />
<br />
Coming up with good debugging messages can be quite a challenge; and once<br />
you have them, they can be a huge help for remote troubleshooting. Such<br />
messages should be compiled out when the DEBUG symbol is not defined (that<br />
is, by default they are not included). When you use dev_dbg() or pr_debug(),<br />
that's automatic. Many subsystems have Kconfig options to turn on -DDEBUG.<br />
A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to the<br />
ones already enabled by DEBUG.<br />
<br />
<br />
== Allocating memory ==<br />
<br />
The kernel provides the following general purpose memory allocators:<br />
kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and<br />
vzalloc(). Please refer to the API documentation for further information<br />
about them.<br />
<br />
The preferred form for passing a size of a struct is the following:<br />
<br />
p = kmalloc(sizeof(*p), ...);<br />
<br />
The alternative form where struct name is spelled out hurts readability and<br />
introduces an opportunity for a bug when the pointer variable type is changed<br />
but the corresponding sizeof that is passed to a memory allocator is not.<br />
<br />
Casting the return value which is a void pointer is redundant. The conversion<br />
from void pointer to any other pointer type is guaranteed by the C programming<br />
language.<br />
<br />
The preferred form for allocating an array is the following:<br />
<br />
p = kmalloc_array(n, sizeof(...), ...);<br />
<br />
The preferred form for allocating a zeroed array is the following:<br />
<br />
p = kcalloc(n, sizeof(...), ...);<br />
<br />
Both forms check for overflow on the allocation size n * sizeof(...),<br />
and return NULL if that occurred.<br />
<br />
== The inline disease ==<br />
<br />
There appears to be a common misperception that gcc has a magic &quot;make me<br />
faster&quot; speedup option called &quot;inline&quot;. While the use of inlines can be<br />
appropriate (for example as a means of replacing macros, see Chapter 12), it<br />
very often is not. Abundant use of the inline keyword leads to a much bigger<br />
kernel, which in turn slows the system as a whole down, due to a bigger<br />
icache footprint for the CPU and simply because there is less memory<br />
available for the pagecache. Just think about it; a pagecache miss causes a<br />
disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles<br />
that can go into these 5 milliseconds.<br />
<br />
A reasonable rule of thumb is to not put inline at functions that have more<br />
than 3 lines of code in them. An exception to this rule are the cases where<br />
a parameter is known to be a compiletime constant, and as a result of this<br />
constantness you *know* the compiler will be able to optimize most of your<br />
function away at compile time. For a good example of this later case, see<br />
the kmalloc() inline function.<br />
<br />
Often people argue that adding inline to functions that are static and used<br />
only once is always a win since there is no space tradeoff. While this is<br />
technically correct, gcc is capable of inlining these automatically without<br />
help, and the maintenance issue of removing the inline when a second user<br />
appears outweighs the potential value of the hint that tells gcc to do<br />
something it would have done anyway.<br />
<br />
<br />
== Function return values and names ==<br />
<br />
Functions can return values of many different kinds, and one of the<br />
most common is a value indicating whether the function succeeded or<br />
failed. Such a value can be represented as an error-code integer<br />
(-Exxx = failure, 0 = success) or a &quot;succeeded&quot; boolean (0 = failure,<br />
non-zero = success).<br />
<br />
Mixing up these two sorts of representations is a fertile source of<br />
difficult-to-find bugs. If the C language included a strong distinction<br />
between integers and booleans then the compiler would find these mistakes<br />
for us... but it doesn't. To help prevent such bugs, always follow this<br />
convention:<br />
<br />
If the name of a function is an action or an imperative command,<br />
the function should return an error-code integer. If the name<br />
is a predicate, the function should return a &quot;succeeded&quot; boolean.<br />
<br />
For example, &quot;add work&quot; is a command, and the add_work() function returns 0<br />
for success or -EBUSY for failure. In the same way, &quot;PCI device present&quot; is<br />
a predicate, and the pci_dev_present() function returns 1 if it succeeds in<br />
finding a matching device or 0 if it doesn't.<br />
<br />
All EXPORTed functions must respect this convention, and so should all<br />
public functions. Private (static) functions need not, but it is<br />
recommended that they do.<br />
<br />
Functions whose return value is the actual result of a computation, rather<br />
than an indication of whether the computation succeeded, are not subject to<br />
this rule. Generally they indicate failure by returning some out-of-range<br />
result. Typical examples would be functions that return pointers; they use<br />
NULL or the ERR_PTR mechanism to report failure.<br />
<br />
<br />
== Don't re-invent the kernel macros ==<br />
<br />
The header file include/linux/kernel.h contains a number of macros that<br />
you should use, rather than explicitly coding some variant of them yourself.<br />
For example, if you need to calculate the length of an array, take advantage<br />
of the macro<br />
<br />
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))<br />
<br />
Similarly, if you need to calculate the size of some structure member, use<br />
<br />
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)-&gt;f))<br />
<br />
There are also min() and max() macros that do strict type checking if you<br />
need them. Feel free to peruse that header file to see what else is already<br />
defined that you shouldn't reproduce in your code.<br />
<br />
<br />
== Editor modelines and other cruft ==<br />
<br />
Some editors can interpret configuration information embedded in source files,<br />
indicated with special markers. For example, emacs interprets lines marked<br />
like this:<br />
<br />
-*- mode: c -*-<br />
<br />
Or like this:<br />
<br />
/*<br />
Local Variables:<br />
compile-command: &quot;gcc -DMAGIC_DEBUG_FLAG foo.c&quot;<br />
End:<br />
*/<br />
<br />
Vim interprets markers that look like this:<br />
<br />
/* vim:set sw=8 noet */<br />
<br />
Do not include any of these in source files. People have their own personal<br />
editor configurations, and your source files should not override them. This<br />
includes markers for indentation and mode configuration. People may use their<br />
own custom mode, or may have some other magic method for making indentation<br />
work correctly.<br />
<br />
== Inline assembly ==<br />
<br />
In architecture-specific code, you may need to use inline assembly to interface<br />
with CPU or platform functionality. Don't hesitate to do so when necessary.<br />
However, don't use inline assembly gratuitously when C can do the job. You can<br />
and should poke hardware from C when possible.<br />
<br />
Consider writing simple helper functions that wrap common bits of inline<br />
assembly, rather than repeatedly writing them with slight variations. Remember<br />
that inline assembly can use C parameters.<br />
<br />
Large, non-trivial assembly functions should go in .S files, with corresponding<br />
C prototypes defined in C header files. The C prototypes for assembly<br />
functions should use &quot;asmlinkage&quot;.<br />
<br />
You may need to mark your asm statement as volatile, to prevent GCC from<br />
removing it if GCC doesn't notice any side effects. You don't always need to<br />
do so, though, and doing so unnecessarily can limit optimization.<br />
<br />
When writing a single inline assembly statement containing multiple<br />
instructions, put each instruction on a separate line in a separate quoted<br />
string, and end each string except the last with \n\t to properly indent the<br />
next instruction in the assembly output:<br />
<br />
asm (&quot;magic %reg1, #42\n\t&quot;<br />
&quot;more_magic %reg2, %reg3&quot;<br />
: /* outputs */ : /* inputs */ : /* clobbers */);<br />
<br />
== References ==<br />
<br />
The C Programming Language, Second Edition<br />
by Brian W. Kernighan and Dennis M. Ritchie.<br />
Prentice Hall, Inc., 1988.<br />
ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).<br />
URL: http://cm.bell-labs.com/cm/cs/cbook/<br />
<br />
The Practice of Programming<br />
by Brian W. Kernighan and Rob Pike.<br />
Addison-Wesley, Inc., 1999.<br />
ISBN 0-201-61586-X.<br />
URL: http://cm.bell-labs.com/cm/cs/tpop/<br />
<br />
GNU manuals - where in compliance with K&amp;R and this text - for cpp, gcc,<br />
gcc internals and indent, all available from http://www.gnu.org/manual/<br />
<br />
WG14 is the international standardization working group for the programming<br />
language C, URL: http://www.open-std.org/JTC1/SC22/WG14/<br />
<br />
Kernel CodingStyle, by greg@kroah.com at OLS 2002:<br />
http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/</div>Stepanhttp://www.coreboot.org/index.php?title=Coding_Style&diff=12313Coding Style2013-12-05T18:53:06Z<p>Stepan: /* Commenting */</p>
<hr />
<div>This is a short document describing the preferred coding style for the<br />
coreboot project. It is in many ways exactly the same as the Linux kernel<br />
coding style. In fact, most of this document has been copied from the<br />
[http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/Documentation/CodingStyle?id=HEAD Linux kernel coding style]<br />
<br />
Please at least consider the points made here.<br />
<br />
First off, I'd suggest printing out a copy of the GNU coding standards,<br />
and NOT read it. Burn them, it's a great symbolic gesture.<br />
<br />
Anyway, here goes:<br />
<br />
<br />
== Indentation ==<br />
<br />
Tabs are 8 characters, and thus indentations are also 8 characters.<br />
There are heretic movements that try to make indentations 4 (or even 2!)<br />
characters deep, and that is akin to trying to define the value of PI to<br />
be 3.<br />
<br />
Rationale: The whole idea behind indentation is to clearly define where<br />
a block of control starts and ends. Especially when you've been looking<br />
at your screen for 20 straight hours, you'll find it a lot easier to see<br />
how the indentation works if you have large indentations.<br />
<br />
Now, some people will claim that having 8-character indentations makes<br />
the code move too far to the right, and makes it hard to read on a<br />
80-character terminal screen. The answer to that is that if you need<br />
more than 3 levels of indentation, you're screwed anyway, and should fix<br />
your program.<br />
<br />
In short, 8-char indents make things easier to read, and have the added<br />
benefit of warning you when you're nesting your functions too deep.<br />
Heed that warning.<br />
<br />
The preferred way to ease multiple indentation levels in a switch statement is<br />
to align the &quot;switch&quot; and its subordinate &quot;case&quot; labels in the same column<br />
instead of &quot;double-indenting&quot; the &quot;case&quot; labels. E.g.:<br />
<br />
switch (suffix) {<br />
case 'G':<br />
case 'g':<br />
mem &lt;&lt;= 30;<br />
break;<br />
case 'M':<br />
case 'm':<br />
mem &lt;&lt;= 20;<br />
break;<br />
case 'K':<br />
case 'k':<br />
mem &lt;&lt;= 10;<br />
/* fall through */<br />
default:<br />
break;<br />
}<br />
<br />
<br />
Don't put multiple statements on a single line unless you have<br />
something to hide:<br />
<br />
if (condition) do_this;<br />
do_something_everytime;<br />
<br />
Don't put multiple assignments on a single line either. Kernel coding style<br />
is super simple. Avoid tricky expressions.<br />
<br />
Outside of comments, documentation and except in Kconfig, spaces are never<br />
used for indentation, and the above example is deliberately broken.<br />
<br />
Get a decent editor and don't leave whitespace at the end of lines.<br />
<br />
== Breaking long lines and strings ==<br />
<br />
Coding style is all about readability and maintainability using commonly<br />
available tools.<br />
<br />
The limit on the length of lines is 80 columns and this is a strongly<br />
preferred limit.<br />
<br />
Statements longer than 80 columns will be broken into sensible chunks, unless<br />
exceeding 80 columns significantly increases readability and does not hide<br />
information. Descendants are always substantially shorter than the parent and<br />
are placed substantially to the right. The same applies to function headers<br />
with a long argument list. However, never break user-visible strings such as<br />
printk messages, because that breaks the ability to grep for them.<br />
<br />
<br />
== Placing Braces and Spaces ==<br />
<br />
The other issue that always comes up in C styling is the placement of<br />
braces. Unlike the indent size, there are few technical reasons to<br />
choose one placement strategy over the other, but the preferred way, as<br />
shown to us by the prophets Kernighan and Ritchie, is to put the opening<br />
brace last on the line, and put the closing brace first, thusly:<br />
<br />
if (x is true) {<br />
we do y<br />
}<br />
<br />
This applies to all non-function statement blocks (if, switch, for,<br />
while, do). E.g.:<br />
<br />
switch (action) {<br />
case KOBJ_ADD:<br />
return &quot;add&quot;;<br />
case KOBJ_REMOVE:<br />
return &quot;remove&quot;;<br />
case KOBJ_CHANGE:<br />
return &quot;change&quot;;<br />
default:<br />
return NULL;<br />
}<br />
<br />
However, there is one special case, namely functions: they have the<br />
opening brace at the beginning of the next line, thus:<br />
<br />
int function(int x)<br />
{<br />
body of function<br />
}<br />
<br />
Heretic people all over the world have claimed that this inconsistency<br />
is ... well ... inconsistent, but all right-thinking people know that<br />
(a) K&amp;R are _right_ and (b) K&amp;R are right. Besides, functions are<br />
special anyway (you can't nest them in C).<br />
<br />
Note that the closing brace is empty on a line of its own, _except_ in<br />
the cases where it is followed by a continuation of the same statement,<br />
ie a &quot;while&quot; in a do-statement or an &quot;else&quot; in an if-statement, like<br />
this:<br />
<br />
do {<br />
body of do-loop<br />
} while (condition);<br />
<br />
and<br />
<br />
if (x == y) {<br />
..<br />
} else if (x &gt; y) {<br />
...<br />
} else {<br />
....<br />
}<br />
<br />
Rationale: K&amp;R.<br />
<br />
Also, note that this brace-placement also minimizes the number of empty<br />
(or almost empty) lines, without any loss of readability. Thus, as the<br />
supply of new-lines on your screen is not a renewable resource (think<br />
25-line terminal screens here), you have more empty lines to put<br />
comments on.<br />
<br />
Do not unnecessarily use braces where a single statement will do.<br />
<br />
if (condition)<br />
action();<br />
<br />
and<br />
<br />
if (condition)<br />
do_this();<br />
else<br />
do_that();<br />
<br />
This does not apply if only one branch of a conditional statement is a single<br />
statement; in the latter case use braces in both branches:<br />
<br />
if (condition) {<br />
do_this();<br />
do_that();<br />
} else {<br />
otherwise();<br />
}<br />
<br />
=== Spaces ===<br />
<br />
Linux kernel style for use of spaces depends (mostly) on<br />
function-versus-keyword usage. Use a space after (most) keywords. The<br />
notable exceptions are sizeof, typeof, alignof, and __attribute__, which look<br />
somewhat like functions (and are usually used with parentheses in Linux,<br />
although they are not required in the language, as in: &quot;sizeof info&quot; after<br />
&quot;struct fileinfo info;&quot; is declared).<br />
<br />
So use a space after these keywords:<br />
if, switch, case, for, do, while<br />
but not with sizeof, typeof, alignof, or __attribute__. E.g.,<br />
s = sizeof(struct file);<br />
<br />
Do not add spaces around (inside) parenthesized expressions. This example is<br />
*bad*:<br />
<br />
s = sizeof( struct file );<br />
<br />
When declaring pointer data or a function that returns a pointer type, the<br />
preferred use of '*' is adjacent to the data name or function name and not<br />
adjacent to the type name. Examples:<br />
<br />
char *linux_banner;<br />
unsigned long long memparse(char *ptr, char **retptr);<br />
char *match_strdup(substring_t *s);<br />
<br />
Use one space around (on each side of) most binary and ternary operators,<br />
such as any of these:<br />
<br />
= + - &lt; &gt; * / % | &amp; ^ &lt;= &gt;= == != ? :<br />
<br />
but no space after unary operators:<br />
&amp; * + - ~ ! sizeof typeof alignof __attribute__ defined<br />
<br />
no space before the postfix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
no space after the prefix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
and no space around the '.' and &quot;-&gt;&quot; structure member operators.<br />
<br />
Do not leave trailing whitespace at the ends of lines. Some editors with<br />
&quot;smart&quot; indentation will insert whitespace at the beginning of new lines as<br />
appropriate, so you can start typing the next line of code right away.<br />
However, some such editors do not remove the whitespace if you end up not<br />
putting a line of code there, such as if you leave a blank line. As a result,<br />
you end up with lines containing trailing whitespace.<br />
<br />
Git will warn you about patches that introduce trailing whitespace, and can<br />
optionally strip the trailing whitespace for you; however, if applying a series<br />
of patches, this may make later patches in the series fail by changing their<br />
context lines.<br />
<br />
== Naming ==<br />
<br />
C is a Spartan language, and so should your naming be. Unlike Modula-2<br />
and Pascal programmers, C programmers do not use cute names like<br />
ThisVariableIsATemporaryCounter. A C programmer would call that<br />
variable &quot;tmp&quot;, which is much easier to write, and not the least more<br />
difficult to understand.<br />
<br />
HOWEVER, while mixed-case names are frowned upon, descriptive names for<br />
global variables are a must. To call a global function &quot;foo&quot; is a<br />
shooting offense.<br />
<br />
GLOBAL variables (to be used only if you _really_ need them) need to<br />
have descriptive names, as do global functions. If you have a function<br />
that counts the number of active users, you should call that<br />
&quot;count_active_users()&quot; or similar, you should _not_ call it &quot;cntusr()&quot;.<br />
<br />
Encoding the type of a function into the name (so-called Hungarian<br />
notation) is brain damaged - the compiler knows the types anyway and can<br />
check those, and it only confuses the programmer. No wonder MicroSoft<br />
makes buggy programs.<br />
<br />
LOCAL variable names should be short, and to the point. If you have<br />
some random integer loop counter, it should probably be called &quot;i&quot;.<br />
Calling it &quot;loop_counter&quot; is non-productive, if there is no chance of it<br />
being mis-understood. Similarly, &quot;tmp&quot; can be just about any type of<br />
variable that is used to hold a temporary value.<br />
<br />
If you are afraid to mix up your local variable names, you have another<br />
problem, which is called the function-growth-hormone-imbalance syndrome.<br />
See chapter 6 (Functions).<br />
<br />
<br />
== Typedefs ==<br />
<br />
Please don't use things like &quot;vps_t&quot;.<br />
<br />
It's a _mistake_ to use typedef for structures and pointers. When you see a<br />
<br />
vps_t a;<br />
<br />
in the source, what does it mean?<br />
<br />
In contrast, if it says<br />
<br />
struct virtual_container *a;<br />
<br />
you can actually tell what &quot;a&quot; is.<br />
<br />
Lots of people think that typedefs &quot;help readability&quot;. Not so. They are<br />
useful only for:<br />
<br />
(a) totally opaque objects (where the typedef is actively used to _hide_ what the object is).<br />
<br />
Example: &quot;pte_t&quot; etc. opaque objects that you can only access using<br />
the proper accessor functions.<br />
<br />
NOTE! Opaqueness and &quot;accessor functions&quot; are not good in themselves.<br />
The reason we have them for things like pte_t etc. is that there<br />
really is absolutely _zero_ portably accessible information there.<br />
<br />
(b) Clear integer types, where the abstraction _helps_ avoid confusion<br />
whether it is &quot;int&quot; or &quot;long&quot;.<br />
<br />
u8/u16/u32 are perfectly fine typedefs, although they fit into<br />
category (d) better than here.<br />
<br />
NOTE! Again - there needs to be a _reason_ for this. If something is<br />
&quot;unsigned long&quot;, then there's no reason to do<br />
<br />
typedef unsigned long myflags_t;<br />
<br />
but if there is a clear reason for why it under certain circumstances<br />
might be an &quot;unsigned int&quot; and under other configurations might be<br />
&quot;unsigned long&quot;, then by all means go ahead and use a typedef.<br />
<br />
(c) when you use sparse to literally create a _new_ type for<br />
type-checking.<br />
<br />
(d) New types which are identical to standard C99 types, in certain<br />
exceptional circumstances.<br />
<br />
Although it would only take a short amount of time for the eyes and<br />
brain to become accustomed to the standard types like 'uint32_t',<br />
some people object to their use anyway.<br />
<br />
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their<br />
signed equivalents which are identical to standard types are<br />
permitted -- although they are not mandatory in new code of your<br />
own.<br />
<br />
When editing existing code which already uses one or the other set<br />
of types, you should conform to the existing choices in that code.<br />
<br />
(e) Types safe for use in userspace.<br />
<br />
In certain structures which are visible to userspace, we cannot<br />
require C99 types and cannot use the 'u32' form above. Thus, we<br />
use __u32 and similar types in all structures which are shared<br />
with userspace.<br />
<br />
Maybe there are other cases too, but the rule should basically be to NEVER<br />
EVER use a typedef unless you can clearly match one of those rules.<br />
<br />
<br />
In general, a pointer, or a struct that has elements that can reasonably<br />
be directly accessed should _never_ be a typedef.<br />
<br />
== Functions ==<br />
<br />
Functions should be short and sweet, and do just one thing. They should<br />
fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,<br />
as we all know), and do one thing and do that well.<br />
<br />
The maximum length of a function is inversely proportional to the<br />
complexity and indentation level of that function. So, if you have a<br />
conceptually simple function that is just one long (but simple)<br />
case-statement, where you have to do lots of small things for a lot of<br />
different cases, it's OK to have a longer function.<br />
<br />
However, if you have a complex function, and you suspect that a<br />
less-than-gifted first-year high-school student might not even<br />
understand what the function is all about, you should adhere to the<br />
maximum limits all the more closely. Use helper functions with<br />
descriptive names (you can ask the compiler to in-line them if you think<br />
it's performance-critical, and it will probably do a better job of it<br />
than you would have done).<br />
<br />
Another measure of the function is the number of local variables. They<br />
shouldn't exceed 5-10, or you're doing something wrong. Re-think the<br />
function, and split it into smaller pieces. A human brain can<br />
generally easily keep track of about 7 different things, anything more<br />
and it gets confused. You know you're brilliant, but maybe you'd like<br />
to understand what you did 2 weeks from now.<br />
<br />
In source files, separate functions with one blank line. If the function is<br />
exported, the EXPORT* macro for it should follow immediately after the closing<br />
function brace line. E.g.:<br />
<br />
int system_is_up(void)<br />
{<br />
return system_state == SYSTEM_RUNNING;<br />
}<br />
EXPORT_SYMBOL(system_is_up);<br />
<br />
In function prototypes, include parameter names with their data types.<br />
Although this is not required by the C language, it is preferred in Linux<br />
because it is a simple way to add valuable information for the reader.<br />
<br />
== Centralized exiting of functions ==<br />
<br />
Albeit deprecated by some people, the equivalent of the goto statement is<br />
used frequently by compilers in form of the unconditional jump instruction.<br />
<br />
The goto statement comes in handy when a function exits from multiple<br />
locations and some common work such as cleanup has to be done. If there is no<br />
cleanup needed then just return directly.<br />
<br />
The rationale is:<br />
<br />
* unconditional statements are easier to understand and follow<br />
* nesting is reduced<br />
* errors by not updating individual exit points when making modifications are prevented<br />
* saves the compiler work to optimize redundant code away ;)<br />
<br />
int fun(int a)<br />
{<br />
int result = 0;<br />
char *buffer = kmalloc(SIZE);<br />
<br />
if (buffer == NULL)<br />
return -ENOMEM;<br />
<br />
if (condition1) {<br />
while (loop1) {<br />
...<br />
}<br />
result = 1;<br />
goto out;<br />
}<br />
...<br />
out:<br />
kfree(buffer);<br />
return result;<br />
}<br />
<br />
== Commenting ==<br />
<br />
Comments are good, but there is also a danger of over-commenting. NEVER<br />
try to explain HOW your code works in a comment: it's much better to<br />
write the code so that the _working_ is obvious, and it's a waste of<br />
time to explain badly written code.<br />
<br />
Generally, you want your comments to tell WHAT your code does, not HOW.<br />
Also, try to avoid putting comments inside a function body: if the<br />
function is so complex that you need to separately comment parts of it,<br />
you should probably go back to chapter 6 for a while. You can make<br />
small comments to note or warn about something particularly clever (or<br />
ugly), but try to avoid excess. Instead, put the comments at the head<br />
of the function, telling people what it does, and possibly WHY it does<br />
it.<br />
<br />
When commenting the kernel API functions, please use the kernel-doc format.<br />
See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc<br />
for details.<br />
<br />
coreboot style for comments is the C89 &quot;/* ... */&quot; style.<br />
You may use C99-style &quot;// ...&quot; comments.<br />
<br />
The preferred style for long (multi-line) comments is:<br />
<br />
/*<br />
* This is the preferred style for multi-line<br />
* comments in the Linux kernel source code.<br />
* Please use it consistently.<br />
*<br />
* Description: A column of asterisks on the left side,<br />
* with beginning and ending almost-blank lines.<br />
*/<br />
<br />
For files in net/ and drivers/net/ the preferred style for long (multi-line)<br />
comments is a little different.<br />
<br />
/* The preferred comment style for files in net/ and drivers/net<br />
* looks like this.<br />
*<br />
* It is nearly the same as the generally preferred comment style,<br />
* but there is no initial almost-blank line.<br />
*/<br />
<br />
It's also important to comment data, whether they are basic types or derived<br />
types. To this end, use just one data declaration per line (no commas for<br />
multiple data declarations). This leaves you room for a small comment on each<br />
item, explaining its use.<br />
<br />
== You've made a mess of it ==<br />
<br />
That's OK, we all do. You've probably been told by your long-time Unix<br />
user helper that &quot;GNU emacs&quot; automatically formats the C sources for<br />
you, and you've noticed that yes, it does do that, but the defaults it<br />
uses are less than desirable (in fact, they are worse than random<br />
typing - an infinite number of monkeys typing into GNU emacs would never<br />
make a good program).<br />
<br />
So, you can either get rid of GNU emacs, or change it to use saner<br />
values. To do the latter, you can stick the following in your .emacs file:<br />
<br />
(defun c-lineup-arglist-tabs-only (ignored)<br />
&quot;Line up argument lists by tabs, not spaces&quot;<br />
(let* ((anchor (c-langelem-pos c-syntactic-element))<br />
(column (c-langelem-2nd-pos c-syntactic-element))<br />
(offset (- (1+ column) anchor))<br />
(steps (floor offset c-basic-offset)))<br />
(* (max steps 1)<br />
c-basic-offset)))<br />
<br />
(add-hook 'c-mode-common-hook<br />
(lambda ()<br />
;; Add kernel style<br />
(c-add-style<br />
&quot;linux-tabs-only&quot;<br />
'(&quot;linux&quot; (c-offsets-alist<br />
(arglist-cont-nonempty<br />
c-lineup-gcc-asm-reg<br />
c-lineup-arglist-tabs-only))))))<br />
<br />
(add-hook 'c-mode-hook<br />
(lambda ()<br />
(let ((filename (buffer-file-name)))<br />
;; Enable kernel mode for the appropriate files<br />
(when (and filename<br />
(string-match (expand-file-name &quot;~/src/linux-trees&quot;)<br />
filename))<br />
(setq indent-tabs-mode t)<br />
(c-set-style &quot;linux-tabs-only&quot;)))))<br />
<br />
This will make emacs go better with the kernel coding style for C<br />
files below ~/src/linux-trees.<br />
<br />
But even if you fail in getting emacs to do sane formatting, not<br />
everything is lost: use &quot;indent&quot;.<br />
<br />
Now, again, GNU indent has the same brain-dead settings that GNU emacs<br />
has, which is why you need to give it a few command line options.<br />
However, that's not too bad, because even the makers of GNU indent<br />
recognize the authority of K&amp;R (the GNU people aren't evil, they are<br />
just severely misguided in this matter), so you just give indent the<br />
options &quot;-kr -i8&quot; (stands for &quot;K&amp;R, 8 character indents&quot;), or use<br />
&quot;scripts/Lindent&quot;, which indents in the latest style.<br />
<br />
&quot;indent&quot; has a lot of options, and especially when it comes to comment<br />
re-formatting you may want to take a look at the man page. But<br />
remember: &quot;indent&quot; is not a fix for bad programming.<br />
<br />
<br />
== Kconfig configuration files ==<br />
<br />
For all of the Kconfig* configuration files throughout the source tree,<br />
the indentation is somewhat different. Lines under a &quot;config&quot; definition<br />
are indented with one tab, while help text is indented an additional two<br />
spaces. Example:<br />
<br />
config AUDIT<br />
bool &quot;Auditing support&quot;<br />
depends on NET<br />
help<br />
Enable auditing infrastructure that can be used with another<br />
kernel subsystem, such as SELinux (which requires this for<br />
logging of avc messages output). Does not do system-call<br />
auditing without CONFIG_AUDITSYSCALL.<br />
<br />
Seriously dangerous features (such as write support for certain<br />
filesystems) should advertise this prominently in their prompt string:<br />
<br />
config ADFS_FS_RW<br />
bool &quot;ADFS write support (DANGEROUS)&quot;<br />
depends on ADFS_FS<br />
...<br />
<br />
For full documentation on the configuration files, see the file<br />
Documentation/kbuild/kconfig-language.txt.<br />
<br />
<br />
== Data structures ==<br />
<br />
Data structures that have visibility outside the single-threaded<br />
environment they are created and destroyed in should always have<br />
reference counts. In the kernel, garbage collection doesn't exist (and<br />
outside the kernel garbage collection is slow and inefficient), which<br />
means that you absolutely _have_ to reference count all your uses.<br />
<br />
Reference counting means that you can avoid locking, and allows multiple<br />
users to have access to the data structure in parallel - and not having<br />
to worry about the structure suddenly going away from under them just<br />
because they slept or did something else for a while.<br />
<br />
Note that locking is _not_ a replacement for reference counting.<br />
Locking is used to keep data structures coherent, while reference<br />
counting is a memory management technique. Usually both are needed, and<br />
they are not to be confused with each other.<br />
<br />
Many data structures can indeed have two levels of reference counting,<br />
when there are users of different &quot;classes&quot;. The subclass count counts<br />
the number of subclass users, and decrements the global count just once<br />
when the subclass count goes to zero.<br />
<br />
Examples of this kind of &quot;multi-level-reference-counting&quot; can be found in<br />
memory management (&quot;struct mm_struct&quot;: mm_users and mm_count), and in<br />
filesystem code (&quot;struct super_block&quot;: s_count and s_active).<br />
<br />
Remember: if another thread can find your data structure, and you don't<br />
have a reference count on it, you almost certainly have a bug.<br />
<br />
<br />
== Macros, Enums and RTL ==<br />
<br />
Names of macros defining constants and labels in enums are capitalized.<br />
<br />
#define CONSTANT 0x12345<br />
<br />
Enums are preferred when defining several related constants.<br />
<br />
CAPITALIZED macro names are appreciated but macros resembling functions<br />
may be named in lower case.<br />
<br />
Generally, inline functions are preferable to macros resembling functions.<br />
<br />
Macros with multiple statements should be enclosed in a do - while block:<br />
<br />
#define macrofun(a, b, c) \<br />
do { \<br />
if (a == 5) \<br />
do_this(b, c); \<br />
} while (0)<br />
<br />
Things to avoid when using macros:<br />
<br />
1) macros that affect control flow:<br />
<br />
#define FOO(x) \<br />
do { \<br />
if (blah(x) &lt; 0) \<br />
return -EBUGGERED; \<br />
} while(0)<br />
<br />
is a _very_ bad idea. It looks like a function call but exits the &quot;calling&quot;<br />
function; don't break the internal parsers of those who will read the code.<br />
<br />
2) macros that depend on having a local variable with a magic name:<br />
<br />
#define FOO(val) bar(index, val)<br />
<br />
might look like a good thing, but it's confusing as hell when one reads the<br />
code and it's prone to breakage from seemingly innocent changes.<br />
<br />
3) macros with arguments that are used as l-values: FOO(x) = y; will<br />
bite you if somebody e.g. turns FOO into an inline function.<br />
<br />
4) forgetting about precedence: macros defining constants using expressions<br />
must enclose the expression in parentheses. Beware of similar issues with<br />
macros using parameters.<br />
<br />
#define CONSTANT 0x4000<br />
#define CONSTEXP (CONSTANT | 3)<br />
<br />
The cpp manual deals with macros exhaustively. The gcc internals manual also<br />
covers RTL which is used frequently with assembly language in the kernel.<br />
<br />
<br />
== Printing kernel messages ==<br />
<br />
Kernel developers like to be seen as literate. Do mind the spelling<br />
of kernel messages to make a good impression. Do not use crippled<br />
words like &quot;dont&quot;; use &quot;do not&quot; or &quot;don't&quot; instead. Make the messages<br />
concise, clear, and unambiguous.<br />
<br />
Kernel messages do not have to be terminated with a period.<br />
<br />
Printing numbers in parentheses (%d) adds no value and should be avoided.<br />
<br />
There are a number of driver model diagnostic macros in &lt;linux/device.h&gt;<br />
which you should use to make sure messages are matched to the right device<br />
and driver, and are tagged with the right level: dev_err(), dev_warn(),<br />
dev_info(), and so forth. For messages that aren't associated with a<br />
particular device, &lt;linux/printk.h&gt; defines pr_debug() and pr_info().<br />
<br />
Coming up with good debugging messages can be quite a challenge; and once<br />
you have them, they can be a huge help for remote troubleshooting. Such<br />
messages should be compiled out when the DEBUG symbol is not defined (that<br />
is, by default they are not included). When you use dev_dbg() or pr_debug(),<br />
that's automatic. Many subsystems have Kconfig options to turn on -DDEBUG.<br />
A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to the<br />
ones already enabled by DEBUG.<br />
<br />
<br />
== Allocating memory ==<br />
<br />
The kernel provides the following general purpose memory allocators:<br />
kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and<br />
vzalloc(). Please refer to the API documentation for further information<br />
about them.<br />
<br />
The preferred form for passing a size of a struct is the following:<br />
<br />
p = kmalloc(sizeof(*p), ...);<br />
<br />
The alternative form where struct name is spelled out hurts readability and<br />
introduces an opportunity for a bug when the pointer variable type is changed<br />
but the corresponding sizeof that is passed to a memory allocator is not.<br />
<br />
Casting the return value which is a void pointer is redundant. The conversion<br />
from void pointer to any other pointer type is guaranteed by the C programming<br />
language.<br />
<br />
The preferred form for allocating an array is the following:<br />
<br />
p = kmalloc_array(n, sizeof(...), ...);<br />
<br />
The preferred form for allocating a zeroed array is the following:<br />
<br />
p = kcalloc(n, sizeof(...), ...);<br />
<br />
Both forms check for overflow on the allocation size n * sizeof(...),<br />
and return NULL if that occurred.<br />
<br />
<br />
== The inline disease ==<br />
<br />
There appears to be a common misperception that gcc has a magic &quot;make me<br />
faster&quot; speedup option called &quot;inline&quot;. While the use of inlines can be<br />
appropriate (for example as a means of replacing macros, see Chapter 12), it<br />
very often is not. Abundant use of the inline keyword leads to a much bigger<br />
kernel, which in turn slows the system as a whole down, due to a bigger<br />
icache footprint for the CPU and simply because there is less memory<br />
available for the pagecache. Just think about it; a pagecache miss causes a<br />
disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles<br />
that can go into these 5 milliseconds.<br />
<br />
A reasonable rule of thumb is to not put inline at functions that have more<br />
than 3 lines of code in them. An exception to this rule are the cases where<br />
a parameter is known to be a compiletime constant, and as a result of this<br />
constantness you *know* the compiler will be able to optimize most of your<br />
function away at compile time. For a good example of this later case, see<br />
the kmalloc() inline function.<br />
<br />
Often people argue that adding inline to functions that are static and used<br />
only once is always a win since there is no space tradeoff. While this is<br />
technically correct, gcc is capable of inlining these automatically without<br />
help, and the maintenance issue of removing the inline when a second user<br />
appears outweighs the potential value of the hint that tells gcc to do<br />
something it would have done anyway.<br />
<br />
<br />
== Function return values and names ==<br />
<br />
Functions can return values of many different kinds, and one of the<br />
most common is a value indicating whether the function succeeded or<br />
failed. Such a value can be represented as an error-code integer<br />
(-Exxx = failure, 0 = success) or a &quot;succeeded&quot; boolean (0 = failure,<br />
non-zero = success).<br />
<br />
Mixing up these two sorts of representations is a fertile source of<br />
difficult-to-find bugs. If the C language included a strong distinction<br />
between integers and booleans then the compiler would find these mistakes<br />
for us... but it doesn't. To help prevent such bugs, always follow this<br />
convention:<br />
<br />
If the name of a function is an action or an imperative command,<br />
the function should return an error-code integer. If the name<br />
is a predicate, the function should return a &quot;succeeded&quot; boolean.<br />
<br />
For example, &quot;add work&quot; is a command, and the add_work() function returns 0<br />
for success or -EBUSY for failure. In the same way, &quot;PCI device present&quot; is<br />
a predicate, and the pci_dev_present() function returns 1 if it succeeds in<br />
finding a matching device or 0 if it doesn't.<br />
<br />
All EXPORTed functions must respect this convention, and so should all<br />
public functions. Private (static) functions need not, but it is<br />
recommended that they do.<br />
<br />
Functions whose return value is the actual result of a computation, rather<br />
than an indication of whether the computation succeeded, are not subject to<br />
this rule. Generally they indicate failure by returning some out-of-range<br />
result. Typical examples would be functions that return pointers; they use<br />
NULL or the ERR_PTR mechanism to report failure.<br />
<br />
<br />
== Don't re-invent the kernel macros ==<br />
<br />
The header file include/linux/kernel.h contains a number of macros that<br />
you should use, rather than explicitly coding some variant of them yourself.<br />
For example, if you need to calculate the length of an array, take advantage<br />
of the macro<br />
<br />
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))<br />
<br />
Similarly, if you need to calculate the size of some structure member, use<br />
<br />
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)-&gt;f))<br />
<br />
There are also min() and max() macros that do strict type checking if you<br />
need them. Feel free to peruse that header file to see what else is already<br />
defined that you shouldn't reproduce in your code.<br />
<br />
<br />
== Editor modelines and other cruft ==<br />
<br />
Some editors can interpret configuration information embedded in source files,<br />
indicated with special markers. For example, emacs interprets lines marked<br />
like this:<br />
<br />
-*- mode: c -*-<br />
<br />
Or like this:<br />
<br />
/*<br />
Local Variables:<br />
compile-command: &quot;gcc -DMAGIC_DEBUG_FLAG foo.c&quot;<br />
End:<br />
*/<br />
<br />
Vim interprets markers that look like this:<br />
<br />
/* vim:set sw=8 noet */<br />
<br />
Do not include any of these in source files. People have their own personal<br />
editor configurations, and your source files should not override them. This<br />
includes markers for indentation and mode configuration. People may use their<br />
own custom mode, or may have some other magic method for making indentation<br />
work correctly.<br />
<br />
== Inline assembly ==<br />
<br />
In architecture-specific code, you may need to use inline assembly to interface<br />
with CPU or platform functionality. Don't hesitate to do so when necessary.<br />
However, don't use inline assembly gratuitously when C can do the job. You can<br />
and should poke hardware from C when possible.<br />
<br />
Consider writing simple helper functions that wrap common bits of inline<br />
assembly, rather than repeatedly writing them with slight variations. Remember<br />
that inline assembly can use C parameters.<br />
<br />
Large, non-trivial assembly functions should go in .S files, with corresponding<br />
C prototypes defined in C header files. The C prototypes for assembly<br />
functions should use &quot;asmlinkage&quot;.<br />
<br />
You may need to mark your asm statement as volatile, to prevent GCC from<br />
removing it if GCC doesn't notice any side effects. You don't always need to<br />
do so, though, and doing so unnecessarily can limit optimization.<br />
<br />
When writing a single inline assembly statement containing multiple<br />
instructions, put each instruction on a separate line in a separate quoted<br />
string, and end each string except the last with \n\t to properly indent the<br />
next instruction in the assembly output:<br />
<br />
asm (&quot;magic %reg1, #42\n\t&quot;<br />
&quot;more_magic %reg2, %reg3&quot;<br />
: /* outputs */ : /* inputs */ : /* clobbers */);<br />
<br />
== References ==<br />
<br />
The C Programming Language, Second Edition<br />
by Brian W. Kernighan and Dennis M. Ritchie.<br />
Prentice Hall, Inc., 1988.<br />
ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).<br />
URL: http://cm.bell-labs.com/cm/cs/cbook/<br />
<br />
The Practice of Programming<br />
by Brian W. Kernighan and Rob Pike.<br />
Addison-Wesley, Inc., 1999.<br />
ISBN 0-201-61586-X.<br />
URL: http://cm.bell-labs.com/cm/cs/tpop/<br />
<br />
GNU manuals - where in compliance with K&amp;R and this text - for cpp, gcc,<br />
gcc internals and indent, all available from http://www.gnu.org/manual/<br />
<br />
WG14 is the international standardization working group for the programming<br />
language C, URL: http://www.open-std.org/JTC1/SC22/WG14/<br />
<br />
Kernel CodingStyle, by greg@kroah.com at OLS 2002:<br />
http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/</div>Stepanhttp://www.coreboot.org/index.php?title=Coding_Style&diff=12312Coding Style2013-12-05T18:50:49Z<p>Stepan: /* Editor modelines and other cruft */</p>
<hr />
<div>This is a short document describing the preferred coding style for the<br />
coreboot project. It is in many ways exactly the same as the Linux kernel<br />
coding style. In fact, most of this document has been copied from the<br />
[http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/Documentation/CodingStyle?id=HEAD Linux kernel coding style]<br />
<br />
Please at least consider the points made here.<br />
<br />
First off, I'd suggest printing out a copy of the GNU coding standards,<br />
and NOT read it. Burn them, it's a great symbolic gesture.<br />
<br />
Anyway, here goes:<br />
<br />
<br />
== Indentation ==<br />
<br />
Tabs are 8 characters, and thus indentations are also 8 characters.<br />
There are heretic movements that try to make indentations 4 (or even 2!)<br />
characters deep, and that is akin to trying to define the value of PI to<br />
be 3.<br />
<br />
Rationale: The whole idea behind indentation is to clearly define where<br />
a block of control starts and ends. Especially when you've been looking<br />
at your screen for 20 straight hours, you'll find it a lot easier to see<br />
how the indentation works if you have large indentations.<br />
<br />
Now, some people will claim that having 8-character indentations makes<br />
the code move too far to the right, and makes it hard to read on a<br />
80-character terminal screen. The answer to that is that if you need<br />
more than 3 levels of indentation, you're screwed anyway, and should fix<br />
your program.<br />
<br />
In short, 8-char indents make things easier to read, and have the added<br />
benefit of warning you when you're nesting your functions too deep.<br />
Heed that warning.<br />
<br />
The preferred way to ease multiple indentation levels in a switch statement is<br />
to align the &quot;switch&quot; and its subordinate &quot;case&quot; labels in the same column<br />
instead of &quot;double-indenting&quot; the &quot;case&quot; labels. E.g.:<br />
<br />
switch (suffix) {<br />
case 'G':<br />
case 'g':<br />
mem &lt;&lt;= 30;<br />
break;<br />
case 'M':<br />
case 'm':<br />
mem &lt;&lt;= 20;<br />
break;<br />
case 'K':<br />
case 'k':<br />
mem &lt;&lt;= 10;<br />
/* fall through */<br />
default:<br />
break;<br />
}<br />
<br />
<br />
Don't put multiple statements on a single line unless you have<br />
something to hide:<br />
<br />
if (condition) do_this;<br />
do_something_everytime;<br />
<br />
Don't put multiple assignments on a single line either. Kernel coding style<br />
is super simple. Avoid tricky expressions.<br />
<br />
Outside of comments, documentation and except in Kconfig, spaces are never<br />
used for indentation, and the above example is deliberately broken.<br />
<br />
Get a decent editor and don't leave whitespace at the end of lines.<br />
<br />
== Breaking long lines and strings ==<br />
<br />
Coding style is all about readability and maintainability using commonly<br />
available tools.<br />
<br />
The limit on the length of lines is 80 columns and this is a strongly<br />
preferred limit.<br />
<br />
Statements longer than 80 columns will be broken into sensible chunks, unless<br />
exceeding 80 columns significantly increases readability and does not hide<br />
information. Descendants are always substantially shorter than the parent and<br />
are placed substantially to the right. The same applies to function headers<br />
with a long argument list. However, never break user-visible strings such as<br />
printk messages, because that breaks the ability to grep for them.<br />
<br />
<br />
== Placing Braces and Spaces ==<br />
<br />
The other issue that always comes up in C styling is the placement of<br />
braces. Unlike the indent size, there are few technical reasons to<br />
choose one placement strategy over the other, but the preferred way, as<br />
shown to us by the prophets Kernighan and Ritchie, is to put the opening<br />
brace last on the line, and put the closing brace first, thusly:<br />
<br />
if (x is true) {<br />
we do y<br />
}<br />
<br />
This applies to all non-function statement blocks (if, switch, for,<br />
while, do). E.g.:<br />
<br />
switch (action) {<br />
case KOBJ_ADD:<br />
return &quot;add&quot;;<br />
case KOBJ_REMOVE:<br />
return &quot;remove&quot;;<br />
case KOBJ_CHANGE:<br />
return &quot;change&quot;;<br />
default:<br />
return NULL;<br />
}<br />
<br />
However, there is one special case, namely functions: they have the<br />
opening brace at the beginning of the next line, thus:<br />
<br />
int function(int x)<br />
{<br />
body of function<br />
}<br />
<br />
Heretic people all over the world have claimed that this inconsistency<br />
is ... well ... inconsistent, but all right-thinking people know that<br />
(a) K&amp;R are _right_ and (b) K&amp;R are right. Besides, functions are<br />
special anyway (you can't nest them in C).<br />
<br />
Note that the closing brace is empty on a line of its own, _except_ in<br />
the cases where it is followed by a continuation of the same statement,<br />
ie a &quot;while&quot; in a do-statement or an &quot;else&quot; in an if-statement, like<br />
this:<br />
<br />
do {<br />
body of do-loop<br />
} while (condition);<br />
<br />
and<br />
<br />
if (x == y) {<br />
..<br />
} else if (x &gt; y) {<br />
...<br />
} else {<br />
....<br />
}<br />
<br />
Rationale: K&amp;R.<br />
<br />
Also, note that this brace-placement also minimizes the number of empty<br />
(or almost empty) lines, without any loss of readability. Thus, as the<br />
supply of new-lines on your screen is not a renewable resource (think<br />
25-line terminal screens here), you have more empty lines to put<br />
comments on.<br />
<br />
Do not unnecessarily use braces where a single statement will do.<br />
<br />
if (condition)<br />
action();<br />
<br />
and<br />
<br />
if (condition)<br />
do_this();<br />
else<br />
do_that();<br />
<br />
This does not apply if only one branch of a conditional statement is a single<br />
statement; in the latter case use braces in both branches:<br />
<br />
if (condition) {<br />
do_this();<br />
do_that();<br />
} else {<br />
otherwise();<br />
}<br />
<br />
=== Spaces ===<br />
<br />
Linux kernel style for use of spaces depends (mostly) on<br />
function-versus-keyword usage. Use a space after (most) keywords. The<br />
notable exceptions are sizeof, typeof, alignof, and __attribute__, which look<br />
somewhat like functions (and are usually used with parentheses in Linux,<br />
although they are not required in the language, as in: &quot;sizeof info&quot; after<br />
&quot;struct fileinfo info;&quot; is declared).<br />
<br />
So use a space after these keywords:<br />
if, switch, case, for, do, while<br />
but not with sizeof, typeof, alignof, or __attribute__. E.g.,<br />
s = sizeof(struct file);<br />
<br />
Do not add spaces around (inside) parenthesized expressions. This example is<br />
*bad*:<br />
<br />
s = sizeof( struct file );<br />
<br />
When declaring pointer data or a function that returns a pointer type, the<br />
preferred use of '*' is adjacent to the data name or function name and not<br />
adjacent to the type name. Examples:<br />
<br />
char *linux_banner;<br />
unsigned long long memparse(char *ptr, char **retptr);<br />
char *match_strdup(substring_t *s);<br />
<br />
Use one space around (on each side of) most binary and ternary operators,<br />
such as any of these:<br />
<br />
= + - &lt; &gt; * / % | &amp; ^ &lt;= &gt;= == != ? :<br />
<br />
but no space after unary operators:<br />
&amp; * + - ~ ! sizeof typeof alignof __attribute__ defined<br />
<br />
no space before the postfix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
no space after the prefix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
and no space around the '.' and &quot;-&gt;&quot; structure member operators.<br />
<br />
Do not leave trailing whitespace at the ends of lines. Some editors with<br />
&quot;smart&quot; indentation will insert whitespace at the beginning of new lines as<br />
appropriate, so you can start typing the next line of code right away.<br />
However, some such editors do not remove the whitespace if you end up not<br />
putting a line of code there, such as if you leave a blank line. As a result,<br />
you end up with lines containing trailing whitespace.<br />
<br />
Git will warn you about patches that introduce trailing whitespace, and can<br />
optionally strip the trailing whitespace for you; however, if applying a series<br />
of patches, this may make later patches in the series fail by changing their<br />
context lines.<br />
<br />
== Naming ==<br />
<br />
C is a Spartan language, and so should your naming be. Unlike Modula-2<br />
and Pascal programmers, C programmers do not use cute names like<br />
ThisVariableIsATemporaryCounter. A C programmer would call that<br />
variable &quot;tmp&quot;, which is much easier to write, and not the least more<br />
difficult to understand.<br />
<br />
HOWEVER, while mixed-case names are frowned upon, descriptive names for<br />
global variables are a must. To call a global function &quot;foo&quot; is a<br />
shooting offense.<br />
<br />
GLOBAL variables (to be used only if you _really_ need them) need to<br />
have descriptive names, as do global functions. If you have a function<br />
that counts the number of active users, you should call that<br />
&quot;count_active_users()&quot; or similar, you should _not_ call it &quot;cntusr()&quot;.<br />
<br />
Encoding the type of a function into the name (so-called Hungarian<br />
notation) is brain damaged - the compiler knows the types anyway and can<br />
check those, and it only confuses the programmer. No wonder MicroSoft<br />
makes buggy programs.<br />
<br />
LOCAL variable names should be short, and to the point. If you have<br />
some random integer loop counter, it should probably be called &quot;i&quot;.<br />
Calling it &quot;loop_counter&quot; is non-productive, if there is no chance of it<br />
being mis-understood. Similarly, &quot;tmp&quot; can be just about any type of<br />
variable that is used to hold a temporary value.<br />
<br />
If you are afraid to mix up your local variable names, you have another<br />
problem, which is called the function-growth-hormone-imbalance syndrome.<br />
See chapter 6 (Functions).<br />
<br />
<br />
== Typedefs ==<br />
<br />
Please don't use things like &quot;vps_t&quot;.<br />
<br />
It's a _mistake_ to use typedef for structures and pointers. When you see a<br />
<br />
vps_t a;<br />
<br />
in the source, what does it mean?<br />
<br />
In contrast, if it says<br />
<br />
struct virtual_container *a;<br />
<br />
you can actually tell what &quot;a&quot; is.<br />
<br />
Lots of people think that typedefs &quot;help readability&quot;. Not so. They are<br />
useful only for:<br />
<br />
(a) totally opaque objects (where the typedef is actively used to _hide_ what the object is).<br />
<br />
Example: &quot;pte_t&quot; etc. opaque objects that you can only access using<br />
the proper accessor functions.<br />
<br />
NOTE! Opaqueness and &quot;accessor functions&quot; are not good in themselves.<br />
The reason we have them for things like pte_t etc. is that there<br />
really is absolutely _zero_ portably accessible information there.<br />
<br />
(b) Clear integer types, where the abstraction _helps_ avoid confusion<br />
whether it is &quot;int&quot; or &quot;long&quot;.<br />
<br />
u8/u16/u32 are perfectly fine typedefs, although they fit into<br />
category (d) better than here.<br />
<br />
NOTE! Again - there needs to be a _reason_ for this. If something is<br />
&quot;unsigned long&quot;, then there's no reason to do<br />
<br />
typedef unsigned long myflags_t;<br />
<br />
but if there is a clear reason for why it under certain circumstances<br />
might be an &quot;unsigned int&quot; and under other configurations might be<br />
&quot;unsigned long&quot;, then by all means go ahead and use a typedef.<br />
<br />
(c) when you use sparse to literally create a _new_ type for<br />
type-checking.<br />
<br />
(d) New types which are identical to standard C99 types, in certain<br />
exceptional circumstances.<br />
<br />
Although it would only take a short amount of time for the eyes and<br />
brain to become accustomed to the standard types like 'uint32_t',<br />
some people object to their use anyway.<br />
<br />
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their<br />
signed equivalents which are identical to standard types are<br />
permitted -- although they are not mandatory in new code of your<br />
own.<br />
<br />
When editing existing code which already uses one or the other set<br />
of types, you should conform to the existing choices in that code.<br />
<br />
(e) Types safe for use in userspace.<br />
<br />
In certain structures which are visible to userspace, we cannot<br />
require C99 types and cannot use the 'u32' form above. Thus, we<br />
use __u32 and similar types in all structures which are shared<br />
with userspace.<br />
<br />
Maybe there are other cases too, but the rule should basically be to NEVER<br />
EVER use a typedef unless you can clearly match one of those rules.<br />
<br />
<br />
In general, a pointer, or a struct that has elements that can reasonably<br />
be directly accessed should _never_ be a typedef.<br />
<br />
== Functions ==<br />
<br />
Functions should be short and sweet, and do just one thing. They should<br />
fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,<br />
as we all know), and do one thing and do that well.<br />
<br />
The maximum length of a function is inversely proportional to the<br />
complexity and indentation level of that function. So, if you have a<br />
conceptually simple function that is just one long (but simple)<br />
case-statement, where you have to do lots of small things for a lot of<br />
different cases, it's OK to have a longer function.<br />
<br />
However, if you have a complex function, and you suspect that a<br />
less-than-gifted first-year high-school student might not even<br />
understand what the function is all about, you should adhere to the<br />
maximum limits all the more closely. Use helper functions with<br />
descriptive names (you can ask the compiler to in-line them if you think<br />
it's performance-critical, and it will probably do a better job of it<br />
than you would have done).<br />
<br />
Another measure of the function is the number of local variables. They<br />
shouldn't exceed 5-10, or you're doing something wrong. Re-think the<br />
function, and split it into smaller pieces. A human brain can<br />
generally easily keep track of about 7 different things, anything more<br />
and it gets confused. You know you're brilliant, but maybe you'd like<br />
to understand what you did 2 weeks from now.<br />
<br />
In source files, separate functions with one blank line. If the function is<br />
exported, the EXPORT* macro for it should follow immediately after the closing<br />
function brace line. E.g.:<br />
<br />
int system_is_up(void)<br />
{<br />
return system_state == SYSTEM_RUNNING;<br />
}<br />
EXPORT_SYMBOL(system_is_up);<br />
<br />
In function prototypes, include parameter names with their data types.<br />
Although this is not required by the C language, it is preferred in Linux<br />
because it is a simple way to add valuable information for the reader.<br />
<br />
== Centralized exiting of functions ==<br />
<br />
Albeit deprecated by some people, the equivalent of the goto statement is<br />
used frequently by compilers in form of the unconditional jump instruction.<br />
<br />
The goto statement comes in handy when a function exits from multiple<br />
locations and some common work such as cleanup has to be done. If there is no<br />
cleanup needed then just return directly.<br />
<br />
The rationale is:<br />
<br />
* unconditional statements are easier to understand and follow<br />
* nesting is reduced<br />
* errors by not updating individual exit points when making modifications are prevented<br />
* saves the compiler work to optimize redundant code away ;)<br />
<br />
int fun(int a)<br />
{<br />
int result = 0;<br />
char *buffer = kmalloc(SIZE);<br />
<br />
if (buffer == NULL)<br />
return -ENOMEM;<br />
<br />
if (condition1) {<br />
while (loop1) {<br />
...<br />
}<br />
result = 1;<br />
goto out;<br />
}<br />
...<br />
out:<br />
kfree(buffer);<br />
return result;<br />
}<br />
<br />
== Commenting ==<br />
<br />
Comments are good, but there is also a danger of over-commenting. NEVER<br />
try to explain HOW your code works in a comment: it's much better to<br />
write the code so that the _working_ is obvious, and it's a waste of<br />
time to explain badly written code.<br />
<br />
Generally, you want your comments to tell WHAT your code does, not HOW.<br />
Also, try to avoid putting comments inside a function body: if the<br />
function is so complex that you need to separately comment parts of it,<br />
you should probably go back to chapter 6 for a while. You can make<br />
small comments to note or warn about something particularly clever (or<br />
ugly), but try to avoid excess. Instead, put the comments at the head<br />
of the function, telling people what it does, and possibly WHY it does<br />
it.<br />
<br />
When commenting the kernel API functions, please use the kernel-doc format.<br />
See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc<br />
for details.<br />
<br />
coreboot style for comments is the C89 &quot;/* ... */&quot; style.<br />
You may use C99-style &quot;// ...&quot; comments.<br />
<br />
The preferred style for long (multi-line) comments is:<br />
<br />
/*<br />
* This is the preferred style for multi-line<br />
* comments in the Linux kernel source code.<br />
* Please use it consistently.<br />
*<br />
* Description: A column of asterisks on the left side,<br />
* with beginning and ending almost-blank lines.<br />
*/<br />
<br />
For files in net/ and drivers/net/ the preferred style for long (multi-line)<br />
comments is a little different.<br />
<br />
/* The preferred comment style for files in net/ and drivers/net<br />
* looks like this.<br />
*<br />
* It is nearly the same as the generally preferred comment style,<br />
* but there is no initial almost-blank line.<br />
*/<br />
<br />
It's also important to comment data, whether they are basic types or derived<br />
types. To this end, use just one data declaration per line (no commas for<br />
multiple data declarations). This leaves you room for a small comment on each<br />
item, explaining its use.<br />
<br />
<br />
== You've made a mess of it ==<br />
<br />
That's OK, we all do. You've probably been told by your long-time Unix<br />
user helper that &quot;GNU emacs&quot; automatically formats the C sources for<br />
you, and you've noticed that yes, it does do that, but the defaults it<br />
uses are less than desirable (in fact, they are worse than random<br />
typing - an infinite number of monkeys typing into GNU emacs would never<br />
make a good program).<br />
<br />
So, you can either get rid of GNU emacs, or change it to use saner<br />
values. To do the latter, you can stick the following in your .emacs file:<br />
<br />
(defun c-lineup-arglist-tabs-only (ignored)<br />
&quot;Line up argument lists by tabs, not spaces&quot;<br />
(let* ((anchor (c-langelem-pos c-syntactic-element))<br />
(column (c-langelem-2nd-pos c-syntactic-element))<br />
(offset (- (1+ column) anchor))<br />
(steps (floor offset c-basic-offset)))<br />
(* (max steps 1)<br />
c-basic-offset)))<br />
<br />
(add-hook 'c-mode-common-hook<br />
(lambda ()<br />
;; Add kernel style<br />
(c-add-style<br />
&quot;linux-tabs-only&quot;<br />
'(&quot;linux&quot; (c-offsets-alist<br />
(arglist-cont-nonempty<br />
c-lineup-gcc-asm-reg<br />
c-lineup-arglist-tabs-only))))))<br />
<br />
(add-hook 'c-mode-hook<br />
(lambda ()<br />
(let ((filename (buffer-file-name)))<br />
;; Enable kernel mode for the appropriate files<br />
(when (and filename<br />
(string-match (expand-file-name &quot;~/src/linux-trees&quot;)<br />
filename))<br />
(setq indent-tabs-mode t)<br />
(c-set-style &quot;linux-tabs-only&quot;)))))<br />
<br />
This will make emacs go better with the kernel coding style for C<br />
files below ~/src/linux-trees.<br />
<br />
But even if you fail in getting emacs to do sane formatting, not<br />
everything is lost: use &quot;indent&quot;.<br />
<br />
Now, again, GNU indent has the same brain-dead settings that GNU emacs<br />
has, which is why you need to give it a few command line options.<br />
However, that's not too bad, because even the makers of GNU indent<br />
recognize the authority of K&amp;R (the GNU people aren't evil, they are<br />
just severely misguided in this matter), so you just give indent the<br />
options &quot;-kr -i8&quot; (stands for &quot;K&amp;R, 8 character indents&quot;), or use<br />
&quot;scripts/Lindent&quot;, which indents in the latest style.<br />
<br />
&quot;indent&quot; has a lot of options, and especially when it comes to comment<br />
re-formatting you may want to take a look at the man page. But<br />
remember: &quot;indent&quot; is not a fix for bad programming.<br />
<br />
<br />
== Kconfig configuration files ==<br />
<br />
For all of the Kconfig* configuration files throughout the source tree,<br />
the indentation is somewhat different. Lines under a &quot;config&quot; definition<br />
are indented with one tab, while help text is indented an additional two<br />
spaces. Example:<br />
<br />
config AUDIT<br />
bool &quot;Auditing support&quot;<br />
depends on NET<br />
help<br />
Enable auditing infrastructure that can be used with another<br />
kernel subsystem, such as SELinux (which requires this for<br />
logging of avc messages output). Does not do system-call<br />
auditing without CONFIG_AUDITSYSCALL.<br />
<br />
Seriously dangerous features (such as write support for certain<br />
filesystems) should advertise this prominently in their prompt string:<br />
<br />
config ADFS_FS_RW<br />
bool &quot;ADFS write support (DANGEROUS)&quot;<br />
depends on ADFS_FS<br />
...<br />
<br />
For full documentation on the configuration files, see the file<br />
Documentation/kbuild/kconfig-language.txt.<br />
<br />
<br />
== Data structures ==<br />
<br />
Data structures that have visibility outside the single-threaded<br />
environment they are created and destroyed in should always have<br />
reference counts. In the kernel, garbage collection doesn't exist (and<br />
outside the kernel garbage collection is slow and inefficient), which<br />
means that you absolutely _have_ to reference count all your uses.<br />
<br />
Reference counting means that you can avoid locking, and allows multiple<br />
users to have access to the data structure in parallel - and not having<br />
to worry about the structure suddenly going away from under them just<br />
because they slept or did something else for a while.<br />
<br />
Note that locking is _not_ a replacement for reference counting.<br />
Locking is used to keep data structures coherent, while reference<br />
counting is a memory management technique. Usually both are needed, and<br />
they are not to be confused with each other.<br />
<br />
Many data structures can indeed have two levels of reference counting,<br />
when there are users of different &quot;classes&quot;. The subclass count counts<br />
the number of subclass users, and decrements the global count just once<br />
when the subclass count goes to zero.<br />
<br />
Examples of this kind of &quot;multi-level-reference-counting&quot; can be found in<br />
memory management (&quot;struct mm_struct&quot;: mm_users and mm_count), and in<br />
filesystem code (&quot;struct super_block&quot;: s_count and s_active).<br />
<br />
Remember: if another thread can find your data structure, and you don't<br />
have a reference count on it, you almost certainly have a bug.<br />
<br />
<br />
== Macros, Enums and RTL ==<br />
<br />
Names of macros defining constants and labels in enums are capitalized.<br />
<br />
#define CONSTANT 0x12345<br />
<br />
Enums are preferred when defining several related constants.<br />
<br />
CAPITALIZED macro names are appreciated but macros resembling functions<br />
may be named in lower case.<br />
<br />
Generally, inline functions are preferable to macros resembling functions.<br />
<br />
Macros with multiple statements should be enclosed in a do - while block:<br />
<br />
#define macrofun(a, b, c) \<br />
do { \<br />
if (a == 5) \<br />
do_this(b, c); \<br />
} while (0)<br />
<br />
Things to avoid when using macros:<br />
<br />
1) macros that affect control flow:<br />
<br />
#define FOO(x) \<br />
do { \<br />
if (blah(x) &lt; 0) \<br />
return -EBUGGERED; \<br />
} while(0)<br />
<br />
is a _very_ bad idea. It looks like a function call but exits the &quot;calling&quot;<br />
function; don't break the internal parsers of those who will read the code.<br />
<br />
2) macros that depend on having a local variable with a magic name:<br />
<br />
#define FOO(val) bar(index, val)<br />
<br />
might look like a good thing, but it's confusing as hell when one reads the<br />
code and it's prone to breakage from seemingly innocent changes.<br />
<br />
3) macros with arguments that are used as l-values: FOO(x) = y; will<br />
bite you if somebody e.g. turns FOO into an inline function.<br />
<br />
4) forgetting about precedence: macros defining constants using expressions<br />
must enclose the expression in parentheses. Beware of similar issues with<br />
macros using parameters.<br />
<br />
#define CONSTANT 0x4000<br />
#define CONSTEXP (CONSTANT | 3)<br />
<br />
The cpp manual deals with macros exhaustively. The gcc internals manual also<br />
covers RTL which is used frequently with assembly language in the kernel.<br />
<br />
<br />
== Printing kernel messages ==<br />
<br />
Kernel developers like to be seen as literate. Do mind the spelling<br />
of kernel messages to make a good impression. Do not use crippled<br />
words like &quot;dont&quot;; use &quot;do not&quot; or &quot;don't&quot; instead. Make the messages<br />
concise, clear, and unambiguous.<br />
<br />
Kernel messages do not have to be terminated with a period.<br />
<br />
Printing numbers in parentheses (%d) adds no value and should be avoided.<br />
<br />
There are a number of driver model diagnostic macros in &lt;linux/device.h&gt;<br />
which you should use to make sure messages are matched to the right device<br />
and driver, and are tagged with the right level: dev_err(), dev_warn(),<br />
dev_info(), and so forth. For messages that aren't associated with a<br />
particular device, &lt;linux/printk.h&gt; defines pr_debug() and pr_info().<br />
<br />
Coming up with good debugging messages can be quite a challenge; and once<br />
you have them, they can be a huge help for remote troubleshooting. Such<br />
messages should be compiled out when the DEBUG symbol is not defined (that<br />
is, by default they are not included). When you use dev_dbg() or pr_debug(),<br />
that's automatic. Many subsystems have Kconfig options to turn on -DDEBUG.<br />
A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to the<br />
ones already enabled by DEBUG.<br />
<br />
<br />
== Allocating memory ==<br />
<br />
The kernel provides the following general purpose memory allocators:<br />
kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and<br />
vzalloc(). Please refer to the API documentation for further information<br />
about them.<br />
<br />
The preferred form for passing a size of a struct is the following:<br />
<br />
p = kmalloc(sizeof(*p), ...);<br />
<br />
The alternative form where struct name is spelled out hurts readability and<br />
introduces an opportunity for a bug when the pointer variable type is changed<br />
but the corresponding sizeof that is passed to a memory allocator is not.<br />
<br />
Casting the return value which is a void pointer is redundant. The conversion<br />
from void pointer to any other pointer type is guaranteed by the C programming<br />
language.<br />
<br />
The preferred form for allocating an array is the following:<br />
<br />
p = kmalloc_array(n, sizeof(...), ...);<br />
<br />
The preferred form for allocating a zeroed array is the following:<br />
<br />
p = kcalloc(n, sizeof(...), ...);<br />
<br />
Both forms check for overflow on the allocation size n * sizeof(...),<br />
and return NULL if that occurred.<br />
<br />
<br />
== The inline disease ==<br />
<br />
There appears to be a common misperception that gcc has a magic &quot;make me<br />
faster&quot; speedup option called &quot;inline&quot;. While the use of inlines can be<br />
appropriate (for example as a means of replacing macros, see Chapter 12), it<br />
very often is not. Abundant use of the inline keyword leads to a much bigger<br />
kernel, which in turn slows the system as a whole down, due to a bigger<br />
icache footprint for the CPU and simply because there is less memory<br />
available for the pagecache. Just think about it; a pagecache miss causes a<br />
disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles<br />
that can go into these 5 milliseconds.<br />
<br />
A reasonable rule of thumb is to not put inline at functions that have more<br />
than 3 lines of code in them. An exception to this rule are the cases where<br />
a parameter is known to be a compiletime constant, and as a result of this<br />
constantness you *know* the compiler will be able to optimize most of your<br />
function away at compile time. For a good example of this later case, see<br />
the kmalloc() inline function.<br />
<br />
Often people argue that adding inline to functions that are static and used<br />
only once is always a win since there is no space tradeoff. While this is<br />
technically correct, gcc is capable of inlining these automatically without<br />
help, and the maintenance issue of removing the inline when a second user<br />
appears outweighs the potential value of the hint that tells gcc to do<br />
something it would have done anyway.<br />
<br />
<br />
== Function return values and names ==<br />
<br />
Functions can return values of many different kinds, and one of the<br />
most common is a value indicating whether the function succeeded or<br />
failed. Such a value can be represented as an error-code integer<br />
(-Exxx = failure, 0 = success) or a &quot;succeeded&quot; boolean (0 = failure,<br />
non-zero = success).<br />
<br />
Mixing up these two sorts of representations is a fertile source of<br />
difficult-to-find bugs. If the C language included a strong distinction<br />
between integers and booleans then the compiler would find these mistakes<br />
for us... but it doesn't. To help prevent such bugs, always follow this<br />
convention:<br />
<br />
If the name of a function is an action or an imperative command,<br />
the function should return an error-code integer. If the name<br />
is a predicate, the function should return a &quot;succeeded&quot; boolean.<br />
<br />
For example, &quot;add work&quot; is a command, and the add_work() function returns 0<br />
for success or -EBUSY for failure. In the same way, &quot;PCI device present&quot; is<br />
a predicate, and the pci_dev_present() function returns 1 if it succeeds in<br />
finding a matching device or 0 if it doesn't.<br />
<br />
All EXPORTed functions must respect this convention, and so should all<br />
public functions. Private (static) functions need not, but it is<br />
recommended that they do.<br />
<br />
Functions whose return value is the actual result of a computation, rather<br />
than an indication of whether the computation succeeded, are not subject to<br />
this rule. Generally they indicate failure by returning some out-of-range<br />
result. Typical examples would be functions that return pointers; they use<br />
NULL or the ERR_PTR mechanism to report failure.<br />
<br />
<br />
== Don't re-invent the kernel macros ==<br />
<br />
The header file include/linux/kernel.h contains a number of macros that<br />
you should use, rather than explicitly coding some variant of them yourself.<br />
For example, if you need to calculate the length of an array, take advantage<br />
of the macro<br />
<br />
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))<br />
<br />
Similarly, if you need to calculate the size of some structure member, use<br />
<br />
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)-&gt;f))<br />
<br />
There are also min() and max() macros that do strict type checking if you<br />
need them. Feel free to peruse that header file to see what else is already<br />
defined that you shouldn't reproduce in your code.<br />
<br />
<br />
== Editor modelines and other cruft ==<br />
<br />
Some editors can interpret configuration information embedded in source files,<br />
indicated with special markers. For example, emacs interprets lines marked<br />
like this:<br />
<br />
-*- mode: c -*-<br />
<br />
Or like this:<br />
<br />
/*<br />
Local Variables:<br />
compile-command: &quot;gcc -DMAGIC_DEBUG_FLAG foo.c&quot;<br />
End:<br />
*/<br />
<br />
Vim interprets markers that look like this:<br />
<br />
/* vim:set sw=8 noet */<br />
<br />
Do not include any of these in source files. People have their own personal<br />
editor configurations, and your source files should not override them. This<br />
includes markers for indentation and mode configuration. People may use their<br />
own custom mode, or may have some other magic method for making indentation<br />
work correctly.<br />
<br />
== Inline assembly ==<br />
<br />
In architecture-specific code, you may need to use inline assembly to interface<br />
with CPU or platform functionality. Don't hesitate to do so when necessary.<br />
However, don't use inline assembly gratuitously when C can do the job. You can<br />
and should poke hardware from C when possible.<br />
<br />
Consider writing simple helper functions that wrap common bits of inline<br />
assembly, rather than repeatedly writing them with slight variations. Remember<br />
that inline assembly can use C parameters.<br />
<br />
Large, non-trivial assembly functions should go in .S files, with corresponding<br />
C prototypes defined in C header files. The C prototypes for assembly<br />
functions should use &quot;asmlinkage&quot;.<br />
<br />
You may need to mark your asm statement as volatile, to prevent GCC from<br />
removing it if GCC doesn't notice any side effects. You don't always need to<br />
do so, though, and doing so unnecessarily can limit optimization.<br />
<br />
When writing a single inline assembly statement containing multiple<br />
instructions, put each instruction on a separate line in a separate quoted<br />
string, and end each string except the last with \n\t to properly indent the<br />
next instruction in the assembly output:<br />
<br />
asm (&quot;magic %reg1, #42\n\t&quot;<br />
&quot;more_magic %reg2, %reg3&quot;<br />
: /* outputs */ : /* inputs */ : /* clobbers */);<br />
<br />
== References ==<br />
<br />
The C Programming Language, Second Edition<br />
by Brian W. Kernighan and Dennis M. Ritchie.<br />
Prentice Hall, Inc., 1988.<br />
ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).<br />
URL: http://cm.bell-labs.com/cm/cs/cbook/<br />
<br />
The Practice of Programming<br />
by Brian W. Kernighan and Rob Pike.<br />
Addison-Wesley, Inc., 1999.<br />
ISBN 0-201-61586-X.<br />
URL: http://cm.bell-labs.com/cm/cs/tpop/<br />
<br />
GNU manuals - where in compliance with K&amp;R and this text - for cpp, gcc,<br />
gcc internals and indent, all available from http://www.gnu.org/manual/<br />
<br />
WG14 is the international standardization working group for the programming<br />
language C, URL: http://www.open-std.org/JTC1/SC22/WG14/<br />
<br />
Kernel CodingStyle, by greg@kroah.com at OLS 2002:<br />
http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/</div>Stepanhttp://www.coreboot.org/index.php?title=Coding_Style&diff=12311Coding Style2013-12-05T18:50:28Z<p>Stepan: /* Inline assembly */</p>
<hr />
<div>This is a short document describing the preferred coding style for the<br />
coreboot project. It is in many ways exactly the same as the Linux kernel<br />
coding style. In fact, most of this document has been copied from the<br />
[http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/Documentation/CodingStyle?id=HEAD Linux kernel coding style]<br />
<br />
Please at least consider the points made here.<br />
<br />
First off, I'd suggest printing out a copy of the GNU coding standards,<br />
and NOT read it. Burn them, it's a great symbolic gesture.<br />
<br />
Anyway, here goes:<br />
<br />
<br />
== Indentation ==<br />
<br />
Tabs are 8 characters, and thus indentations are also 8 characters.<br />
There are heretic movements that try to make indentations 4 (or even 2!)<br />
characters deep, and that is akin to trying to define the value of PI to<br />
be 3.<br />
<br />
Rationale: The whole idea behind indentation is to clearly define where<br />
a block of control starts and ends. Especially when you've been looking<br />
at your screen for 20 straight hours, you'll find it a lot easier to see<br />
how the indentation works if you have large indentations.<br />
<br />
Now, some people will claim that having 8-character indentations makes<br />
the code move too far to the right, and makes it hard to read on a<br />
80-character terminal screen. The answer to that is that if you need<br />
more than 3 levels of indentation, you're screwed anyway, and should fix<br />
your program.<br />
<br />
In short, 8-char indents make things easier to read, and have the added<br />
benefit of warning you when you're nesting your functions too deep.<br />
Heed that warning.<br />
<br />
The preferred way to ease multiple indentation levels in a switch statement is<br />
to align the &quot;switch&quot; and its subordinate &quot;case&quot; labels in the same column<br />
instead of &quot;double-indenting&quot; the &quot;case&quot; labels. E.g.:<br />
<br />
switch (suffix) {<br />
case 'G':<br />
case 'g':<br />
mem &lt;&lt;= 30;<br />
break;<br />
case 'M':<br />
case 'm':<br />
mem &lt;&lt;= 20;<br />
break;<br />
case 'K':<br />
case 'k':<br />
mem &lt;&lt;= 10;<br />
/* fall through */<br />
default:<br />
break;<br />
}<br />
<br />
<br />
Don't put multiple statements on a single line unless you have<br />
something to hide:<br />
<br />
if (condition) do_this;<br />
do_something_everytime;<br />
<br />
Don't put multiple assignments on a single line either. Kernel coding style<br />
is super simple. Avoid tricky expressions.<br />
<br />
Outside of comments, documentation and except in Kconfig, spaces are never<br />
used for indentation, and the above example is deliberately broken.<br />
<br />
Get a decent editor and don't leave whitespace at the end of lines.<br />
<br />
== Breaking long lines and strings ==<br />
<br />
Coding style is all about readability and maintainability using commonly<br />
available tools.<br />
<br />
The limit on the length of lines is 80 columns and this is a strongly<br />
preferred limit.<br />
<br />
Statements longer than 80 columns will be broken into sensible chunks, unless<br />
exceeding 80 columns significantly increases readability and does not hide<br />
information. Descendants are always substantially shorter than the parent and<br />
are placed substantially to the right. The same applies to function headers<br />
with a long argument list. However, never break user-visible strings such as<br />
printk messages, because that breaks the ability to grep for them.<br />
<br />
<br />
== Placing Braces and Spaces ==<br />
<br />
The other issue that always comes up in C styling is the placement of<br />
braces. Unlike the indent size, there are few technical reasons to<br />
choose one placement strategy over the other, but the preferred way, as<br />
shown to us by the prophets Kernighan and Ritchie, is to put the opening<br />
brace last on the line, and put the closing brace first, thusly:<br />
<br />
if (x is true) {<br />
we do y<br />
}<br />
<br />
This applies to all non-function statement blocks (if, switch, for,<br />
while, do). E.g.:<br />
<br />
switch (action) {<br />
case KOBJ_ADD:<br />
return &quot;add&quot;;<br />
case KOBJ_REMOVE:<br />
return &quot;remove&quot;;<br />
case KOBJ_CHANGE:<br />
return &quot;change&quot;;<br />
default:<br />
return NULL;<br />
}<br />
<br />
However, there is one special case, namely functions: they have the<br />
opening brace at the beginning of the next line, thus:<br />
<br />
int function(int x)<br />
{<br />
body of function<br />
}<br />
<br />
Heretic people all over the world have claimed that this inconsistency<br />
is ... well ... inconsistent, but all right-thinking people know that<br />
(a) K&amp;R are _right_ and (b) K&amp;R are right. Besides, functions are<br />
special anyway (you can't nest them in C).<br />
<br />
Note that the closing brace is empty on a line of its own, _except_ in<br />
the cases where it is followed by a continuation of the same statement,<br />
ie a &quot;while&quot; in a do-statement or an &quot;else&quot; in an if-statement, like<br />
this:<br />
<br />
do {<br />
body of do-loop<br />
} while (condition);<br />
<br />
and<br />
<br />
if (x == y) {<br />
..<br />
} else if (x &gt; y) {<br />
...<br />
} else {<br />
....<br />
}<br />
<br />
Rationale: K&amp;R.<br />
<br />
Also, note that this brace-placement also minimizes the number of empty<br />
(or almost empty) lines, without any loss of readability. Thus, as the<br />
supply of new-lines on your screen is not a renewable resource (think<br />
25-line terminal screens here), you have more empty lines to put<br />
comments on.<br />
<br />
Do not unnecessarily use braces where a single statement will do.<br />
<br />
if (condition)<br />
action();<br />
<br />
and<br />
<br />
if (condition)<br />
do_this();<br />
else<br />
do_that();<br />
<br />
This does not apply if only one branch of a conditional statement is a single<br />
statement; in the latter case use braces in both branches:<br />
<br />
if (condition) {<br />
do_this();<br />
do_that();<br />
} else {<br />
otherwise();<br />
}<br />
<br />
=== Spaces ===<br />
<br />
Linux kernel style for use of spaces depends (mostly) on<br />
function-versus-keyword usage. Use a space after (most) keywords. The<br />
notable exceptions are sizeof, typeof, alignof, and __attribute__, which look<br />
somewhat like functions (and are usually used with parentheses in Linux,<br />
although they are not required in the language, as in: &quot;sizeof info&quot; after<br />
&quot;struct fileinfo info;&quot; is declared).<br />
<br />
So use a space after these keywords:<br />
if, switch, case, for, do, while<br />
but not with sizeof, typeof, alignof, or __attribute__. E.g.,<br />
s = sizeof(struct file);<br />
<br />
Do not add spaces around (inside) parenthesized expressions. This example is<br />
*bad*:<br />
<br />
s = sizeof( struct file );<br />
<br />
When declaring pointer data or a function that returns a pointer type, the<br />
preferred use of '*' is adjacent to the data name or function name and not<br />
adjacent to the type name. Examples:<br />
<br />
char *linux_banner;<br />
unsigned long long memparse(char *ptr, char **retptr);<br />
char *match_strdup(substring_t *s);<br />
<br />
Use one space around (on each side of) most binary and ternary operators,<br />
such as any of these:<br />
<br />
= + - &lt; &gt; * / % | &amp; ^ &lt;= &gt;= == != ? :<br />
<br />
but no space after unary operators:<br />
&amp; * + - ~ ! sizeof typeof alignof __attribute__ defined<br />
<br />
no space before the postfix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
no space after the prefix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
and no space around the '.' and &quot;-&gt;&quot; structure member operators.<br />
<br />
Do not leave trailing whitespace at the ends of lines. Some editors with<br />
&quot;smart&quot; indentation will insert whitespace at the beginning of new lines as<br />
appropriate, so you can start typing the next line of code right away.<br />
However, some such editors do not remove the whitespace if you end up not<br />
putting a line of code there, such as if you leave a blank line. As a result,<br />
you end up with lines containing trailing whitespace.<br />
<br />
Git will warn you about patches that introduce trailing whitespace, and can<br />
optionally strip the trailing whitespace for you; however, if applying a series<br />
of patches, this may make later patches in the series fail by changing their<br />
context lines.<br />
<br />
== Naming ==<br />
<br />
C is a Spartan language, and so should your naming be. Unlike Modula-2<br />
and Pascal programmers, C programmers do not use cute names like<br />
ThisVariableIsATemporaryCounter. A C programmer would call that<br />
variable &quot;tmp&quot;, which is much easier to write, and not the least more<br />
difficult to understand.<br />
<br />
HOWEVER, while mixed-case names are frowned upon, descriptive names for<br />
global variables are a must. To call a global function &quot;foo&quot; is a<br />
shooting offense.<br />
<br />
GLOBAL variables (to be used only if you _really_ need them) need to<br />
have descriptive names, as do global functions. If you have a function<br />
that counts the number of active users, you should call that<br />
&quot;count_active_users()&quot; or similar, you should _not_ call it &quot;cntusr()&quot;.<br />
<br />
Encoding the type of a function into the name (so-called Hungarian<br />
notation) is brain damaged - the compiler knows the types anyway and can<br />
check those, and it only confuses the programmer. No wonder MicroSoft<br />
makes buggy programs.<br />
<br />
LOCAL variable names should be short, and to the point. If you have<br />
some random integer loop counter, it should probably be called &quot;i&quot;.<br />
Calling it &quot;loop_counter&quot; is non-productive, if there is no chance of it<br />
being mis-understood. Similarly, &quot;tmp&quot; can be just about any type of<br />
variable that is used to hold a temporary value.<br />
<br />
If you are afraid to mix up your local variable names, you have another<br />
problem, which is called the function-growth-hormone-imbalance syndrome.<br />
See chapter 6 (Functions).<br />
<br />
<br />
== Typedefs ==<br />
<br />
Please don't use things like &quot;vps_t&quot;.<br />
<br />
It's a _mistake_ to use typedef for structures and pointers. When you see a<br />
<br />
vps_t a;<br />
<br />
in the source, what does it mean?<br />
<br />
In contrast, if it says<br />
<br />
struct virtual_container *a;<br />
<br />
you can actually tell what &quot;a&quot; is.<br />
<br />
Lots of people think that typedefs &quot;help readability&quot;. Not so. They are<br />
useful only for:<br />
<br />
(a) totally opaque objects (where the typedef is actively used to _hide_ what the object is).<br />
<br />
Example: &quot;pte_t&quot; etc. opaque objects that you can only access using<br />
the proper accessor functions.<br />
<br />
NOTE! Opaqueness and &quot;accessor functions&quot; are not good in themselves.<br />
The reason we have them for things like pte_t etc. is that there<br />
really is absolutely _zero_ portably accessible information there.<br />
<br />
(b) Clear integer types, where the abstraction _helps_ avoid confusion<br />
whether it is &quot;int&quot; or &quot;long&quot;.<br />
<br />
u8/u16/u32 are perfectly fine typedefs, although they fit into<br />
category (d) better than here.<br />
<br />
NOTE! Again - there needs to be a _reason_ for this. If something is<br />
&quot;unsigned long&quot;, then there's no reason to do<br />
<br />
typedef unsigned long myflags_t;<br />
<br />
but if there is a clear reason for why it under certain circumstances<br />
might be an &quot;unsigned int&quot; and under other configurations might be<br />
&quot;unsigned long&quot;, then by all means go ahead and use a typedef.<br />
<br />
(c) when you use sparse to literally create a _new_ type for<br />
type-checking.<br />
<br />
(d) New types which are identical to standard C99 types, in certain<br />
exceptional circumstances.<br />
<br />
Although it would only take a short amount of time for the eyes and<br />
brain to become accustomed to the standard types like 'uint32_t',<br />
some people object to their use anyway.<br />
<br />
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their<br />
signed equivalents which are identical to standard types are<br />
permitted -- although they are not mandatory in new code of your<br />
own.<br />
<br />
When editing existing code which already uses one or the other set<br />
of types, you should conform to the existing choices in that code.<br />
<br />
(e) Types safe for use in userspace.<br />
<br />
In certain structures which are visible to userspace, we cannot<br />
require C99 types and cannot use the 'u32' form above. Thus, we<br />
use __u32 and similar types in all structures which are shared<br />
with userspace.<br />
<br />
Maybe there are other cases too, but the rule should basically be to NEVER<br />
EVER use a typedef unless you can clearly match one of those rules.<br />
<br />
<br />
In general, a pointer, or a struct that has elements that can reasonably<br />
be directly accessed should _never_ be a typedef.<br />
<br />
== Functions ==<br />
<br />
Functions should be short and sweet, and do just one thing. They should<br />
fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,<br />
as we all know), and do one thing and do that well.<br />
<br />
The maximum length of a function is inversely proportional to the<br />
complexity and indentation level of that function. So, if you have a<br />
conceptually simple function that is just one long (but simple)<br />
case-statement, where you have to do lots of small things for a lot of<br />
different cases, it's OK to have a longer function.<br />
<br />
However, if you have a complex function, and you suspect that a<br />
less-than-gifted first-year high-school student might not even<br />
understand what the function is all about, you should adhere to the<br />
maximum limits all the more closely. Use helper functions with<br />
descriptive names (you can ask the compiler to in-line them if you think<br />
it's performance-critical, and it will probably do a better job of it<br />
than you would have done).<br />
<br />
Another measure of the function is the number of local variables. They<br />
shouldn't exceed 5-10, or you're doing something wrong. Re-think the<br />
function, and split it into smaller pieces. A human brain can<br />
generally easily keep track of about 7 different things, anything more<br />
and it gets confused. You know you're brilliant, but maybe you'd like<br />
to understand what you did 2 weeks from now.<br />
<br />
In source files, separate functions with one blank line. If the function is<br />
exported, the EXPORT* macro for it should follow immediately after the closing<br />
function brace line. E.g.:<br />
<br />
int system_is_up(void)<br />
{<br />
return system_state == SYSTEM_RUNNING;<br />
}<br />
EXPORT_SYMBOL(system_is_up);<br />
<br />
In function prototypes, include parameter names with their data types.<br />
Although this is not required by the C language, it is preferred in Linux<br />
because it is a simple way to add valuable information for the reader.<br />
<br />
== Centralized exiting of functions ==<br />
<br />
Albeit deprecated by some people, the equivalent of the goto statement is<br />
used frequently by compilers in form of the unconditional jump instruction.<br />
<br />
The goto statement comes in handy when a function exits from multiple<br />
locations and some common work such as cleanup has to be done. If there is no<br />
cleanup needed then just return directly.<br />
<br />
The rationale is:<br />
<br />
* unconditional statements are easier to understand and follow<br />
* nesting is reduced<br />
* errors by not updating individual exit points when making modifications are prevented<br />
* saves the compiler work to optimize redundant code away ;)<br />
<br />
int fun(int a)<br />
{<br />
int result = 0;<br />
char *buffer = kmalloc(SIZE);<br />
<br />
if (buffer == NULL)<br />
return -ENOMEM;<br />
<br />
if (condition1) {<br />
while (loop1) {<br />
...<br />
}<br />
result = 1;<br />
goto out;<br />
}<br />
...<br />
out:<br />
kfree(buffer);<br />
return result;<br />
}<br />
<br />
== Commenting ==<br />
<br />
Comments are good, but there is also a danger of over-commenting. NEVER<br />
try to explain HOW your code works in a comment: it's much better to<br />
write the code so that the _working_ is obvious, and it's a waste of<br />
time to explain badly written code.<br />
<br />
Generally, you want your comments to tell WHAT your code does, not HOW.<br />
Also, try to avoid putting comments inside a function body: if the<br />
function is so complex that you need to separately comment parts of it,<br />
you should probably go back to chapter 6 for a while. You can make<br />
small comments to note or warn about something particularly clever (or<br />
ugly), but try to avoid excess. Instead, put the comments at the head<br />
of the function, telling people what it does, and possibly WHY it does<br />
it.<br />
<br />
When commenting the kernel API functions, please use the kernel-doc format.<br />
See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc<br />
for details.<br />
<br />
coreboot style for comments is the C89 &quot;/* ... */&quot; style.<br />
You may use C99-style &quot;// ...&quot; comments.<br />
<br />
The preferred style for long (multi-line) comments is:<br />
<br />
/*<br />
* This is the preferred style for multi-line<br />
* comments in the Linux kernel source code.<br />
* Please use it consistently.<br />
*<br />
* Description: A column of asterisks on the left side,<br />
* with beginning and ending almost-blank lines.<br />
*/<br />
<br />
For files in net/ and drivers/net/ the preferred style for long (multi-line)<br />
comments is a little different.<br />
<br />
/* The preferred comment style for files in net/ and drivers/net<br />
* looks like this.<br />
*<br />
* It is nearly the same as the generally preferred comment style,<br />
* but there is no initial almost-blank line.<br />
*/<br />
<br />
It's also important to comment data, whether they are basic types or derived<br />
types. To this end, use just one data declaration per line (no commas for<br />
multiple data declarations). This leaves you room for a small comment on each<br />
item, explaining its use.<br />
<br />
<br />
== You've made a mess of it ==<br />
<br />
That's OK, we all do. You've probably been told by your long-time Unix<br />
user helper that &quot;GNU emacs&quot; automatically formats the C sources for<br />
you, and you've noticed that yes, it does do that, but the defaults it<br />
uses are less than desirable (in fact, they are worse than random<br />
typing - an infinite number of monkeys typing into GNU emacs would never<br />
make a good program).<br />
<br />
So, you can either get rid of GNU emacs, or change it to use saner<br />
values. To do the latter, you can stick the following in your .emacs file:<br />
<br />
(defun c-lineup-arglist-tabs-only (ignored)<br />
&quot;Line up argument lists by tabs, not spaces&quot;<br />
(let* ((anchor (c-langelem-pos c-syntactic-element))<br />
(column (c-langelem-2nd-pos c-syntactic-element))<br />
(offset (- (1+ column) anchor))<br />
(steps (floor offset c-basic-offset)))<br />
(* (max steps 1)<br />
c-basic-offset)))<br />
<br />
(add-hook 'c-mode-common-hook<br />
(lambda ()<br />
;; Add kernel style<br />
(c-add-style<br />
&quot;linux-tabs-only&quot;<br />
'(&quot;linux&quot; (c-offsets-alist<br />
(arglist-cont-nonempty<br />
c-lineup-gcc-asm-reg<br />
c-lineup-arglist-tabs-only))))))<br />
<br />
(add-hook 'c-mode-hook<br />
(lambda ()<br />
(let ((filename (buffer-file-name)))<br />
;; Enable kernel mode for the appropriate files<br />
(when (and filename<br />
(string-match (expand-file-name &quot;~/src/linux-trees&quot;)<br />
filename))<br />
(setq indent-tabs-mode t)<br />
(c-set-style &quot;linux-tabs-only&quot;)))))<br />
<br />
This will make emacs go better with the kernel coding style for C<br />
files below ~/src/linux-trees.<br />
<br />
But even if you fail in getting emacs to do sane formatting, not<br />
everything is lost: use &quot;indent&quot;.<br />
<br />
Now, again, GNU indent has the same brain-dead settings that GNU emacs<br />
has, which is why you need to give it a few command line options.<br />
However, that's not too bad, because even the makers of GNU indent<br />
recognize the authority of K&amp;R (the GNU people aren't evil, they are<br />
just severely misguided in this matter), so you just give indent the<br />
options &quot;-kr -i8&quot; (stands for &quot;K&amp;R, 8 character indents&quot;), or use<br />
&quot;scripts/Lindent&quot;, which indents in the latest style.<br />
<br />
&quot;indent&quot; has a lot of options, and especially when it comes to comment<br />
re-formatting you may want to take a look at the man page. But<br />
remember: &quot;indent&quot; is not a fix for bad programming.<br />
<br />
<br />
== Kconfig configuration files ==<br />
<br />
For all of the Kconfig* configuration files throughout the source tree,<br />
the indentation is somewhat different. Lines under a &quot;config&quot; definition<br />
are indented with one tab, while help text is indented an additional two<br />
spaces. Example:<br />
<br />
config AUDIT<br />
bool &quot;Auditing support&quot;<br />
depends on NET<br />
help<br />
Enable auditing infrastructure that can be used with another<br />
kernel subsystem, such as SELinux (which requires this for<br />
logging of avc messages output). Does not do system-call<br />
auditing without CONFIG_AUDITSYSCALL.<br />
<br />
Seriously dangerous features (such as write support for certain<br />
filesystems) should advertise this prominently in their prompt string:<br />
<br />
config ADFS_FS_RW<br />
bool &quot;ADFS write support (DANGEROUS)&quot;<br />
depends on ADFS_FS<br />
...<br />
<br />
For full documentation on the configuration files, see the file<br />
Documentation/kbuild/kconfig-language.txt.<br />
<br />
<br />
== Data structures ==<br />
<br />
Data structures that have visibility outside the single-threaded<br />
environment they are created and destroyed in should always have<br />
reference counts. In the kernel, garbage collection doesn't exist (and<br />
outside the kernel garbage collection is slow and inefficient), which<br />
means that you absolutely _have_ to reference count all your uses.<br />
<br />
Reference counting means that you can avoid locking, and allows multiple<br />
users to have access to the data structure in parallel - and not having<br />
to worry about the structure suddenly going away from under them just<br />
because they slept or did something else for a while.<br />
<br />
Note that locking is _not_ a replacement for reference counting.<br />
Locking is used to keep data structures coherent, while reference<br />
counting is a memory management technique. Usually both are needed, and<br />
they are not to be confused with each other.<br />
<br />
Many data structures can indeed have two levels of reference counting,<br />
when there are users of different &quot;classes&quot;. The subclass count counts<br />
the number of subclass users, and decrements the global count just once<br />
when the subclass count goes to zero.<br />
<br />
Examples of this kind of &quot;multi-level-reference-counting&quot; can be found in<br />
memory management (&quot;struct mm_struct&quot;: mm_users and mm_count), and in<br />
filesystem code (&quot;struct super_block&quot;: s_count and s_active).<br />
<br />
Remember: if another thread can find your data structure, and you don't<br />
have a reference count on it, you almost certainly have a bug.<br />
<br />
<br />
== Macros, Enums and RTL ==<br />
<br />
Names of macros defining constants and labels in enums are capitalized.<br />
<br />
#define CONSTANT 0x12345<br />
<br />
Enums are preferred when defining several related constants.<br />
<br />
CAPITALIZED macro names are appreciated but macros resembling functions<br />
may be named in lower case.<br />
<br />
Generally, inline functions are preferable to macros resembling functions.<br />
<br />
Macros with multiple statements should be enclosed in a do - while block:<br />
<br />
#define macrofun(a, b, c) \<br />
do { \<br />
if (a == 5) \<br />
do_this(b, c); \<br />
} while (0)<br />
<br />
Things to avoid when using macros:<br />
<br />
1) macros that affect control flow:<br />
<br />
#define FOO(x) \<br />
do { \<br />
if (blah(x) &lt; 0) \<br />
return -EBUGGERED; \<br />
} while(0)<br />
<br />
is a _very_ bad idea. It looks like a function call but exits the &quot;calling&quot;<br />
function; don't break the internal parsers of those who will read the code.<br />
<br />
2) macros that depend on having a local variable with a magic name:<br />
<br />
#define FOO(val) bar(index, val)<br />
<br />
might look like a good thing, but it's confusing as hell when one reads the<br />
code and it's prone to breakage from seemingly innocent changes.<br />
<br />
3) macros with arguments that are used as l-values: FOO(x) = y; will<br />
bite you if somebody e.g. turns FOO into an inline function.<br />
<br />
4) forgetting about precedence: macros defining constants using expressions<br />
must enclose the expression in parentheses. Beware of similar issues with<br />
macros using parameters.<br />
<br />
#define CONSTANT 0x4000<br />
#define CONSTEXP (CONSTANT | 3)<br />
<br />
The cpp manual deals with macros exhaustively. The gcc internals manual also<br />
covers RTL which is used frequently with assembly language in the kernel.<br />
<br />
<br />
== Printing kernel messages ==<br />
<br />
Kernel developers like to be seen as literate. Do mind the spelling<br />
of kernel messages to make a good impression. Do not use crippled<br />
words like &quot;dont&quot;; use &quot;do not&quot; or &quot;don't&quot; instead. Make the messages<br />
concise, clear, and unambiguous.<br />
<br />
Kernel messages do not have to be terminated with a period.<br />
<br />
Printing numbers in parentheses (%d) adds no value and should be avoided.<br />
<br />
There are a number of driver model diagnostic macros in &lt;linux/device.h&gt;<br />
which you should use to make sure messages are matched to the right device<br />
and driver, and are tagged with the right level: dev_err(), dev_warn(),<br />
dev_info(), and so forth. For messages that aren't associated with a<br />
particular device, &lt;linux/printk.h&gt; defines pr_debug() and pr_info().<br />
<br />
Coming up with good debugging messages can be quite a challenge; and once<br />
you have them, they can be a huge help for remote troubleshooting. Such<br />
messages should be compiled out when the DEBUG symbol is not defined (that<br />
is, by default they are not included). When you use dev_dbg() or pr_debug(),<br />
that's automatic. Many subsystems have Kconfig options to turn on -DDEBUG.<br />
A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to the<br />
ones already enabled by DEBUG.<br />
<br />
<br />
== Allocating memory ==<br />
<br />
The kernel provides the following general purpose memory allocators:<br />
kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and<br />
vzalloc(). Please refer to the API documentation for further information<br />
about them.<br />
<br />
The preferred form for passing a size of a struct is the following:<br />
<br />
p = kmalloc(sizeof(*p), ...);<br />
<br />
The alternative form where struct name is spelled out hurts readability and<br />
introduces an opportunity for a bug when the pointer variable type is changed<br />
but the corresponding sizeof that is passed to a memory allocator is not.<br />
<br />
Casting the return value which is a void pointer is redundant. The conversion<br />
from void pointer to any other pointer type is guaranteed by the C programming<br />
language.<br />
<br />
The preferred form for allocating an array is the following:<br />
<br />
p = kmalloc_array(n, sizeof(...), ...);<br />
<br />
The preferred form for allocating a zeroed array is the following:<br />
<br />
p = kcalloc(n, sizeof(...), ...);<br />
<br />
Both forms check for overflow on the allocation size n * sizeof(...),<br />
and return NULL if that occurred.<br />
<br />
<br />
== The inline disease ==<br />
<br />
There appears to be a common misperception that gcc has a magic &quot;make me<br />
faster&quot; speedup option called &quot;inline&quot;. While the use of inlines can be<br />
appropriate (for example as a means of replacing macros, see Chapter 12), it<br />
very often is not. Abundant use of the inline keyword leads to a much bigger<br />
kernel, which in turn slows the system as a whole down, due to a bigger<br />
icache footprint for the CPU and simply because there is less memory<br />
available for the pagecache. Just think about it; a pagecache miss causes a<br />
disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles<br />
that can go into these 5 milliseconds.<br />
<br />
A reasonable rule of thumb is to not put inline at functions that have more<br />
than 3 lines of code in them. An exception to this rule are the cases where<br />
a parameter is known to be a compiletime constant, and as a result of this<br />
constantness you *know* the compiler will be able to optimize most of your<br />
function away at compile time. For a good example of this later case, see<br />
the kmalloc() inline function.<br />
<br />
Often people argue that adding inline to functions that are static and used<br />
only once is always a win since there is no space tradeoff. While this is<br />
technically correct, gcc is capable of inlining these automatically without<br />
help, and the maintenance issue of removing the inline when a second user<br />
appears outweighs the potential value of the hint that tells gcc to do<br />
something it would have done anyway.<br />
<br />
<br />
== Function return values and names ==<br />
<br />
Functions can return values of many different kinds, and one of the<br />
most common is a value indicating whether the function succeeded or<br />
failed. Such a value can be represented as an error-code integer<br />
(-Exxx = failure, 0 = success) or a &quot;succeeded&quot; boolean (0 = failure,<br />
non-zero = success).<br />
<br />
Mixing up these two sorts of representations is a fertile source of<br />
difficult-to-find bugs. If the C language included a strong distinction<br />
between integers and booleans then the compiler would find these mistakes<br />
for us... but it doesn't. To help prevent such bugs, always follow this<br />
convention:<br />
<br />
If the name of a function is an action or an imperative command,<br />
the function should return an error-code integer. If the name<br />
is a predicate, the function should return a &quot;succeeded&quot; boolean.<br />
<br />
For example, &quot;add work&quot; is a command, and the add_work() function returns 0<br />
for success or -EBUSY for failure. In the same way, &quot;PCI device present&quot; is<br />
a predicate, and the pci_dev_present() function returns 1 if it succeeds in<br />
finding a matching device or 0 if it doesn't.<br />
<br />
All EXPORTed functions must respect this convention, and so should all<br />
public functions. Private (static) functions need not, but it is<br />
recommended that they do.<br />
<br />
Functions whose return value is the actual result of a computation, rather<br />
than an indication of whether the computation succeeded, are not subject to<br />
this rule. Generally they indicate failure by returning some out-of-range<br />
result. Typical examples would be functions that return pointers; they use<br />
NULL or the ERR_PTR mechanism to report failure.<br />
<br />
<br />
== Don't re-invent the kernel macros ==<br />
<br />
The header file include/linux/kernel.h contains a number of macros that<br />
you should use, rather than explicitly coding some variant of them yourself.<br />
For example, if you need to calculate the length of an array, take advantage<br />
of the macro<br />
<br />
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))<br />
<br />
Similarly, if you need to calculate the size of some structure member, use<br />
<br />
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)-&gt;f))<br />
<br />
There are also min() and max() macros that do strict type checking if you<br />
need them. Feel free to peruse that header file to see what else is already<br />
defined that you shouldn't reproduce in your code.<br />
<br />
<br />
== Editor modelines and other cruft ==<br />
<br />
Some editors can interpret configuration information embedded in source files,<br />
indicated with special markers. For example, emacs interprets lines marked<br />
like this:<br />
<br />
-*- mode: c -*-<br />
<br />
Or like this:<br />
<br />
/*<br />
Local Variables:<br />
compile-command: &quot;gcc -DMAGIC_DEBUG_FLAG foo.c&quot;<br />
End:<br />
*/<br />
<br />
Vim interprets markers that look like this:<br />
<br />
/* vim:set sw=8 noet */<br />
<br />
Do not include any of these in source files. People have their own personal<br />
editor configurations, and your source files should not override them. This<br />
includes markers for indentation and mode configuration. People may use their<br />
own custom mode, or may have some other magic method for making indentation<br />
work correctly.<br />
<br />
<br />
== Inline assembly ==<br />
<br />
In architecture-specific code, you may need to use inline assembly to interface<br />
with CPU or platform functionality. Don't hesitate to do so when necessary.<br />
However, don't use inline assembly gratuitously when C can do the job. You can<br />
and should poke hardware from C when possible.<br />
<br />
Consider writing simple helper functions that wrap common bits of inline<br />
assembly, rather than repeatedly writing them with slight variations. Remember<br />
that inline assembly can use C parameters.<br />
<br />
Large, non-trivial assembly functions should go in .S files, with corresponding<br />
C prototypes defined in C header files. The C prototypes for assembly<br />
functions should use &quot;asmlinkage&quot;.<br />
<br />
You may need to mark your asm statement as volatile, to prevent GCC from<br />
removing it if GCC doesn't notice any side effects. You don't always need to<br />
do so, though, and doing so unnecessarily can limit optimization.<br />
<br />
When writing a single inline assembly statement containing multiple<br />
instructions, put each instruction on a separate line in a separate quoted<br />
string, and end each string except the last with \n\t to properly indent the<br />
next instruction in the assembly output:<br />
<br />
asm (&quot;magic %reg1, #42\n\t&quot;<br />
&quot;more_magic %reg2, %reg3&quot;<br />
: /* outputs */ : /* inputs */ : /* clobbers */);<br />
<br />
== References ==<br />
<br />
The C Programming Language, Second Edition<br />
by Brian W. Kernighan and Dennis M. Ritchie.<br />
Prentice Hall, Inc., 1988.<br />
ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).<br />
URL: http://cm.bell-labs.com/cm/cs/cbook/<br />
<br />
The Practice of Programming<br />
by Brian W. Kernighan and Rob Pike.<br />
Addison-Wesley, Inc., 1999.<br />
ISBN 0-201-61586-X.<br />
URL: http://cm.bell-labs.com/cm/cs/tpop/<br />
<br />
GNU manuals - where in compliance with K&amp;R and this text - for cpp, gcc,<br />
gcc internals and indent, all available from http://www.gnu.org/manual/<br />
<br />
WG14 is the international standardization working group for the programming<br />
language C, URL: http://www.open-std.org/JTC1/SC22/WG14/<br />
<br />
Kernel CodingStyle, by greg@kroah.com at OLS 2002:<br />
http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/</div>Stepanhttp://www.coreboot.org/index.php?title=Coding_Style&diff=12310Coding Style2013-12-05T18:50:07Z<p>Stepan: /* Centralized exiting of functions */</p>
<hr />
<div>This is a short document describing the preferred coding style for the<br />
coreboot project. It is in many ways exactly the same as the Linux kernel<br />
coding style. In fact, most of this document has been copied from the<br />
[http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/Documentation/CodingStyle?id=HEAD Linux kernel coding style]<br />
<br />
Please at least consider the points made here.<br />
<br />
First off, I'd suggest printing out a copy of the GNU coding standards,<br />
and NOT read it. Burn them, it's a great symbolic gesture.<br />
<br />
Anyway, here goes:<br />
<br />
<br />
== Indentation ==<br />
<br />
Tabs are 8 characters, and thus indentations are also 8 characters.<br />
There are heretic movements that try to make indentations 4 (or even 2!)<br />
characters deep, and that is akin to trying to define the value of PI to<br />
be 3.<br />
<br />
Rationale: The whole idea behind indentation is to clearly define where<br />
a block of control starts and ends. Especially when you've been looking<br />
at your screen for 20 straight hours, you'll find it a lot easier to see<br />
how the indentation works if you have large indentations.<br />
<br />
Now, some people will claim that having 8-character indentations makes<br />
the code move too far to the right, and makes it hard to read on a<br />
80-character terminal screen. The answer to that is that if you need<br />
more than 3 levels of indentation, you're screwed anyway, and should fix<br />
your program.<br />
<br />
In short, 8-char indents make things easier to read, and have the added<br />
benefit of warning you when you're nesting your functions too deep.<br />
Heed that warning.<br />
<br />
The preferred way to ease multiple indentation levels in a switch statement is<br />
to align the &quot;switch&quot; and its subordinate &quot;case&quot; labels in the same column<br />
instead of &quot;double-indenting&quot; the &quot;case&quot; labels. E.g.:<br />
<br />
switch (suffix) {<br />
case 'G':<br />
case 'g':<br />
mem &lt;&lt;= 30;<br />
break;<br />
case 'M':<br />
case 'm':<br />
mem &lt;&lt;= 20;<br />
break;<br />
case 'K':<br />
case 'k':<br />
mem &lt;&lt;= 10;<br />
/* fall through */<br />
default:<br />
break;<br />
}<br />
<br />
<br />
Don't put multiple statements on a single line unless you have<br />
something to hide:<br />
<br />
if (condition) do_this;<br />
do_something_everytime;<br />
<br />
Don't put multiple assignments on a single line either. Kernel coding style<br />
is super simple. Avoid tricky expressions.<br />
<br />
Outside of comments, documentation and except in Kconfig, spaces are never<br />
used for indentation, and the above example is deliberately broken.<br />
<br />
Get a decent editor and don't leave whitespace at the end of lines.<br />
<br />
== Breaking long lines and strings ==<br />
<br />
Coding style is all about readability and maintainability using commonly<br />
available tools.<br />
<br />
The limit on the length of lines is 80 columns and this is a strongly<br />
preferred limit.<br />
<br />
Statements longer than 80 columns will be broken into sensible chunks, unless<br />
exceeding 80 columns significantly increases readability and does not hide<br />
information. Descendants are always substantially shorter than the parent and<br />
are placed substantially to the right. The same applies to function headers<br />
with a long argument list. However, never break user-visible strings such as<br />
printk messages, because that breaks the ability to grep for them.<br />
<br />
<br />
== Placing Braces and Spaces ==<br />
<br />
The other issue that always comes up in C styling is the placement of<br />
braces. Unlike the indent size, there are few technical reasons to<br />
choose one placement strategy over the other, but the preferred way, as<br />
shown to us by the prophets Kernighan and Ritchie, is to put the opening<br />
brace last on the line, and put the closing brace first, thusly:<br />
<br />
if (x is true) {<br />
we do y<br />
}<br />
<br />
This applies to all non-function statement blocks (if, switch, for,<br />
while, do). E.g.:<br />
<br />
switch (action) {<br />
case KOBJ_ADD:<br />
return &quot;add&quot;;<br />
case KOBJ_REMOVE:<br />
return &quot;remove&quot;;<br />
case KOBJ_CHANGE:<br />
return &quot;change&quot;;<br />
default:<br />
return NULL;<br />
}<br />
<br />
However, there is one special case, namely functions: they have the<br />
opening brace at the beginning of the next line, thus:<br />
<br />
int function(int x)<br />
{<br />
body of function<br />
}<br />
<br />
Heretic people all over the world have claimed that this inconsistency<br />
is ... well ... inconsistent, but all right-thinking people know that<br />
(a) K&amp;R are _right_ and (b) K&amp;R are right. Besides, functions are<br />
special anyway (you can't nest them in C).<br />
<br />
Note that the closing brace is empty on a line of its own, _except_ in<br />
the cases where it is followed by a continuation of the same statement,<br />
ie a &quot;while&quot; in a do-statement or an &quot;else&quot; in an if-statement, like<br />
this:<br />
<br />
do {<br />
body of do-loop<br />
} while (condition);<br />
<br />
and<br />
<br />
if (x == y) {<br />
..<br />
} else if (x &gt; y) {<br />
...<br />
} else {<br />
....<br />
}<br />
<br />
Rationale: K&amp;R.<br />
<br />
Also, note that this brace-placement also minimizes the number of empty<br />
(or almost empty) lines, without any loss of readability. Thus, as the<br />
supply of new-lines on your screen is not a renewable resource (think<br />
25-line terminal screens here), you have more empty lines to put<br />
comments on.<br />
<br />
Do not unnecessarily use braces where a single statement will do.<br />
<br />
if (condition)<br />
action();<br />
<br />
and<br />
<br />
if (condition)<br />
do_this();<br />
else<br />
do_that();<br />
<br />
This does not apply if only one branch of a conditional statement is a single<br />
statement; in the latter case use braces in both branches:<br />
<br />
if (condition) {<br />
do_this();<br />
do_that();<br />
} else {<br />
otherwise();<br />
}<br />
<br />
=== Spaces ===<br />
<br />
Linux kernel style for use of spaces depends (mostly) on<br />
function-versus-keyword usage. Use a space after (most) keywords. The<br />
notable exceptions are sizeof, typeof, alignof, and __attribute__, which look<br />
somewhat like functions (and are usually used with parentheses in Linux,<br />
although they are not required in the language, as in: &quot;sizeof info&quot; after<br />
&quot;struct fileinfo info;&quot; is declared).<br />
<br />
So use a space after these keywords:<br />
if, switch, case, for, do, while<br />
but not with sizeof, typeof, alignof, or __attribute__. E.g.,<br />
s = sizeof(struct file);<br />
<br />
Do not add spaces around (inside) parenthesized expressions. This example is<br />
*bad*:<br />
<br />
s = sizeof( struct file );<br />
<br />
When declaring pointer data or a function that returns a pointer type, the<br />
preferred use of '*' is adjacent to the data name or function name and not<br />
adjacent to the type name. Examples:<br />
<br />
char *linux_banner;<br />
unsigned long long memparse(char *ptr, char **retptr);<br />
char *match_strdup(substring_t *s);<br />
<br />
Use one space around (on each side of) most binary and ternary operators,<br />
such as any of these:<br />
<br />
= + - &lt; &gt; * / % | &amp; ^ &lt;= &gt;= == != ? :<br />
<br />
but no space after unary operators:<br />
&amp; * + - ~ ! sizeof typeof alignof __attribute__ defined<br />
<br />
no space before the postfix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
no space after the prefix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
and no space around the '.' and &quot;-&gt;&quot; structure member operators.<br />
<br />
Do not leave trailing whitespace at the ends of lines. Some editors with<br />
&quot;smart&quot; indentation will insert whitespace at the beginning of new lines as<br />
appropriate, so you can start typing the next line of code right away.<br />
However, some such editors do not remove the whitespace if you end up not<br />
putting a line of code there, such as if you leave a blank line. As a result,<br />
you end up with lines containing trailing whitespace.<br />
<br />
Git will warn you about patches that introduce trailing whitespace, and can<br />
optionally strip the trailing whitespace for you; however, if applying a series<br />
of patches, this may make later patches in the series fail by changing their<br />
context lines.<br />
<br />
== Naming ==<br />
<br />
C is a Spartan language, and so should your naming be. Unlike Modula-2<br />
and Pascal programmers, C programmers do not use cute names like<br />
ThisVariableIsATemporaryCounter. A C programmer would call that<br />
variable &quot;tmp&quot;, which is much easier to write, and not the least more<br />
difficult to understand.<br />
<br />
HOWEVER, while mixed-case names are frowned upon, descriptive names for<br />
global variables are a must. To call a global function &quot;foo&quot; is a<br />
shooting offense.<br />
<br />
GLOBAL variables (to be used only if you _really_ need them) need to<br />
have descriptive names, as do global functions. If you have a function<br />
that counts the number of active users, you should call that<br />
&quot;count_active_users()&quot; or similar, you should _not_ call it &quot;cntusr()&quot;.<br />
<br />
Encoding the type of a function into the name (so-called Hungarian<br />
notation) is brain damaged - the compiler knows the types anyway and can<br />
check those, and it only confuses the programmer. No wonder MicroSoft<br />
makes buggy programs.<br />
<br />
LOCAL variable names should be short, and to the point. If you have<br />
some random integer loop counter, it should probably be called &quot;i&quot;.<br />
Calling it &quot;loop_counter&quot; is non-productive, if there is no chance of it<br />
being mis-understood. Similarly, &quot;tmp&quot; can be just about any type of<br />
variable that is used to hold a temporary value.<br />
<br />
If you are afraid to mix up your local variable names, you have another<br />
problem, which is called the function-growth-hormone-imbalance syndrome.<br />
See chapter 6 (Functions).<br />
<br />
<br />
== Typedefs ==<br />
<br />
Please don't use things like &quot;vps_t&quot;.<br />
<br />
It's a _mistake_ to use typedef for structures and pointers. When you see a<br />
<br />
vps_t a;<br />
<br />
in the source, what does it mean?<br />
<br />
In contrast, if it says<br />
<br />
struct virtual_container *a;<br />
<br />
you can actually tell what &quot;a&quot; is.<br />
<br />
Lots of people think that typedefs &quot;help readability&quot;. Not so. They are<br />
useful only for:<br />
<br />
(a) totally opaque objects (where the typedef is actively used to _hide_ what the object is).<br />
<br />
Example: &quot;pte_t&quot; etc. opaque objects that you can only access using<br />
the proper accessor functions.<br />
<br />
NOTE! Opaqueness and &quot;accessor functions&quot; are not good in themselves.<br />
The reason we have them for things like pte_t etc. is that there<br />
really is absolutely _zero_ portably accessible information there.<br />
<br />
(b) Clear integer types, where the abstraction _helps_ avoid confusion<br />
whether it is &quot;int&quot; or &quot;long&quot;.<br />
<br />
u8/u16/u32 are perfectly fine typedefs, although they fit into<br />
category (d) better than here.<br />
<br />
NOTE! Again - there needs to be a _reason_ for this. If something is<br />
&quot;unsigned long&quot;, then there's no reason to do<br />
<br />
typedef unsigned long myflags_t;<br />
<br />
but if there is a clear reason for why it under certain circumstances<br />
might be an &quot;unsigned int&quot; and under other configurations might be<br />
&quot;unsigned long&quot;, then by all means go ahead and use a typedef.<br />
<br />
(c) when you use sparse to literally create a _new_ type for<br />
type-checking.<br />
<br />
(d) New types which are identical to standard C99 types, in certain<br />
exceptional circumstances.<br />
<br />
Although it would only take a short amount of time for the eyes and<br />
brain to become accustomed to the standard types like 'uint32_t',<br />
some people object to their use anyway.<br />
<br />
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their<br />
signed equivalents which are identical to standard types are<br />
permitted -- although they are not mandatory in new code of your<br />
own.<br />
<br />
When editing existing code which already uses one or the other set<br />
of types, you should conform to the existing choices in that code.<br />
<br />
(e) Types safe for use in userspace.<br />
<br />
In certain structures which are visible to userspace, we cannot<br />
require C99 types and cannot use the 'u32' form above. Thus, we<br />
use __u32 and similar types in all structures which are shared<br />
with userspace.<br />
<br />
Maybe there are other cases too, but the rule should basically be to NEVER<br />
EVER use a typedef unless you can clearly match one of those rules.<br />
<br />
<br />
In general, a pointer, or a struct that has elements that can reasonably<br />
be directly accessed should _never_ be a typedef.<br />
<br />
== Functions ==<br />
<br />
Functions should be short and sweet, and do just one thing. They should<br />
fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,<br />
as we all know), and do one thing and do that well.<br />
<br />
The maximum length of a function is inversely proportional to the<br />
complexity and indentation level of that function. So, if you have a<br />
conceptually simple function that is just one long (but simple)<br />
case-statement, where you have to do lots of small things for a lot of<br />
different cases, it's OK to have a longer function.<br />
<br />
However, if you have a complex function, and you suspect that a<br />
less-than-gifted first-year high-school student might not even<br />
understand what the function is all about, you should adhere to the<br />
maximum limits all the more closely. Use helper functions with<br />
descriptive names (you can ask the compiler to in-line them if you think<br />
it's performance-critical, and it will probably do a better job of it<br />
than you would have done).<br />
<br />
Another measure of the function is the number of local variables. They<br />
shouldn't exceed 5-10, or you're doing something wrong. Re-think the<br />
function, and split it into smaller pieces. A human brain can<br />
generally easily keep track of about 7 different things, anything more<br />
and it gets confused. You know you're brilliant, but maybe you'd like<br />
to understand what you did 2 weeks from now.<br />
<br />
In source files, separate functions with one blank line. If the function is<br />
exported, the EXPORT* macro for it should follow immediately after the closing<br />
function brace line. E.g.:<br />
<br />
int system_is_up(void)<br />
{<br />
return system_state == SYSTEM_RUNNING;<br />
}<br />
EXPORT_SYMBOL(system_is_up);<br />
<br />
In function prototypes, include parameter names with their data types.<br />
Although this is not required by the C language, it is preferred in Linux<br />
because it is a simple way to add valuable information for the reader.<br />
<br />
== Centralized exiting of functions ==<br />
<br />
Albeit deprecated by some people, the equivalent of the goto statement is<br />
used frequently by compilers in form of the unconditional jump instruction.<br />
<br />
The goto statement comes in handy when a function exits from multiple<br />
locations and some common work such as cleanup has to be done. If there is no<br />
cleanup needed then just return directly.<br />
<br />
The rationale is:<br />
<br />
* unconditional statements are easier to understand and follow<br />
* nesting is reduced<br />
* errors by not updating individual exit points when making modifications are prevented<br />
* saves the compiler work to optimize redundant code away ;)<br />
<br />
int fun(int a)<br />
{<br />
int result = 0;<br />
char *buffer = kmalloc(SIZE);<br />
<br />
if (buffer == NULL)<br />
return -ENOMEM;<br />
<br />
if (condition1) {<br />
while (loop1) {<br />
...<br />
}<br />
result = 1;<br />
goto out;<br />
}<br />
...<br />
out:<br />
kfree(buffer);<br />
return result;<br />
}<br />
<br />
== Commenting ==<br />
<br />
Comments are good, but there is also a danger of over-commenting. NEVER<br />
try to explain HOW your code works in a comment: it's much better to<br />
write the code so that the _working_ is obvious, and it's a waste of<br />
time to explain badly written code.<br />
<br />
Generally, you want your comments to tell WHAT your code does, not HOW.<br />
Also, try to avoid putting comments inside a function body: if the<br />
function is so complex that you need to separately comment parts of it,<br />
you should probably go back to chapter 6 for a while. You can make<br />
small comments to note or warn about something particularly clever (or<br />
ugly), but try to avoid excess. Instead, put the comments at the head<br />
of the function, telling people what it does, and possibly WHY it does<br />
it.<br />
<br />
When commenting the kernel API functions, please use the kernel-doc format.<br />
See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc<br />
for details.<br />
<br />
coreboot style for comments is the C89 &quot;/* ... */&quot; style.<br />
You may use C99-style &quot;// ...&quot; comments.<br />
<br />
The preferred style for long (multi-line) comments is:<br />
<br />
/*<br />
* This is the preferred style for multi-line<br />
* comments in the Linux kernel source code.<br />
* Please use it consistently.<br />
*<br />
* Description: A column of asterisks on the left side,<br />
* with beginning and ending almost-blank lines.<br />
*/<br />
<br />
For files in net/ and drivers/net/ the preferred style for long (multi-line)<br />
comments is a little different.<br />
<br />
/* The preferred comment style for files in net/ and drivers/net<br />
* looks like this.<br />
*<br />
* It is nearly the same as the generally preferred comment style,<br />
* but there is no initial almost-blank line.<br />
*/<br />
<br />
It's also important to comment data, whether they are basic types or derived<br />
types. To this end, use just one data declaration per line (no commas for<br />
multiple data declarations). This leaves you room for a small comment on each<br />
item, explaining its use.<br />
<br />
<br />
== You've made a mess of it ==<br />
<br />
That's OK, we all do. You've probably been told by your long-time Unix<br />
user helper that &quot;GNU emacs&quot; automatically formats the C sources for<br />
you, and you've noticed that yes, it does do that, but the defaults it<br />
uses are less than desirable (in fact, they are worse than random<br />
typing - an infinite number of monkeys typing into GNU emacs would never<br />
make a good program).<br />
<br />
So, you can either get rid of GNU emacs, or change it to use saner<br />
values. To do the latter, you can stick the following in your .emacs file:<br />
<br />
(defun c-lineup-arglist-tabs-only (ignored)<br />
&quot;Line up argument lists by tabs, not spaces&quot;<br />
(let* ((anchor (c-langelem-pos c-syntactic-element))<br />
(column (c-langelem-2nd-pos c-syntactic-element))<br />
(offset (- (1+ column) anchor))<br />
(steps (floor offset c-basic-offset)))<br />
(* (max steps 1)<br />
c-basic-offset)))<br />
<br />
(add-hook 'c-mode-common-hook<br />
(lambda ()<br />
;; Add kernel style<br />
(c-add-style<br />
&quot;linux-tabs-only&quot;<br />
'(&quot;linux&quot; (c-offsets-alist<br />
(arglist-cont-nonempty<br />
c-lineup-gcc-asm-reg<br />
c-lineup-arglist-tabs-only))))))<br />
<br />
(add-hook 'c-mode-hook<br />
(lambda ()<br />
(let ((filename (buffer-file-name)))<br />
;; Enable kernel mode for the appropriate files<br />
(when (and filename<br />
(string-match (expand-file-name &quot;~/src/linux-trees&quot;)<br />
filename))<br />
(setq indent-tabs-mode t)<br />
(c-set-style &quot;linux-tabs-only&quot;)))))<br />
<br />
This will make emacs go better with the kernel coding style for C<br />
files below ~/src/linux-trees.<br />
<br />
But even if you fail in getting emacs to do sane formatting, not<br />
everything is lost: use &quot;indent&quot;.<br />
<br />
Now, again, GNU indent has the same brain-dead settings that GNU emacs<br />
has, which is why you need to give it a few command line options.<br />
However, that's not too bad, because even the makers of GNU indent<br />
recognize the authority of K&amp;R (the GNU people aren't evil, they are<br />
just severely misguided in this matter), so you just give indent the<br />
options &quot;-kr -i8&quot; (stands for &quot;K&amp;R, 8 character indents&quot;), or use<br />
&quot;scripts/Lindent&quot;, which indents in the latest style.<br />
<br />
&quot;indent&quot; has a lot of options, and especially when it comes to comment<br />
re-formatting you may want to take a look at the man page. But<br />
remember: &quot;indent&quot; is not a fix for bad programming.<br />
<br />
<br />
== Kconfig configuration files ==<br />
<br />
For all of the Kconfig* configuration files throughout the source tree,<br />
the indentation is somewhat different. Lines under a &quot;config&quot; definition<br />
are indented with one tab, while help text is indented an additional two<br />
spaces. Example:<br />
<br />
config AUDIT<br />
bool &quot;Auditing support&quot;<br />
depends on NET<br />
help<br />
Enable auditing infrastructure that can be used with another<br />
kernel subsystem, such as SELinux (which requires this for<br />
logging of avc messages output). Does not do system-call<br />
auditing without CONFIG_AUDITSYSCALL.<br />
<br />
Seriously dangerous features (such as write support for certain<br />
filesystems) should advertise this prominently in their prompt string:<br />
<br />
config ADFS_FS_RW<br />
bool &quot;ADFS write support (DANGEROUS)&quot;<br />
depends on ADFS_FS<br />
...<br />
<br />
For full documentation on the configuration files, see the file<br />
Documentation/kbuild/kconfig-language.txt.<br />
<br />
<br />
== Data structures ==<br />
<br />
Data structures that have visibility outside the single-threaded<br />
environment they are created and destroyed in should always have<br />
reference counts. In the kernel, garbage collection doesn't exist (and<br />
outside the kernel garbage collection is slow and inefficient), which<br />
means that you absolutely _have_ to reference count all your uses.<br />
<br />
Reference counting means that you can avoid locking, and allows multiple<br />
users to have access to the data structure in parallel - and not having<br />
to worry about the structure suddenly going away from under them just<br />
because they slept or did something else for a while.<br />
<br />
Note that locking is _not_ a replacement for reference counting.<br />
Locking is used to keep data structures coherent, while reference<br />
counting is a memory management technique. Usually both are needed, and<br />
they are not to be confused with each other.<br />
<br />
Many data structures can indeed have two levels of reference counting,<br />
when there are users of different &quot;classes&quot;. The subclass count counts<br />
the number of subclass users, and decrements the global count just once<br />
when the subclass count goes to zero.<br />
<br />
Examples of this kind of &quot;multi-level-reference-counting&quot; can be found in<br />
memory management (&quot;struct mm_struct&quot;: mm_users and mm_count), and in<br />
filesystem code (&quot;struct super_block&quot;: s_count and s_active).<br />
<br />
Remember: if another thread can find your data structure, and you don't<br />
have a reference count on it, you almost certainly have a bug.<br />
<br />
<br />
== Macros, Enums and RTL ==<br />
<br />
Names of macros defining constants and labels in enums are capitalized.<br />
<br />
#define CONSTANT 0x12345<br />
<br />
Enums are preferred when defining several related constants.<br />
<br />
CAPITALIZED macro names are appreciated but macros resembling functions<br />
may be named in lower case.<br />
<br />
Generally, inline functions are preferable to macros resembling functions.<br />
<br />
Macros with multiple statements should be enclosed in a do - while block:<br />
<br />
#define macrofun(a, b, c) \<br />
do { \<br />
if (a == 5) \<br />
do_this(b, c); \<br />
} while (0)<br />
<br />
Things to avoid when using macros:<br />
<br />
1) macros that affect control flow:<br />
<br />
#define FOO(x) \<br />
do { \<br />
if (blah(x) &lt; 0) \<br />
return -EBUGGERED; \<br />
} while(0)<br />
<br />
is a _very_ bad idea. It looks like a function call but exits the &quot;calling&quot;<br />
function; don't break the internal parsers of those who will read the code.<br />
<br />
2) macros that depend on having a local variable with a magic name:<br />
<br />
#define FOO(val) bar(index, val)<br />
<br />
might look like a good thing, but it's confusing as hell when one reads the<br />
code and it's prone to breakage from seemingly innocent changes.<br />
<br />
3) macros with arguments that are used as l-values: FOO(x) = y; will<br />
bite you if somebody e.g. turns FOO into an inline function.<br />
<br />
4) forgetting about precedence: macros defining constants using expressions<br />
must enclose the expression in parentheses. Beware of similar issues with<br />
macros using parameters.<br />
<br />
#define CONSTANT 0x4000<br />
#define CONSTEXP (CONSTANT | 3)<br />
<br />
The cpp manual deals with macros exhaustively. The gcc internals manual also<br />
covers RTL which is used frequently with assembly language in the kernel.<br />
<br />
<br />
== Printing kernel messages ==<br />
<br />
Kernel developers like to be seen as literate. Do mind the spelling<br />
of kernel messages to make a good impression. Do not use crippled<br />
words like &quot;dont&quot;; use &quot;do not&quot; or &quot;don't&quot; instead. Make the messages<br />
concise, clear, and unambiguous.<br />
<br />
Kernel messages do not have to be terminated with a period.<br />
<br />
Printing numbers in parentheses (%d) adds no value and should be avoided.<br />
<br />
There are a number of driver model diagnostic macros in &lt;linux/device.h&gt;<br />
which you should use to make sure messages are matched to the right device<br />
and driver, and are tagged with the right level: dev_err(), dev_warn(),<br />
dev_info(), and so forth. For messages that aren't associated with a<br />
particular device, &lt;linux/printk.h&gt; defines pr_debug() and pr_info().<br />
<br />
Coming up with good debugging messages can be quite a challenge; and once<br />
you have them, they can be a huge help for remote troubleshooting. Such<br />
messages should be compiled out when the DEBUG symbol is not defined (that<br />
is, by default they are not included). When you use dev_dbg() or pr_debug(),<br />
that's automatic. Many subsystems have Kconfig options to turn on -DDEBUG.<br />
A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to the<br />
ones already enabled by DEBUG.<br />
<br />
<br />
== Allocating memory ==<br />
<br />
The kernel provides the following general purpose memory allocators:<br />
kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and<br />
vzalloc(). Please refer to the API documentation for further information<br />
about them.<br />
<br />
The preferred form for passing a size of a struct is the following:<br />
<br />
p = kmalloc(sizeof(*p), ...);<br />
<br />
The alternative form where struct name is spelled out hurts readability and<br />
introduces an opportunity for a bug when the pointer variable type is changed<br />
but the corresponding sizeof that is passed to a memory allocator is not.<br />
<br />
Casting the return value which is a void pointer is redundant. The conversion<br />
from void pointer to any other pointer type is guaranteed by the C programming<br />
language.<br />
<br />
The preferred form for allocating an array is the following:<br />
<br />
p = kmalloc_array(n, sizeof(...), ...);<br />
<br />
The preferred form for allocating a zeroed array is the following:<br />
<br />
p = kcalloc(n, sizeof(...), ...);<br />
<br />
Both forms check for overflow on the allocation size n * sizeof(...),<br />
and return NULL if that occurred.<br />
<br />
<br />
== The inline disease ==<br />
<br />
There appears to be a common misperception that gcc has a magic &quot;make me<br />
faster&quot; speedup option called &quot;inline&quot;. While the use of inlines can be<br />
appropriate (for example as a means of replacing macros, see Chapter 12), it<br />
very often is not. Abundant use of the inline keyword leads to a much bigger<br />
kernel, which in turn slows the system as a whole down, due to a bigger<br />
icache footprint for the CPU and simply because there is less memory<br />
available for the pagecache. Just think about it; a pagecache miss causes a<br />
disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles<br />
that can go into these 5 milliseconds.<br />
<br />
A reasonable rule of thumb is to not put inline at functions that have more<br />
than 3 lines of code in them. An exception to this rule are the cases where<br />
a parameter is known to be a compiletime constant, and as a result of this<br />
constantness you *know* the compiler will be able to optimize most of your<br />
function away at compile time. For a good example of this later case, see<br />
the kmalloc() inline function.<br />
<br />
Often people argue that adding inline to functions that are static and used<br />
only once is always a win since there is no space tradeoff. While this is<br />
technically correct, gcc is capable of inlining these automatically without<br />
help, and the maintenance issue of removing the inline when a second user<br />
appears outweighs the potential value of the hint that tells gcc to do<br />
something it would have done anyway.<br />
<br />
<br />
== Function return values and names ==<br />
<br />
Functions can return values of many different kinds, and one of the<br />
most common is a value indicating whether the function succeeded or<br />
failed. Such a value can be represented as an error-code integer<br />
(-Exxx = failure, 0 = success) or a &quot;succeeded&quot; boolean (0 = failure,<br />
non-zero = success).<br />
<br />
Mixing up these two sorts of representations is a fertile source of<br />
difficult-to-find bugs. If the C language included a strong distinction<br />
between integers and booleans then the compiler would find these mistakes<br />
for us... but it doesn't. To help prevent such bugs, always follow this<br />
convention:<br />
<br />
If the name of a function is an action or an imperative command,<br />
the function should return an error-code integer. If the name<br />
is a predicate, the function should return a &quot;succeeded&quot; boolean.<br />
<br />
For example, &quot;add work&quot; is a command, and the add_work() function returns 0<br />
for success or -EBUSY for failure. In the same way, &quot;PCI device present&quot; is<br />
a predicate, and the pci_dev_present() function returns 1 if it succeeds in<br />
finding a matching device or 0 if it doesn't.<br />
<br />
All EXPORTed functions must respect this convention, and so should all<br />
public functions. Private (static) functions need not, but it is<br />
recommended that they do.<br />
<br />
Functions whose return value is the actual result of a computation, rather<br />
than an indication of whether the computation succeeded, are not subject to<br />
this rule. Generally they indicate failure by returning some out-of-range<br />
result. Typical examples would be functions that return pointers; they use<br />
NULL or the ERR_PTR mechanism to report failure.<br />
<br />
<br />
== Don't re-invent the kernel macros ==<br />
<br />
The header file include/linux/kernel.h contains a number of macros that<br />
you should use, rather than explicitly coding some variant of them yourself.<br />
For example, if you need to calculate the length of an array, take advantage<br />
of the macro<br />
<br />
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))<br />
<br />
Similarly, if you need to calculate the size of some structure member, use<br />
<br />
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)-&gt;f))<br />
<br />
There are also min() and max() macros that do strict type checking if you<br />
need them. Feel free to peruse that header file to see what else is already<br />
defined that you shouldn't reproduce in your code.<br />
<br />
<br />
== Editor modelines and other cruft ==<br />
<br />
Some editors can interpret configuration information embedded in source files,<br />
indicated with special markers. For example, emacs interprets lines marked<br />
like this:<br />
<br />
-*- mode: c -*-<br />
<br />
Or like this:<br />
<br />
/*<br />
Local Variables:<br />
compile-command: &quot;gcc -DMAGIC_DEBUG_FLAG foo.c&quot;<br />
End:<br />
*/<br />
<br />
Vim interprets markers that look like this:<br />
<br />
/* vim:set sw=8 noet */<br />
<br />
Do not include any of these in source files. People have their own personal<br />
editor configurations, and your source files should not override them. This<br />
includes markers for indentation and mode configuration. People may use their<br />
own custom mode, or may have some other magic method for making indentation<br />
work correctly.<br />
<br />
<br />
== Inline assembly ==<br />
<br />
In architecture-specific code, you may need to use inline assembly to interface<br />
with CPU or platform functionality. Don't hesitate to do so when necessary.<br />
However, don't use inline assembly gratuitously when C can do the job. You can<br />
and should poke hardware from C when possible.<br />
<br />
Consider writing simple helper functions that wrap common bits of inline<br />
assembly, rather than repeatedly writing them with slight variations. Remember<br />
that inline assembly can use C parameters.<br />
<br />
Large, non-trivial assembly functions should go in .S files, with corresponding<br />
C prototypes defined in C header files. The C prototypes for assembly<br />
functions should use &quot;asmlinkage&quot;.<br />
<br />
You may need to mark your asm statement as volatile, to prevent GCC from<br />
removing it if GCC doesn't notice any side effects. You don't always need to<br />
do so, though, and doing so unnecessarily can limit optimization.<br />
<br />
When writing a single inline assembly statement containing multiple<br />
instructions, put each instruction on a separate line in a separate quoted<br />
string, and end each string except the last with \n\t to properly indent the<br />
next instruction in the assembly output:<br />
<br />
asm (&quot;magic %reg1, #42\n\t&quot;<br />
&quot;more_magic %reg2, %reg3&quot;<br />
: /* outputs */ : /* inputs */ : /* clobbers */);<br />
<br />
<br />
<br />
== References ==<br />
<br />
The C Programming Language, Second Edition<br />
by Brian W. Kernighan and Dennis M. Ritchie.<br />
Prentice Hall, Inc., 1988.<br />
ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).<br />
URL: http://cm.bell-labs.com/cm/cs/cbook/<br />
<br />
The Practice of Programming<br />
by Brian W. Kernighan and Rob Pike.<br />
Addison-Wesley, Inc., 1999.<br />
ISBN 0-201-61586-X.<br />
URL: http://cm.bell-labs.com/cm/cs/tpop/<br />
<br />
GNU manuals - where in compliance with K&amp;R and this text - for cpp, gcc,<br />
gcc internals and indent, all available from http://www.gnu.org/manual/<br />
<br />
WG14 is the international standardization working group for the programming<br />
language C, URL: http://www.open-std.org/JTC1/SC22/WG14/<br />
<br />
Kernel CodingStyle, by greg@kroah.com at OLS 2002:<br />
http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/</div>Stepanhttp://www.coreboot.org/index.php?title=Coding_Style&diff=12309Coding Style2013-12-05T18:48:55Z<p>Stepan: /* Centralized exiting of functions */</p>
<hr />
<div>This is a short document describing the preferred coding style for the<br />
coreboot project. It is in many ways exactly the same as the Linux kernel<br />
coding style. In fact, most of this document has been copied from the<br />
[http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/Documentation/CodingStyle?id=HEAD Linux kernel coding style]<br />
<br />
Please at least consider the points made here.<br />
<br />
First off, I'd suggest printing out a copy of the GNU coding standards,<br />
and NOT read it. Burn them, it's a great symbolic gesture.<br />
<br />
Anyway, here goes:<br />
<br />
<br />
== Indentation ==<br />
<br />
Tabs are 8 characters, and thus indentations are also 8 characters.<br />
There are heretic movements that try to make indentations 4 (or even 2!)<br />
characters deep, and that is akin to trying to define the value of PI to<br />
be 3.<br />
<br />
Rationale: The whole idea behind indentation is to clearly define where<br />
a block of control starts and ends. Especially when you've been looking<br />
at your screen for 20 straight hours, you'll find it a lot easier to see<br />
how the indentation works if you have large indentations.<br />
<br />
Now, some people will claim that having 8-character indentations makes<br />
the code move too far to the right, and makes it hard to read on a<br />
80-character terminal screen. The answer to that is that if you need<br />
more than 3 levels of indentation, you're screwed anyway, and should fix<br />
your program.<br />
<br />
In short, 8-char indents make things easier to read, and have the added<br />
benefit of warning you when you're nesting your functions too deep.<br />
Heed that warning.<br />
<br />
The preferred way to ease multiple indentation levels in a switch statement is<br />
to align the &quot;switch&quot; and its subordinate &quot;case&quot; labels in the same column<br />
instead of &quot;double-indenting&quot; the &quot;case&quot; labels. E.g.:<br />
<br />
switch (suffix) {<br />
case 'G':<br />
case 'g':<br />
mem &lt;&lt;= 30;<br />
break;<br />
case 'M':<br />
case 'm':<br />
mem &lt;&lt;= 20;<br />
break;<br />
case 'K':<br />
case 'k':<br />
mem &lt;&lt;= 10;<br />
/* fall through */<br />
default:<br />
break;<br />
}<br />
<br />
<br />
Don't put multiple statements on a single line unless you have<br />
something to hide:<br />
<br />
if (condition) do_this;<br />
do_something_everytime;<br />
<br />
Don't put multiple assignments on a single line either. Kernel coding style<br />
is super simple. Avoid tricky expressions.<br />
<br />
Outside of comments, documentation and except in Kconfig, spaces are never<br />
used for indentation, and the above example is deliberately broken.<br />
<br />
Get a decent editor and don't leave whitespace at the end of lines.<br />
<br />
== Breaking long lines and strings ==<br />
<br />
Coding style is all about readability and maintainability using commonly<br />
available tools.<br />
<br />
The limit on the length of lines is 80 columns and this is a strongly<br />
preferred limit.<br />
<br />
Statements longer than 80 columns will be broken into sensible chunks, unless<br />
exceeding 80 columns significantly increases readability and does not hide<br />
information. Descendants are always substantially shorter than the parent and<br />
are placed substantially to the right. The same applies to function headers<br />
with a long argument list. However, never break user-visible strings such as<br />
printk messages, because that breaks the ability to grep for them.<br />
<br />
<br />
== Placing Braces and Spaces ==<br />
<br />
The other issue that always comes up in C styling is the placement of<br />
braces. Unlike the indent size, there are few technical reasons to<br />
choose one placement strategy over the other, but the preferred way, as<br />
shown to us by the prophets Kernighan and Ritchie, is to put the opening<br />
brace last on the line, and put the closing brace first, thusly:<br />
<br />
if (x is true) {<br />
we do y<br />
}<br />
<br />
This applies to all non-function statement blocks (if, switch, for,<br />
while, do). E.g.:<br />
<br />
switch (action) {<br />
case KOBJ_ADD:<br />
return &quot;add&quot;;<br />
case KOBJ_REMOVE:<br />
return &quot;remove&quot;;<br />
case KOBJ_CHANGE:<br />
return &quot;change&quot;;<br />
default:<br />
return NULL;<br />
}<br />
<br />
However, there is one special case, namely functions: they have the<br />
opening brace at the beginning of the next line, thus:<br />
<br />
int function(int x)<br />
{<br />
body of function<br />
}<br />
<br />
Heretic people all over the world have claimed that this inconsistency<br />
is ... well ... inconsistent, but all right-thinking people know that<br />
(a) K&amp;R are _right_ and (b) K&amp;R are right. Besides, functions are<br />
special anyway (you can't nest them in C).<br />
<br />
Note that the closing brace is empty on a line of its own, _except_ in<br />
the cases where it is followed by a continuation of the same statement,<br />
ie a &quot;while&quot; in a do-statement or an &quot;else&quot; in an if-statement, like<br />
this:<br />
<br />
do {<br />
body of do-loop<br />
} while (condition);<br />
<br />
and<br />
<br />
if (x == y) {<br />
..<br />
} else if (x &gt; y) {<br />
...<br />
} else {<br />
....<br />
}<br />
<br />
Rationale: K&amp;R.<br />
<br />
Also, note that this brace-placement also minimizes the number of empty<br />
(or almost empty) lines, without any loss of readability. Thus, as the<br />
supply of new-lines on your screen is not a renewable resource (think<br />
25-line terminal screens here), you have more empty lines to put<br />
comments on.<br />
<br />
Do not unnecessarily use braces where a single statement will do.<br />
<br />
if (condition)<br />
action();<br />
<br />
and<br />
<br />
if (condition)<br />
do_this();<br />
else<br />
do_that();<br />
<br />
This does not apply if only one branch of a conditional statement is a single<br />
statement; in the latter case use braces in both branches:<br />
<br />
if (condition) {<br />
do_this();<br />
do_that();<br />
} else {<br />
otherwise();<br />
}<br />
<br />
=== Spaces ===<br />
<br />
Linux kernel style for use of spaces depends (mostly) on<br />
function-versus-keyword usage. Use a space after (most) keywords. The<br />
notable exceptions are sizeof, typeof, alignof, and __attribute__, which look<br />
somewhat like functions (and are usually used with parentheses in Linux,<br />
although they are not required in the language, as in: &quot;sizeof info&quot; after<br />
&quot;struct fileinfo info;&quot; is declared).<br />
<br />
So use a space after these keywords:<br />
if, switch, case, for, do, while<br />
but not with sizeof, typeof, alignof, or __attribute__. E.g.,<br />
s = sizeof(struct file);<br />
<br />
Do not add spaces around (inside) parenthesized expressions. This example is<br />
*bad*:<br />
<br />
s = sizeof( struct file );<br />
<br />
When declaring pointer data or a function that returns a pointer type, the<br />
preferred use of '*' is adjacent to the data name or function name and not<br />
adjacent to the type name. Examples:<br />
<br />
char *linux_banner;<br />
unsigned long long memparse(char *ptr, char **retptr);<br />
char *match_strdup(substring_t *s);<br />
<br />
Use one space around (on each side of) most binary and ternary operators,<br />
such as any of these:<br />
<br />
= + - &lt; &gt; * / % | &amp; ^ &lt;= &gt;= == != ? :<br />
<br />
but no space after unary operators:<br />
&amp; * + - ~ ! sizeof typeof alignof __attribute__ defined<br />
<br />
no space before the postfix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
no space after the prefix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
and no space around the '.' and &quot;-&gt;&quot; structure member operators.<br />
<br />
Do not leave trailing whitespace at the ends of lines. Some editors with<br />
&quot;smart&quot; indentation will insert whitespace at the beginning of new lines as<br />
appropriate, so you can start typing the next line of code right away.<br />
However, some such editors do not remove the whitespace if you end up not<br />
putting a line of code there, such as if you leave a blank line. As a result,<br />
you end up with lines containing trailing whitespace.<br />
<br />
Git will warn you about patches that introduce trailing whitespace, and can<br />
optionally strip the trailing whitespace for you; however, if applying a series<br />
of patches, this may make later patches in the series fail by changing their<br />
context lines.<br />
<br />
== Naming ==<br />
<br />
C is a Spartan language, and so should your naming be. Unlike Modula-2<br />
and Pascal programmers, C programmers do not use cute names like<br />
ThisVariableIsATemporaryCounter. A C programmer would call that<br />
variable &quot;tmp&quot;, which is much easier to write, and not the least more<br />
difficult to understand.<br />
<br />
HOWEVER, while mixed-case names are frowned upon, descriptive names for<br />
global variables are a must. To call a global function &quot;foo&quot; is a<br />
shooting offense.<br />
<br />
GLOBAL variables (to be used only if you _really_ need them) need to<br />
have descriptive names, as do global functions. If you have a function<br />
that counts the number of active users, you should call that<br />
&quot;count_active_users()&quot; or similar, you should _not_ call it &quot;cntusr()&quot;.<br />
<br />
Encoding the type of a function into the name (so-called Hungarian<br />
notation) is brain damaged - the compiler knows the types anyway and can<br />
check those, and it only confuses the programmer. No wonder MicroSoft<br />
makes buggy programs.<br />
<br />
LOCAL variable names should be short, and to the point. If you have<br />
some random integer loop counter, it should probably be called &quot;i&quot;.<br />
Calling it &quot;loop_counter&quot; is non-productive, if there is no chance of it<br />
being mis-understood. Similarly, &quot;tmp&quot; can be just about any type of<br />
variable that is used to hold a temporary value.<br />
<br />
If you are afraid to mix up your local variable names, you have another<br />
problem, which is called the function-growth-hormone-imbalance syndrome.<br />
See chapter 6 (Functions).<br />
<br />
<br />
== Typedefs ==<br />
<br />
Please don't use things like &quot;vps_t&quot;.<br />
<br />
It's a _mistake_ to use typedef for structures and pointers. When you see a<br />
<br />
vps_t a;<br />
<br />
in the source, what does it mean?<br />
<br />
In contrast, if it says<br />
<br />
struct virtual_container *a;<br />
<br />
you can actually tell what &quot;a&quot; is.<br />
<br />
Lots of people think that typedefs &quot;help readability&quot;. Not so. They are<br />
useful only for:<br />
<br />
(a) totally opaque objects (where the typedef is actively used to _hide_ what the object is).<br />
<br />
Example: &quot;pte_t&quot; etc. opaque objects that you can only access using<br />
the proper accessor functions.<br />
<br />
NOTE! Opaqueness and &quot;accessor functions&quot; are not good in themselves.<br />
The reason we have them for things like pte_t etc. is that there<br />
really is absolutely _zero_ portably accessible information there.<br />
<br />
(b) Clear integer types, where the abstraction _helps_ avoid confusion<br />
whether it is &quot;int&quot; or &quot;long&quot;.<br />
<br />
u8/u16/u32 are perfectly fine typedefs, although they fit into<br />
category (d) better than here.<br />
<br />
NOTE! Again - there needs to be a _reason_ for this. If something is<br />
&quot;unsigned long&quot;, then there's no reason to do<br />
<br />
typedef unsigned long myflags_t;<br />
<br />
but if there is a clear reason for why it under certain circumstances<br />
might be an &quot;unsigned int&quot; and under other configurations might be<br />
&quot;unsigned long&quot;, then by all means go ahead and use a typedef.<br />
<br />
(c) when you use sparse to literally create a _new_ type for<br />
type-checking.<br />
<br />
(d) New types which are identical to standard C99 types, in certain<br />
exceptional circumstances.<br />
<br />
Although it would only take a short amount of time for the eyes and<br />
brain to become accustomed to the standard types like 'uint32_t',<br />
some people object to their use anyway.<br />
<br />
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their<br />
signed equivalents which are identical to standard types are<br />
permitted -- although they are not mandatory in new code of your<br />
own.<br />
<br />
When editing existing code which already uses one or the other set<br />
of types, you should conform to the existing choices in that code.<br />
<br />
(e) Types safe for use in userspace.<br />
<br />
In certain structures which are visible to userspace, we cannot<br />
require C99 types and cannot use the 'u32' form above. Thus, we<br />
use __u32 and similar types in all structures which are shared<br />
with userspace.<br />
<br />
Maybe there are other cases too, but the rule should basically be to NEVER<br />
EVER use a typedef unless you can clearly match one of those rules.<br />
<br />
<br />
In general, a pointer, or a struct that has elements that can reasonably<br />
be directly accessed should _never_ be a typedef.<br />
<br />
== Functions ==<br />
<br />
Functions should be short and sweet, and do just one thing. They should<br />
fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,<br />
as we all know), and do one thing and do that well.<br />
<br />
The maximum length of a function is inversely proportional to the<br />
complexity and indentation level of that function. So, if you have a<br />
conceptually simple function that is just one long (but simple)<br />
case-statement, where you have to do lots of small things for a lot of<br />
different cases, it's OK to have a longer function.<br />
<br />
However, if you have a complex function, and you suspect that a<br />
less-than-gifted first-year high-school student might not even<br />
understand what the function is all about, you should adhere to the<br />
maximum limits all the more closely. Use helper functions with<br />
descriptive names (you can ask the compiler to in-line them if you think<br />
it's performance-critical, and it will probably do a better job of it<br />
than you would have done).<br />
<br />
Another measure of the function is the number of local variables. They<br />
shouldn't exceed 5-10, or you're doing something wrong. Re-think the<br />
function, and split it into smaller pieces. A human brain can<br />
generally easily keep track of about 7 different things, anything more<br />
and it gets confused. You know you're brilliant, but maybe you'd like<br />
to understand what you did 2 weeks from now.<br />
<br />
In source files, separate functions with one blank line. If the function is<br />
exported, the EXPORT* macro for it should follow immediately after the closing<br />
function brace line. E.g.:<br />
<br />
int system_is_up(void)<br />
{<br />
return system_state == SYSTEM_RUNNING;<br />
}<br />
EXPORT_SYMBOL(system_is_up);<br />
<br />
In function prototypes, include parameter names with their data types.<br />
Although this is not required by the C language, it is preferred in Linux<br />
because it is a simple way to add valuable information for the reader.<br />
<br />
== Centralized exiting of functions ==<br />
<br />
Albeit deprecated by some people, the equivalent of the goto statement is<br />
used frequently by compilers in form of the unconditional jump instruction.<br />
<br />
The goto statement comes in handy when a function exits from multiple<br />
locations and some common work such as cleanup has to be done. If there is no<br />
cleanup needed then just return directly.<br />
<br />
The rationale is:<br />
<br />
- unconditional statements are easier to understand and follow<br />
- nesting is reduced<br />
- errors by not updating individual exit points when making<br />
modifications are prevented<br />
- saves the compiler work to optimize redundant code away ;)<br />
<br />
int fun(int a)<br />
{<br />
int result = 0;<br />
char *buffer = kmalloc(SIZE);<br />
<br />
if (buffer == NULL)<br />
return -ENOMEM;<br />
<br />
if (condition1) {<br />
while (loop1) {<br />
...<br />
}<br />
result = 1;<br />
goto out;<br />
}<br />
...<br />
out:<br />
kfree(buffer);<br />
return result;<br />
}<br />
<br />
== Commenting ==<br />
<br />
Comments are good, but there is also a danger of over-commenting. NEVER<br />
try to explain HOW your code works in a comment: it's much better to<br />
write the code so that the _working_ is obvious, and it's a waste of<br />
time to explain badly written code.<br />
<br />
Generally, you want your comments to tell WHAT your code does, not HOW.<br />
Also, try to avoid putting comments inside a function body: if the<br />
function is so complex that you need to separately comment parts of it,<br />
you should probably go back to chapter 6 for a while. You can make<br />
small comments to note or warn about something particularly clever (or<br />
ugly), but try to avoid excess. Instead, put the comments at the head<br />
of the function, telling people what it does, and possibly WHY it does<br />
it.<br />
<br />
When commenting the kernel API functions, please use the kernel-doc format.<br />
See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc<br />
for details.<br />
<br />
coreboot style for comments is the C89 &quot;/* ... */&quot; style.<br />
You may use C99-style &quot;// ...&quot; comments.<br />
<br />
The preferred style for long (multi-line) comments is:<br />
<br />
/*<br />
* This is the preferred style for multi-line<br />
* comments in the Linux kernel source code.<br />
* Please use it consistently.<br />
*<br />
* Description: A column of asterisks on the left side,<br />
* with beginning and ending almost-blank lines.<br />
*/<br />
<br />
For files in net/ and drivers/net/ the preferred style for long (multi-line)<br />
comments is a little different.<br />
<br />
/* The preferred comment style for files in net/ and drivers/net<br />
* looks like this.<br />
*<br />
* It is nearly the same as the generally preferred comment style,<br />
* but there is no initial almost-blank line.<br />
*/<br />
<br />
It's also important to comment data, whether they are basic types or derived<br />
types. To this end, use just one data declaration per line (no commas for<br />
multiple data declarations). This leaves you room for a small comment on each<br />
item, explaining its use.<br />
<br />
<br />
== You've made a mess of it ==<br />
<br />
That's OK, we all do. You've probably been told by your long-time Unix<br />
user helper that &quot;GNU emacs&quot; automatically formats the C sources for<br />
you, and you've noticed that yes, it does do that, but the defaults it<br />
uses are less than desirable (in fact, they are worse than random<br />
typing - an infinite number of monkeys typing into GNU emacs would never<br />
make a good program).<br />
<br />
So, you can either get rid of GNU emacs, or change it to use saner<br />
values. To do the latter, you can stick the following in your .emacs file:<br />
<br />
(defun c-lineup-arglist-tabs-only (ignored)<br />
&quot;Line up argument lists by tabs, not spaces&quot;<br />
(let* ((anchor (c-langelem-pos c-syntactic-element))<br />
(column (c-langelem-2nd-pos c-syntactic-element))<br />
(offset (- (1+ column) anchor))<br />
(steps (floor offset c-basic-offset)))<br />
(* (max steps 1)<br />
c-basic-offset)))<br />
<br />
(add-hook 'c-mode-common-hook<br />
(lambda ()<br />
;; Add kernel style<br />
(c-add-style<br />
&quot;linux-tabs-only&quot;<br />
'(&quot;linux&quot; (c-offsets-alist<br />
(arglist-cont-nonempty<br />
c-lineup-gcc-asm-reg<br />
c-lineup-arglist-tabs-only))))))<br />
<br />
(add-hook 'c-mode-hook<br />
(lambda ()<br />
(let ((filename (buffer-file-name)))<br />
;; Enable kernel mode for the appropriate files<br />
(when (and filename<br />
(string-match (expand-file-name &quot;~/src/linux-trees&quot;)<br />
filename))<br />
(setq indent-tabs-mode t)<br />
(c-set-style &quot;linux-tabs-only&quot;)))))<br />
<br />
This will make emacs go better with the kernel coding style for C<br />
files below ~/src/linux-trees.<br />
<br />
But even if you fail in getting emacs to do sane formatting, not<br />
everything is lost: use &quot;indent&quot;.<br />
<br />
Now, again, GNU indent has the same brain-dead settings that GNU emacs<br />
has, which is why you need to give it a few command line options.<br />
However, that's not too bad, because even the makers of GNU indent<br />
recognize the authority of K&amp;R (the GNU people aren't evil, they are<br />
just severely misguided in this matter), so you just give indent the<br />
options &quot;-kr -i8&quot; (stands for &quot;K&amp;R, 8 character indents&quot;), or use<br />
&quot;scripts/Lindent&quot;, which indents in the latest style.<br />
<br />
&quot;indent&quot; has a lot of options, and especially when it comes to comment<br />
re-formatting you may want to take a look at the man page. But<br />
remember: &quot;indent&quot; is not a fix for bad programming.<br />
<br />
<br />
== Kconfig configuration files ==<br />
<br />
For all of the Kconfig* configuration files throughout the source tree,<br />
the indentation is somewhat different. Lines under a &quot;config&quot; definition<br />
are indented with one tab, while help text is indented an additional two<br />
spaces. Example:<br />
<br />
config AUDIT<br />
bool &quot;Auditing support&quot;<br />
depends on NET<br />
help<br />
Enable auditing infrastructure that can be used with another<br />
kernel subsystem, such as SELinux (which requires this for<br />
logging of avc messages output). Does not do system-call<br />
auditing without CONFIG_AUDITSYSCALL.<br />
<br />
Seriously dangerous features (such as write support for certain<br />
filesystems) should advertise this prominently in their prompt string:<br />
<br />
config ADFS_FS_RW<br />
bool &quot;ADFS write support (DANGEROUS)&quot;<br />
depends on ADFS_FS<br />
...<br />
<br />
For full documentation on the configuration files, see the file<br />
Documentation/kbuild/kconfig-language.txt.<br />
<br />
<br />
== Data structures ==<br />
<br />
Data structures that have visibility outside the single-threaded<br />
environment they are created and destroyed in should always have<br />
reference counts. In the kernel, garbage collection doesn't exist (and<br />
outside the kernel garbage collection is slow and inefficient), which<br />
means that you absolutely _have_ to reference count all your uses.<br />
<br />
Reference counting means that you can avoid locking, and allows multiple<br />
users to have access to the data structure in parallel - and not having<br />
to worry about the structure suddenly going away from under them just<br />
because they slept or did something else for a while.<br />
<br />
Note that locking is _not_ a replacement for reference counting.<br />
Locking is used to keep data structures coherent, while reference<br />
counting is a memory management technique. Usually both are needed, and<br />
they are not to be confused with each other.<br />
<br />
Many data structures can indeed have two levels of reference counting,<br />
when there are users of different &quot;classes&quot;. The subclass count counts<br />
the number of subclass users, and decrements the global count just once<br />
when the subclass count goes to zero.<br />
<br />
Examples of this kind of &quot;multi-level-reference-counting&quot; can be found in<br />
memory management (&quot;struct mm_struct&quot;: mm_users and mm_count), and in<br />
filesystem code (&quot;struct super_block&quot;: s_count and s_active).<br />
<br />
Remember: if another thread can find your data structure, and you don't<br />
have a reference count on it, you almost certainly have a bug.<br />
<br />
<br />
== Macros, Enums and RTL ==<br />
<br />
Names of macros defining constants and labels in enums are capitalized.<br />
<br />
#define CONSTANT 0x12345<br />
<br />
Enums are preferred when defining several related constants.<br />
<br />
CAPITALIZED macro names are appreciated but macros resembling functions<br />
may be named in lower case.<br />
<br />
Generally, inline functions are preferable to macros resembling functions.<br />
<br />
Macros with multiple statements should be enclosed in a do - while block:<br />
<br />
#define macrofun(a, b, c) \<br />
do { \<br />
if (a == 5) \<br />
do_this(b, c); \<br />
} while (0)<br />
<br />
Things to avoid when using macros:<br />
<br />
1) macros that affect control flow:<br />
<br />
#define FOO(x) \<br />
do { \<br />
if (blah(x) &lt; 0) \<br />
return -EBUGGERED; \<br />
} while(0)<br />
<br />
is a _very_ bad idea. It looks like a function call but exits the &quot;calling&quot;<br />
function; don't break the internal parsers of those who will read the code.<br />
<br />
2) macros that depend on having a local variable with a magic name:<br />
<br />
#define FOO(val) bar(index, val)<br />
<br />
might look like a good thing, but it's confusing as hell when one reads the<br />
code and it's prone to breakage from seemingly innocent changes.<br />
<br />
3) macros with arguments that are used as l-values: FOO(x) = y; will<br />
bite you if somebody e.g. turns FOO into an inline function.<br />
<br />
4) forgetting about precedence: macros defining constants using expressions<br />
must enclose the expression in parentheses. Beware of similar issues with<br />
macros using parameters.<br />
<br />
#define CONSTANT 0x4000<br />
#define CONSTEXP (CONSTANT | 3)<br />
<br />
The cpp manual deals with macros exhaustively. The gcc internals manual also<br />
covers RTL which is used frequently with assembly language in the kernel.<br />
<br />
<br />
== Printing kernel messages ==<br />
<br />
Kernel developers like to be seen as literate. Do mind the spelling<br />
of kernel messages to make a good impression. Do not use crippled<br />
words like &quot;dont&quot;; use &quot;do not&quot; or &quot;don't&quot; instead. Make the messages<br />
concise, clear, and unambiguous.<br />
<br />
Kernel messages do not have to be terminated with a period.<br />
<br />
Printing numbers in parentheses (%d) adds no value and should be avoided.<br />
<br />
There are a number of driver model diagnostic macros in &lt;linux/device.h&gt;<br />
which you should use to make sure messages are matched to the right device<br />
and driver, and are tagged with the right level: dev_err(), dev_warn(),<br />
dev_info(), and so forth. For messages that aren't associated with a<br />
particular device, &lt;linux/printk.h&gt; defines pr_debug() and pr_info().<br />
<br />
Coming up with good debugging messages can be quite a challenge; and once<br />
you have them, they can be a huge help for remote troubleshooting. Such<br />
messages should be compiled out when the DEBUG symbol is not defined (that<br />
is, by default they are not included). When you use dev_dbg() or pr_debug(),<br />
that's automatic. Many subsystems have Kconfig options to turn on -DDEBUG.<br />
A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to the<br />
ones already enabled by DEBUG.<br />
<br />
<br />
== Allocating memory ==<br />
<br />
The kernel provides the following general purpose memory allocators:<br />
kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and<br />
vzalloc(). Please refer to the API documentation for further information<br />
about them.<br />
<br />
The preferred form for passing a size of a struct is the following:<br />
<br />
p = kmalloc(sizeof(*p), ...);<br />
<br />
The alternative form where struct name is spelled out hurts readability and<br />
introduces an opportunity for a bug when the pointer variable type is changed<br />
but the corresponding sizeof that is passed to a memory allocator is not.<br />
<br />
Casting the return value which is a void pointer is redundant. The conversion<br />
from void pointer to any other pointer type is guaranteed by the C programming<br />
language.<br />
<br />
The preferred form for allocating an array is the following:<br />
<br />
p = kmalloc_array(n, sizeof(...), ...);<br />
<br />
The preferred form for allocating a zeroed array is the following:<br />
<br />
p = kcalloc(n, sizeof(...), ...);<br />
<br />
Both forms check for overflow on the allocation size n * sizeof(...),<br />
and return NULL if that occurred.<br />
<br />
<br />
== The inline disease ==<br />
<br />
There appears to be a common misperception that gcc has a magic &quot;make me<br />
faster&quot; speedup option called &quot;inline&quot;. While the use of inlines can be<br />
appropriate (for example as a means of replacing macros, see Chapter 12), it<br />
very often is not. Abundant use of the inline keyword leads to a much bigger<br />
kernel, which in turn slows the system as a whole down, due to a bigger<br />
icache footprint for the CPU and simply because there is less memory<br />
available for the pagecache. Just think about it; a pagecache miss causes a<br />
disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles<br />
that can go into these 5 milliseconds.<br />
<br />
A reasonable rule of thumb is to not put inline at functions that have more<br />
than 3 lines of code in them. An exception to this rule are the cases where<br />
a parameter is known to be a compiletime constant, and as a result of this<br />
constantness you *know* the compiler will be able to optimize most of your<br />
function away at compile time. For a good example of this later case, see<br />
the kmalloc() inline function.<br />
<br />
Often people argue that adding inline to functions that are static and used<br />
only once is always a win since there is no space tradeoff. While this is<br />
technically correct, gcc is capable of inlining these automatically without<br />
help, and the maintenance issue of removing the inline when a second user<br />
appears outweighs the potential value of the hint that tells gcc to do<br />
something it would have done anyway.<br />
<br />
<br />
== Function return values and names ==<br />
<br />
Functions can return values of many different kinds, and one of the<br />
most common is a value indicating whether the function succeeded or<br />
failed. Such a value can be represented as an error-code integer<br />
(-Exxx = failure, 0 = success) or a &quot;succeeded&quot; boolean (0 = failure,<br />
non-zero = success).<br />
<br />
Mixing up these two sorts of representations is a fertile source of<br />
difficult-to-find bugs. If the C language included a strong distinction<br />
between integers and booleans then the compiler would find these mistakes<br />
for us... but it doesn't. To help prevent such bugs, always follow this<br />
convention:<br />
<br />
If the name of a function is an action or an imperative command,<br />
the function should return an error-code integer. If the name<br />
is a predicate, the function should return a &quot;succeeded&quot; boolean.<br />
<br />
For example, &quot;add work&quot; is a command, and the add_work() function returns 0<br />
for success or -EBUSY for failure. In the same way, &quot;PCI device present&quot; is<br />
a predicate, and the pci_dev_present() function returns 1 if it succeeds in<br />
finding a matching device or 0 if it doesn't.<br />
<br />
All EXPORTed functions must respect this convention, and so should all<br />
public functions. Private (static) functions need not, but it is<br />
recommended that they do.<br />
<br />
Functions whose return value is the actual result of a computation, rather<br />
than an indication of whether the computation succeeded, are not subject to<br />
this rule. Generally they indicate failure by returning some out-of-range<br />
result. Typical examples would be functions that return pointers; they use<br />
NULL or the ERR_PTR mechanism to report failure.<br />
<br />
<br />
== Don't re-invent the kernel macros ==<br />
<br />
The header file include/linux/kernel.h contains a number of macros that<br />
you should use, rather than explicitly coding some variant of them yourself.<br />
For example, if you need to calculate the length of an array, take advantage<br />
of the macro<br />
<br />
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))<br />
<br />
Similarly, if you need to calculate the size of some structure member, use<br />
<br />
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)-&gt;f))<br />
<br />
There are also min() and max() macros that do strict type checking if you<br />
need them. Feel free to peruse that header file to see what else is already<br />
defined that you shouldn't reproduce in your code.<br />
<br />
<br />
== Editor modelines and other cruft ==<br />
<br />
Some editors can interpret configuration information embedded in source files,<br />
indicated with special markers. For example, emacs interprets lines marked<br />
like this:<br />
<br />
-*- mode: c -*-<br />
<br />
Or like this:<br />
<br />
/*<br />
Local Variables:<br />
compile-command: &quot;gcc -DMAGIC_DEBUG_FLAG foo.c&quot;<br />
End:<br />
*/<br />
<br />
Vim interprets markers that look like this:<br />
<br />
/* vim:set sw=8 noet */<br />
<br />
Do not include any of these in source files. People have their own personal<br />
editor configurations, and your source files should not override them. This<br />
includes markers for indentation and mode configuration. People may use their<br />
own custom mode, or may have some other magic method for making indentation<br />
work correctly.<br />
<br />
<br />
== Inline assembly ==<br />
<br />
In architecture-specific code, you may need to use inline assembly to interface<br />
with CPU or platform functionality. Don't hesitate to do so when necessary.<br />
However, don't use inline assembly gratuitously when C can do the job. You can<br />
and should poke hardware from C when possible.<br />
<br />
Consider writing simple helper functions that wrap common bits of inline<br />
assembly, rather than repeatedly writing them with slight variations. Remember<br />
that inline assembly can use C parameters.<br />
<br />
Large, non-trivial assembly functions should go in .S files, with corresponding<br />
C prototypes defined in C header files. The C prototypes for assembly<br />
functions should use &quot;asmlinkage&quot;.<br />
<br />
You may need to mark your asm statement as volatile, to prevent GCC from<br />
removing it if GCC doesn't notice any side effects. You don't always need to<br />
do so, though, and doing so unnecessarily can limit optimization.<br />
<br />
When writing a single inline assembly statement containing multiple<br />
instructions, put each instruction on a separate line in a separate quoted<br />
string, and end each string except the last with \n\t to properly indent the<br />
next instruction in the assembly output:<br />
<br />
asm (&quot;magic %reg1, #42\n\t&quot;<br />
&quot;more_magic %reg2, %reg3&quot;<br />
: /* outputs */ : /* inputs */ : /* clobbers */);<br />
<br />
<br />
<br />
== References ==<br />
<br />
The C Programming Language, Second Edition<br />
by Brian W. Kernighan and Dennis M. Ritchie.<br />
Prentice Hall, Inc., 1988.<br />
ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).<br />
URL: http://cm.bell-labs.com/cm/cs/cbook/<br />
<br />
The Practice of Programming<br />
by Brian W. Kernighan and Rob Pike.<br />
Addison-Wesley, Inc., 1999.<br />
ISBN 0-201-61586-X.<br />
URL: http://cm.bell-labs.com/cm/cs/tpop/<br />
<br />
GNU manuals - where in compliance with K&amp;R and this text - for cpp, gcc,<br />
gcc internals and indent, all available from http://www.gnu.org/manual/<br />
<br />
WG14 is the international standardization working group for the programming<br />
language C, URL: http://www.open-std.org/JTC1/SC22/WG14/<br />
<br />
Kernel CodingStyle, by greg@kroah.com at OLS 2002:<br />
http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/</div>Stepanhttp://www.coreboot.org/index.php?title=Coding_Style&diff=12308Coding Style2013-12-05T18:48:24Z<p>Stepan: /* Functions */</p>
<hr />
<div>This is a short document describing the preferred coding style for the<br />
coreboot project. It is in many ways exactly the same as the Linux kernel<br />
coding style. In fact, most of this document has been copied from the<br />
[http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/Documentation/CodingStyle?id=HEAD Linux kernel coding style]<br />
<br />
Please at least consider the points made here.<br />
<br />
First off, I'd suggest printing out a copy of the GNU coding standards,<br />
and NOT read it. Burn them, it's a great symbolic gesture.<br />
<br />
Anyway, here goes:<br />
<br />
<br />
== Indentation ==<br />
<br />
Tabs are 8 characters, and thus indentations are also 8 characters.<br />
There are heretic movements that try to make indentations 4 (or even 2!)<br />
characters deep, and that is akin to trying to define the value of PI to<br />
be 3.<br />
<br />
Rationale: The whole idea behind indentation is to clearly define where<br />
a block of control starts and ends. Especially when you've been looking<br />
at your screen for 20 straight hours, you'll find it a lot easier to see<br />
how the indentation works if you have large indentations.<br />
<br />
Now, some people will claim that having 8-character indentations makes<br />
the code move too far to the right, and makes it hard to read on a<br />
80-character terminal screen. The answer to that is that if you need<br />
more than 3 levels of indentation, you're screwed anyway, and should fix<br />
your program.<br />
<br />
In short, 8-char indents make things easier to read, and have the added<br />
benefit of warning you when you're nesting your functions too deep.<br />
Heed that warning.<br />
<br />
The preferred way to ease multiple indentation levels in a switch statement is<br />
to align the &quot;switch&quot; and its subordinate &quot;case&quot; labels in the same column<br />
instead of &quot;double-indenting&quot; the &quot;case&quot; labels. E.g.:<br />
<br />
switch (suffix) {<br />
case 'G':<br />
case 'g':<br />
mem &lt;&lt;= 30;<br />
break;<br />
case 'M':<br />
case 'm':<br />
mem &lt;&lt;= 20;<br />
break;<br />
case 'K':<br />
case 'k':<br />
mem &lt;&lt;= 10;<br />
/* fall through */<br />
default:<br />
break;<br />
}<br />
<br />
<br />
Don't put multiple statements on a single line unless you have<br />
something to hide:<br />
<br />
if (condition) do_this;<br />
do_something_everytime;<br />
<br />
Don't put multiple assignments on a single line either. Kernel coding style<br />
is super simple. Avoid tricky expressions.<br />
<br />
Outside of comments, documentation and except in Kconfig, spaces are never<br />
used for indentation, and the above example is deliberately broken.<br />
<br />
Get a decent editor and don't leave whitespace at the end of lines.<br />
<br />
== Breaking long lines and strings ==<br />
<br />
Coding style is all about readability and maintainability using commonly<br />
available tools.<br />
<br />
The limit on the length of lines is 80 columns and this is a strongly<br />
preferred limit.<br />
<br />
Statements longer than 80 columns will be broken into sensible chunks, unless<br />
exceeding 80 columns significantly increases readability and does not hide<br />
information. Descendants are always substantially shorter than the parent and<br />
are placed substantially to the right. The same applies to function headers<br />
with a long argument list. However, never break user-visible strings such as<br />
printk messages, because that breaks the ability to grep for them.<br />
<br />
<br />
== Placing Braces and Spaces ==<br />
<br />
The other issue that always comes up in C styling is the placement of<br />
braces. Unlike the indent size, there are few technical reasons to<br />
choose one placement strategy over the other, but the preferred way, as<br />
shown to us by the prophets Kernighan and Ritchie, is to put the opening<br />
brace last on the line, and put the closing brace first, thusly:<br />
<br />
if (x is true) {<br />
we do y<br />
}<br />
<br />
This applies to all non-function statement blocks (if, switch, for,<br />
while, do). E.g.:<br />
<br />
switch (action) {<br />
case KOBJ_ADD:<br />
return &quot;add&quot;;<br />
case KOBJ_REMOVE:<br />
return &quot;remove&quot;;<br />
case KOBJ_CHANGE:<br />
return &quot;change&quot;;<br />
default:<br />
return NULL;<br />
}<br />
<br />
However, there is one special case, namely functions: they have the<br />
opening brace at the beginning of the next line, thus:<br />
<br />
int function(int x)<br />
{<br />
body of function<br />
}<br />
<br />
Heretic people all over the world have claimed that this inconsistency<br />
is ... well ... inconsistent, but all right-thinking people know that<br />
(a) K&amp;R are _right_ and (b) K&amp;R are right. Besides, functions are<br />
special anyway (you can't nest them in C).<br />
<br />
Note that the closing brace is empty on a line of its own, _except_ in<br />
the cases where it is followed by a continuation of the same statement,<br />
ie a &quot;while&quot; in a do-statement or an &quot;else&quot; in an if-statement, like<br />
this:<br />
<br />
do {<br />
body of do-loop<br />
} while (condition);<br />
<br />
and<br />
<br />
if (x == y) {<br />
..<br />
} else if (x &gt; y) {<br />
...<br />
} else {<br />
....<br />
}<br />
<br />
Rationale: K&amp;R.<br />
<br />
Also, note that this brace-placement also minimizes the number of empty<br />
(or almost empty) lines, without any loss of readability. Thus, as the<br />
supply of new-lines on your screen is not a renewable resource (think<br />
25-line terminal screens here), you have more empty lines to put<br />
comments on.<br />
<br />
Do not unnecessarily use braces where a single statement will do.<br />
<br />
if (condition)<br />
action();<br />
<br />
and<br />
<br />
if (condition)<br />
do_this();<br />
else<br />
do_that();<br />
<br />
This does not apply if only one branch of a conditional statement is a single<br />
statement; in the latter case use braces in both branches:<br />
<br />
if (condition) {<br />
do_this();<br />
do_that();<br />
} else {<br />
otherwise();<br />
}<br />
<br />
=== Spaces ===<br />
<br />
Linux kernel style for use of spaces depends (mostly) on<br />
function-versus-keyword usage. Use a space after (most) keywords. The<br />
notable exceptions are sizeof, typeof, alignof, and __attribute__, which look<br />
somewhat like functions (and are usually used with parentheses in Linux,<br />
although they are not required in the language, as in: &quot;sizeof info&quot; after<br />
&quot;struct fileinfo info;&quot; is declared).<br />
<br />
So use a space after these keywords:<br />
if, switch, case, for, do, while<br />
but not with sizeof, typeof, alignof, or __attribute__. E.g.,<br />
s = sizeof(struct file);<br />
<br />
Do not add spaces around (inside) parenthesized expressions. This example is<br />
*bad*:<br />
<br />
s = sizeof( struct file );<br />
<br />
When declaring pointer data or a function that returns a pointer type, the<br />
preferred use of '*' is adjacent to the data name or function name and not<br />
adjacent to the type name. Examples:<br />
<br />
char *linux_banner;<br />
unsigned long long memparse(char *ptr, char **retptr);<br />
char *match_strdup(substring_t *s);<br />
<br />
Use one space around (on each side of) most binary and ternary operators,<br />
such as any of these:<br />
<br />
= + - &lt; &gt; * / % | &amp; ^ &lt;= &gt;= == != ? :<br />
<br />
but no space after unary operators:<br />
&amp; * + - ~ ! sizeof typeof alignof __attribute__ defined<br />
<br />
no space before the postfix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
no space after the prefix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
and no space around the '.' and &quot;-&gt;&quot; structure member operators.<br />
<br />
Do not leave trailing whitespace at the ends of lines. Some editors with<br />
&quot;smart&quot; indentation will insert whitespace at the beginning of new lines as<br />
appropriate, so you can start typing the next line of code right away.<br />
However, some such editors do not remove the whitespace if you end up not<br />
putting a line of code there, such as if you leave a blank line. As a result,<br />
you end up with lines containing trailing whitespace.<br />
<br />
Git will warn you about patches that introduce trailing whitespace, and can<br />
optionally strip the trailing whitespace for you; however, if applying a series<br />
of patches, this may make later patches in the series fail by changing their<br />
context lines.<br />
<br />
== Naming ==<br />
<br />
C is a Spartan language, and so should your naming be. Unlike Modula-2<br />
and Pascal programmers, C programmers do not use cute names like<br />
ThisVariableIsATemporaryCounter. A C programmer would call that<br />
variable &quot;tmp&quot;, which is much easier to write, and not the least more<br />
difficult to understand.<br />
<br />
HOWEVER, while mixed-case names are frowned upon, descriptive names for<br />
global variables are a must. To call a global function &quot;foo&quot; is a<br />
shooting offense.<br />
<br />
GLOBAL variables (to be used only if you _really_ need them) need to<br />
have descriptive names, as do global functions. If you have a function<br />
that counts the number of active users, you should call that<br />
&quot;count_active_users()&quot; or similar, you should _not_ call it &quot;cntusr()&quot;.<br />
<br />
Encoding the type of a function into the name (so-called Hungarian<br />
notation) is brain damaged - the compiler knows the types anyway and can<br />
check those, and it only confuses the programmer. No wonder MicroSoft<br />
makes buggy programs.<br />
<br />
LOCAL variable names should be short, and to the point. If you have<br />
some random integer loop counter, it should probably be called &quot;i&quot;.<br />
Calling it &quot;loop_counter&quot; is non-productive, if there is no chance of it<br />
being mis-understood. Similarly, &quot;tmp&quot; can be just about any type of<br />
variable that is used to hold a temporary value.<br />
<br />
If you are afraid to mix up your local variable names, you have another<br />
problem, which is called the function-growth-hormone-imbalance syndrome.<br />
See chapter 6 (Functions).<br />
<br />
<br />
== Typedefs ==<br />
<br />
Please don't use things like &quot;vps_t&quot;.<br />
<br />
It's a _mistake_ to use typedef for structures and pointers. When you see a<br />
<br />
vps_t a;<br />
<br />
in the source, what does it mean?<br />
<br />
In contrast, if it says<br />
<br />
struct virtual_container *a;<br />
<br />
you can actually tell what &quot;a&quot; is.<br />
<br />
Lots of people think that typedefs &quot;help readability&quot;. Not so. They are<br />
useful only for:<br />
<br />
(a) totally opaque objects (where the typedef is actively used to _hide_ what the object is).<br />
<br />
Example: &quot;pte_t&quot; etc. opaque objects that you can only access using<br />
the proper accessor functions.<br />
<br />
NOTE! Opaqueness and &quot;accessor functions&quot; are not good in themselves.<br />
The reason we have them for things like pte_t etc. is that there<br />
really is absolutely _zero_ portably accessible information there.<br />
<br />
(b) Clear integer types, where the abstraction _helps_ avoid confusion<br />
whether it is &quot;int&quot; or &quot;long&quot;.<br />
<br />
u8/u16/u32 are perfectly fine typedefs, although they fit into<br />
category (d) better than here.<br />
<br />
NOTE! Again - there needs to be a _reason_ for this. If something is<br />
&quot;unsigned long&quot;, then there's no reason to do<br />
<br />
typedef unsigned long myflags_t;<br />
<br />
but if there is a clear reason for why it under certain circumstances<br />
might be an &quot;unsigned int&quot; and under other configurations might be<br />
&quot;unsigned long&quot;, then by all means go ahead and use a typedef.<br />
<br />
(c) when you use sparse to literally create a _new_ type for<br />
type-checking.<br />
<br />
(d) New types which are identical to standard C99 types, in certain<br />
exceptional circumstances.<br />
<br />
Although it would only take a short amount of time for the eyes and<br />
brain to become accustomed to the standard types like 'uint32_t',<br />
some people object to their use anyway.<br />
<br />
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their<br />
signed equivalents which are identical to standard types are<br />
permitted -- although they are not mandatory in new code of your<br />
own.<br />
<br />
When editing existing code which already uses one or the other set<br />
of types, you should conform to the existing choices in that code.<br />
<br />
(e) Types safe for use in userspace.<br />
<br />
In certain structures which are visible to userspace, we cannot<br />
require C99 types and cannot use the 'u32' form above. Thus, we<br />
use __u32 and similar types in all structures which are shared<br />
with userspace.<br />
<br />
Maybe there are other cases too, but the rule should basically be to NEVER<br />
EVER use a typedef unless you can clearly match one of those rules.<br />
<br />
<br />
In general, a pointer, or a struct that has elements that can reasonably<br />
be directly accessed should _never_ be a typedef.<br />
<br />
== Functions ==<br />
<br />
Functions should be short and sweet, and do just one thing. They should<br />
fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,<br />
as we all know), and do one thing and do that well.<br />
<br />
The maximum length of a function is inversely proportional to the<br />
complexity and indentation level of that function. So, if you have a<br />
conceptually simple function that is just one long (but simple)<br />
case-statement, where you have to do lots of small things for a lot of<br />
different cases, it's OK to have a longer function.<br />
<br />
However, if you have a complex function, and you suspect that a<br />
less-than-gifted first-year high-school student might not even<br />
understand what the function is all about, you should adhere to the<br />
maximum limits all the more closely. Use helper functions with<br />
descriptive names (you can ask the compiler to in-line them if you think<br />
it's performance-critical, and it will probably do a better job of it<br />
than you would have done).<br />
<br />
Another measure of the function is the number of local variables. They<br />
shouldn't exceed 5-10, or you're doing something wrong. Re-think the<br />
function, and split it into smaller pieces. A human brain can<br />
generally easily keep track of about 7 different things, anything more<br />
and it gets confused. You know you're brilliant, but maybe you'd like<br />
to understand what you did 2 weeks from now.<br />
<br />
In source files, separate functions with one blank line. If the function is<br />
exported, the EXPORT* macro for it should follow immediately after the closing<br />
function brace line. E.g.:<br />
<br />
int system_is_up(void)<br />
{<br />
return system_state == SYSTEM_RUNNING;<br />
}<br />
EXPORT_SYMBOL(system_is_up);<br />
<br />
In function prototypes, include parameter names with their data types.<br />
Although this is not required by the C language, it is preferred in Linux<br />
because it is a simple way to add valuable information for the reader.<br />
<br />
== Centralized exiting of functions ==<br />
<br />
Albeit deprecated by some people, the equivalent of the goto statement is<br />
used frequently by compilers in form of the unconditional jump instruction.<br />
<br />
The goto statement comes in handy when a function exits from multiple<br />
locations and some common work such as cleanup has to be done. If there is no<br />
cleanup needed then just return directly.<br />
<br />
The rationale is:<br />
<br />
- unconditional statements are easier to understand and follow<br />
- nesting is reduced<br />
- errors by not updating individual exit points when making<br />
modifications are prevented<br />
- saves the compiler work to optimize redundant code away ;)<br />
<br />
int fun(int a)<br />
{<br />
int result = 0;<br />
char *buffer = kmalloc(SIZE);<br />
<br />
if (buffer == NULL)<br />
return -ENOMEM;<br />
<br />
if (condition1) {<br />
while (loop1) {<br />
...<br />
}<br />
result = 1;<br />
goto out;<br />
}<br />
...<br />
out:<br />
kfree(buffer);<br />
return result;<br />
}<br />
<br />
== Commenting ==<br />
<br />
Comments are good, but there is also a danger of over-commenting. NEVER<br />
try to explain HOW your code works in a comment: it's much better to<br />
write the code so that the _working_ is obvious, and it's a waste of<br />
time to explain badly written code.<br />
<br />
Generally, you want your comments to tell WHAT your code does, not HOW.<br />
Also, try to avoid putting comments inside a function body: if the<br />
function is so complex that you need to separately comment parts of it,<br />
you should probably go back to chapter 6 for a while. You can make<br />
small comments to note or warn about something particularly clever (or<br />
ugly), but try to avoid excess. Instead, put the comments at the head<br />
of the function, telling people what it does, and possibly WHY it does<br />
it.<br />
<br />
When commenting the kernel API functions, please use the kernel-doc format.<br />
See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc<br />
for details.<br />
<br />
coreboot style for comments is the C89 &quot;/* ... */&quot; style.<br />
You may use C99-style &quot;// ...&quot; comments.<br />
<br />
The preferred style for long (multi-line) comments is:<br />
<br />
/*<br />
* This is the preferred style for multi-line<br />
* comments in the Linux kernel source code.<br />
* Please use it consistently.<br />
*<br />
* Description: A column of asterisks on the left side,<br />
* with beginning and ending almost-blank lines.<br />
*/<br />
<br />
For files in net/ and drivers/net/ the preferred style for long (multi-line)<br />
comments is a little different.<br />
<br />
/* The preferred comment style for files in net/ and drivers/net<br />
* looks like this.<br />
*<br />
* It is nearly the same as the generally preferred comment style,<br />
* but there is no initial almost-blank line.<br />
*/<br />
<br />
It's also important to comment data, whether they are basic types or derived<br />
types. To this end, use just one data declaration per line (no commas for<br />
multiple data declarations). This leaves you room for a small comment on each<br />
item, explaining its use.<br />
<br />
<br />
== You've made a mess of it ==<br />
<br />
That's OK, we all do. You've probably been told by your long-time Unix<br />
user helper that &quot;GNU emacs&quot; automatically formats the C sources for<br />
you, and you've noticed that yes, it does do that, but the defaults it<br />
uses are less than desirable (in fact, they are worse than random<br />
typing - an infinite number of monkeys typing into GNU emacs would never<br />
make a good program).<br />
<br />
So, you can either get rid of GNU emacs, or change it to use saner<br />
values. To do the latter, you can stick the following in your .emacs file:<br />
<br />
(defun c-lineup-arglist-tabs-only (ignored)<br />
&quot;Line up argument lists by tabs, not spaces&quot;<br />
(let* ((anchor (c-langelem-pos c-syntactic-element))<br />
(column (c-langelem-2nd-pos c-syntactic-element))<br />
(offset (- (1+ column) anchor))<br />
(steps (floor offset c-basic-offset)))<br />
(* (max steps 1)<br />
c-basic-offset)))<br />
<br />
(add-hook 'c-mode-common-hook<br />
(lambda ()<br />
;; Add kernel style<br />
(c-add-style<br />
&quot;linux-tabs-only&quot;<br />
'(&quot;linux&quot; (c-offsets-alist<br />
(arglist-cont-nonempty<br />
c-lineup-gcc-asm-reg<br />
c-lineup-arglist-tabs-only))))))<br />
<br />
(add-hook 'c-mode-hook<br />
(lambda ()<br />
(let ((filename (buffer-file-name)))<br />
;; Enable kernel mode for the appropriate files<br />
(when (and filename<br />
(string-match (expand-file-name &quot;~/src/linux-trees&quot;)<br />
filename))<br />
(setq indent-tabs-mode t)<br />
(c-set-style &quot;linux-tabs-only&quot;)))))<br />
<br />
This will make emacs go better with the kernel coding style for C<br />
files below ~/src/linux-trees.<br />
<br />
But even if you fail in getting emacs to do sane formatting, not<br />
everything is lost: use &quot;indent&quot;.<br />
<br />
Now, again, GNU indent has the same brain-dead settings that GNU emacs<br />
has, which is why you need to give it a few command line options.<br />
However, that's not too bad, because even the makers of GNU indent<br />
recognize the authority of K&amp;R (the GNU people aren't evil, they are<br />
just severely misguided in this matter), so you just give indent the<br />
options &quot;-kr -i8&quot; (stands for &quot;K&amp;R, 8 character indents&quot;), or use<br />
&quot;scripts/Lindent&quot;, which indents in the latest style.<br />
<br />
&quot;indent&quot; has a lot of options, and especially when it comes to comment<br />
re-formatting you may want to take a look at the man page. But<br />
remember: &quot;indent&quot; is not a fix for bad programming.<br />
<br />
<br />
== Kconfig configuration files ==<br />
<br />
For all of the Kconfig* configuration files throughout the source tree,<br />
the indentation is somewhat different. Lines under a &quot;config&quot; definition<br />
are indented with one tab, while help text is indented an additional two<br />
spaces. Example:<br />
<br />
config AUDIT<br />
bool &quot;Auditing support&quot;<br />
depends on NET<br />
help<br />
Enable auditing infrastructure that can be used with another<br />
kernel subsystem, such as SELinux (which requires this for<br />
logging of avc messages output). Does not do system-call<br />
auditing without CONFIG_AUDITSYSCALL.<br />
<br />
Seriously dangerous features (such as write support for certain<br />
filesystems) should advertise this prominently in their prompt string:<br />
<br />
config ADFS_FS_RW<br />
bool &quot;ADFS write support (DANGEROUS)&quot;<br />
depends on ADFS_FS<br />
...<br />
<br />
For full documentation on the configuration files, see the file<br />
Documentation/kbuild/kconfig-language.txt.<br />
<br />
<br />
== Data structures ==<br />
<br />
Data structures that have visibility outside the single-threaded<br />
environment they are created and destroyed in should always have<br />
reference counts. In the kernel, garbage collection doesn't exist (and<br />
outside the kernel garbage collection is slow and inefficient), which<br />
means that you absolutely _have_ to reference count all your uses.<br />
<br />
Reference counting means that you can avoid locking, and allows multiple<br />
users to have access to the data structure in parallel - and not having<br />
to worry about the structure suddenly going away from under them just<br />
because they slept or did something else for a while.<br />
<br />
Note that locking is _not_ a replacement for reference counting.<br />
Locking is used to keep data structures coherent, while reference<br />
counting is a memory management technique. Usually both are needed, and<br />
they are not to be confused with each other.<br />
<br />
Many data structures can indeed have two levels of reference counting,<br />
when there are users of different &quot;classes&quot;. The subclass count counts<br />
the number of subclass users, and decrements the global count just once<br />
when the subclass count goes to zero.<br />
<br />
Examples of this kind of &quot;multi-level-reference-counting&quot; can be found in<br />
memory management (&quot;struct mm_struct&quot;: mm_users and mm_count), and in<br />
filesystem code (&quot;struct super_block&quot;: s_count and s_active).<br />
<br />
Remember: if another thread can find your data structure, and you don't<br />
have a reference count on it, you almost certainly have a bug.<br />
<br />
<br />
== Macros, Enums and RTL ==<br />
<br />
Names of macros defining constants and labels in enums are capitalized.<br />
<br />
#define CONSTANT 0x12345<br />
<br />
Enums are preferred when defining several related constants.<br />
<br />
CAPITALIZED macro names are appreciated but macros resembling functions<br />
may be named in lower case.<br />
<br />
Generally, inline functions are preferable to macros resembling functions.<br />
<br />
Macros with multiple statements should be enclosed in a do - while block:<br />
<br />
#define macrofun(a, b, c) \<br />
do { \<br />
if (a == 5) \<br />
do_this(b, c); \<br />
} while (0)<br />
<br />
Things to avoid when using macros:<br />
<br />
1) macros that affect control flow:<br />
<br />
#define FOO(x) \<br />
do { \<br />
if (blah(x) &lt; 0) \<br />
return -EBUGGERED; \<br />
} while(0)<br />
<br />
is a _very_ bad idea. It looks like a function call but exits the &quot;calling&quot;<br />
function; don't break the internal parsers of those who will read the code.<br />
<br />
2) macros that depend on having a local variable with a magic name:<br />
<br />
#define FOO(val) bar(index, val)<br />
<br />
might look like a good thing, but it's confusing as hell when one reads the<br />
code and it's prone to breakage from seemingly innocent changes.<br />
<br />
3) macros with arguments that are used as l-values: FOO(x) = y; will<br />
bite you if somebody e.g. turns FOO into an inline function.<br />
<br />
4) forgetting about precedence: macros defining constants using expressions<br />
must enclose the expression in parentheses. Beware of similar issues with<br />
macros using parameters.<br />
<br />
#define CONSTANT 0x4000<br />
#define CONSTEXP (CONSTANT | 3)<br />
<br />
The cpp manual deals with macros exhaustively. The gcc internals manual also<br />
covers RTL which is used frequently with assembly language in the kernel.<br />
<br />
<br />
== Printing kernel messages ==<br />
<br />
Kernel developers like to be seen as literate. Do mind the spelling<br />
of kernel messages to make a good impression. Do not use crippled<br />
words like &quot;dont&quot;; use &quot;do not&quot; or &quot;don't&quot; instead. Make the messages<br />
concise, clear, and unambiguous.<br />
<br />
Kernel messages do not have to be terminated with a period.<br />
<br />
Printing numbers in parentheses (%d) adds no value and should be avoided.<br />
<br />
There are a number of driver model diagnostic macros in &lt;linux/device.h&gt;<br />
which you should use to make sure messages are matched to the right device<br />
and driver, and are tagged with the right level: dev_err(), dev_warn(),<br />
dev_info(), and so forth. For messages that aren't associated with a<br />
particular device, &lt;linux/printk.h&gt; defines pr_debug() and pr_info().<br />
<br />
Coming up with good debugging messages can be quite a challenge; and once<br />
you have them, they can be a huge help for remote troubleshooting. Such<br />
messages should be compiled out when the DEBUG symbol is not defined (that<br />
is, by default they are not included). When you use dev_dbg() or pr_debug(),<br />
that's automatic. Many subsystems have Kconfig options to turn on -DDEBUG.<br />
A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to the<br />
ones already enabled by DEBUG.<br />
<br />
<br />
== Allocating memory ==<br />
<br />
The kernel provides the following general purpose memory allocators:<br />
kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and<br />
vzalloc(). Please refer to the API documentation for further information<br />
about them.<br />
<br />
The preferred form for passing a size of a struct is the following:<br />
<br />
p = kmalloc(sizeof(*p), ...);<br />
<br />
The alternative form where struct name is spelled out hurts readability and<br />
introduces an opportunity for a bug when the pointer variable type is changed<br />
but the corresponding sizeof that is passed to a memory allocator is not.<br />
<br />
Casting the return value which is a void pointer is redundant. The conversion<br />
from void pointer to any other pointer type is guaranteed by the C programming<br />
language.<br />
<br />
The preferred form for allocating an array is the following:<br />
<br />
p = kmalloc_array(n, sizeof(...), ...);<br />
<br />
The preferred form for allocating a zeroed array is the following:<br />
<br />
p = kcalloc(n, sizeof(...), ...);<br />
<br />
Both forms check for overflow on the allocation size n * sizeof(...),<br />
and return NULL if that occurred.<br />
<br />
<br />
== The inline disease ==<br />
<br />
There appears to be a common misperception that gcc has a magic &quot;make me<br />
faster&quot; speedup option called &quot;inline&quot;. While the use of inlines can be<br />
appropriate (for example as a means of replacing macros, see Chapter 12), it<br />
very often is not. Abundant use of the inline keyword leads to a much bigger<br />
kernel, which in turn slows the system as a whole down, due to a bigger<br />
icache footprint for the CPU and simply because there is less memory<br />
available for the pagecache. Just think about it; a pagecache miss causes a<br />
disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles<br />
that can go into these 5 milliseconds.<br />
<br />
A reasonable rule of thumb is to not put inline at functions that have more<br />
than 3 lines of code in them. An exception to this rule are the cases where<br />
a parameter is known to be a compiletime constant, and as a result of this<br />
constantness you *know* the compiler will be able to optimize most of your<br />
function away at compile time. For a good example of this later case, see<br />
the kmalloc() inline function.<br />
<br />
Often people argue that adding inline to functions that are static and used<br />
only once is always a win since there is no space tradeoff. While this is<br />
technically correct, gcc is capable of inlining these automatically without<br />
help, and the maintenance issue of removing the inline when a second user<br />
appears outweighs the potential value of the hint that tells gcc to do<br />
something it would have done anyway.<br />
<br />
<br />
== Function return values and names ==<br />
<br />
Functions can return values of many different kinds, and one of the<br />
most common is a value indicating whether the function succeeded or<br />
failed. Such a value can be represented as an error-code integer<br />
(-Exxx = failure, 0 = success) or a &quot;succeeded&quot; boolean (0 = failure,<br />
non-zero = success).<br />
<br />
Mixing up these two sorts of representations is a fertile source of<br />
difficult-to-find bugs. If the C language included a strong distinction<br />
between integers and booleans then the compiler would find these mistakes<br />
for us... but it doesn't. To help prevent such bugs, always follow this<br />
convention:<br />
<br />
If the name of a function is an action or an imperative command,<br />
the function should return an error-code integer. If the name<br />
is a predicate, the function should return a &quot;succeeded&quot; boolean.<br />
<br />
For example, &quot;add work&quot; is a command, and the add_work() function returns 0<br />
for success or -EBUSY for failure. In the same way, &quot;PCI device present&quot; is<br />
a predicate, and the pci_dev_present() function returns 1 if it succeeds in<br />
finding a matching device or 0 if it doesn't.<br />
<br />
All EXPORTed functions must respect this convention, and so should all<br />
public functions. Private (static) functions need not, but it is<br />
recommended that they do.<br />
<br />
Functions whose return value is the actual result of a computation, rather<br />
than an indication of whether the computation succeeded, are not subject to<br />
this rule. Generally they indicate failure by returning some out-of-range<br />
result. Typical examples would be functions that return pointers; they use<br />
NULL or the ERR_PTR mechanism to report failure.<br />
<br />
<br />
== Don't re-invent the kernel macros ==<br />
<br />
The header file include/linux/kernel.h contains a number of macros that<br />
you should use, rather than explicitly coding some variant of them yourself.<br />
For example, if you need to calculate the length of an array, take advantage<br />
of the macro<br />
<br />
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))<br />
<br />
Similarly, if you need to calculate the size of some structure member, use<br />
<br />
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)-&gt;f))<br />
<br />
There are also min() and max() macros that do strict type checking if you<br />
need them. Feel free to peruse that header file to see what else is already<br />
defined that you shouldn't reproduce in your code.<br />
<br />
<br />
== Editor modelines and other cruft ==<br />
<br />
Some editors can interpret configuration information embedded in source files,<br />
indicated with special markers. For example, emacs interprets lines marked<br />
like this:<br />
<br />
-*- mode: c -*-<br />
<br />
Or like this:<br />
<br />
/*<br />
Local Variables:<br />
compile-command: &quot;gcc -DMAGIC_DEBUG_FLAG foo.c&quot;<br />
End:<br />
*/<br />
<br />
Vim interprets markers that look like this:<br />
<br />
/* vim:set sw=8 noet */<br />
<br />
Do not include any of these in source files. People have their own personal<br />
editor configurations, and your source files should not override them. This<br />
includes markers for indentation and mode configuration. People may use their<br />
own custom mode, or may have some other magic method for making indentation<br />
work correctly.<br />
<br />
<br />
== Inline assembly ==<br />
<br />
In architecture-specific code, you may need to use inline assembly to interface<br />
with CPU or platform functionality. Don't hesitate to do so when necessary.<br />
However, don't use inline assembly gratuitously when C can do the job. You can<br />
and should poke hardware from C when possible.<br />
<br />
Consider writing simple helper functions that wrap common bits of inline<br />
assembly, rather than repeatedly writing them with slight variations. Remember<br />
that inline assembly can use C parameters.<br />
<br />
Large, non-trivial assembly functions should go in .S files, with corresponding<br />
C prototypes defined in C header files. The C prototypes for assembly<br />
functions should use &quot;asmlinkage&quot;.<br />
<br />
You may need to mark your asm statement as volatile, to prevent GCC from<br />
removing it if GCC doesn't notice any side effects. You don't always need to<br />
do so, though, and doing so unnecessarily can limit optimization.<br />
<br />
When writing a single inline assembly statement containing multiple<br />
instructions, put each instruction on a separate line in a separate quoted<br />
string, and end each string except the last with \n\t to properly indent the<br />
next instruction in the assembly output:<br />
<br />
asm (&quot;magic %reg1, #42\n\t&quot;<br />
&quot;more_magic %reg2, %reg3&quot;<br />
: /* outputs */ : /* inputs */ : /* clobbers */);<br />
<br />
<br />
<br />
== References ==<br />
<br />
The C Programming Language, Second Edition<br />
by Brian W. Kernighan and Dennis M. Ritchie.<br />
Prentice Hall, Inc., 1988.<br />
ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).<br />
URL: http://cm.bell-labs.com/cm/cs/cbook/<br />
<br />
The Practice of Programming<br />
by Brian W. Kernighan and Rob Pike.<br />
Addison-Wesley, Inc., 1999.<br />
ISBN 0-201-61586-X.<br />
URL: http://cm.bell-labs.com/cm/cs/tpop/<br />
<br />
GNU manuals - where in compliance with K&amp;R and this text - for cpp, gcc,<br />
gcc internals and indent, all available from http://www.gnu.org/manual/<br />
<br />
WG14 is the international standardization working group for the programming<br />
language C, URL: http://www.open-std.org/JTC1/SC22/WG14/<br />
<br />
Kernel CodingStyle, by greg@kroah.com at OLS 2002:<br />
http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/</div>Stepanhttp://www.coreboot.org/index.php?title=Coding_Style&diff=12307Coding Style2013-12-05T18:47:58Z<p>Stepan: /* Typedefs */</p>
<hr />
<div>This is a short document describing the preferred coding style for the<br />
coreboot project. It is in many ways exactly the same as the Linux kernel<br />
coding style. In fact, most of this document has been copied from the<br />
[http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/Documentation/CodingStyle?id=HEAD Linux kernel coding style]<br />
<br />
Please at least consider the points made here.<br />
<br />
First off, I'd suggest printing out a copy of the GNU coding standards,<br />
and NOT read it. Burn them, it's a great symbolic gesture.<br />
<br />
Anyway, here goes:<br />
<br />
<br />
== Indentation ==<br />
<br />
Tabs are 8 characters, and thus indentations are also 8 characters.<br />
There are heretic movements that try to make indentations 4 (or even 2!)<br />
characters deep, and that is akin to trying to define the value of PI to<br />
be 3.<br />
<br />
Rationale: The whole idea behind indentation is to clearly define where<br />
a block of control starts and ends. Especially when you've been looking<br />
at your screen for 20 straight hours, you'll find it a lot easier to see<br />
how the indentation works if you have large indentations.<br />
<br />
Now, some people will claim that having 8-character indentations makes<br />
the code move too far to the right, and makes it hard to read on a<br />
80-character terminal screen. The answer to that is that if you need<br />
more than 3 levels of indentation, you're screwed anyway, and should fix<br />
your program.<br />
<br />
In short, 8-char indents make things easier to read, and have the added<br />
benefit of warning you when you're nesting your functions too deep.<br />
Heed that warning.<br />
<br />
The preferred way to ease multiple indentation levels in a switch statement is<br />
to align the &quot;switch&quot; and its subordinate &quot;case&quot; labels in the same column<br />
instead of &quot;double-indenting&quot; the &quot;case&quot; labels. E.g.:<br />
<br />
switch (suffix) {<br />
case 'G':<br />
case 'g':<br />
mem &lt;&lt;= 30;<br />
break;<br />
case 'M':<br />
case 'm':<br />
mem &lt;&lt;= 20;<br />
break;<br />
case 'K':<br />
case 'k':<br />
mem &lt;&lt;= 10;<br />
/* fall through */<br />
default:<br />
break;<br />
}<br />
<br />
<br />
Don't put multiple statements on a single line unless you have<br />
something to hide:<br />
<br />
if (condition) do_this;<br />
do_something_everytime;<br />
<br />
Don't put multiple assignments on a single line either. Kernel coding style<br />
is super simple. Avoid tricky expressions.<br />
<br />
Outside of comments, documentation and except in Kconfig, spaces are never<br />
used for indentation, and the above example is deliberately broken.<br />
<br />
Get a decent editor and don't leave whitespace at the end of lines.<br />
<br />
== Breaking long lines and strings ==<br />
<br />
Coding style is all about readability and maintainability using commonly<br />
available tools.<br />
<br />
The limit on the length of lines is 80 columns and this is a strongly<br />
preferred limit.<br />
<br />
Statements longer than 80 columns will be broken into sensible chunks, unless<br />
exceeding 80 columns significantly increases readability and does not hide<br />
information. Descendants are always substantially shorter than the parent and<br />
are placed substantially to the right. The same applies to function headers<br />
with a long argument list. However, never break user-visible strings such as<br />
printk messages, because that breaks the ability to grep for them.<br />
<br />
<br />
== Placing Braces and Spaces ==<br />
<br />
The other issue that always comes up in C styling is the placement of<br />
braces. Unlike the indent size, there are few technical reasons to<br />
choose one placement strategy over the other, but the preferred way, as<br />
shown to us by the prophets Kernighan and Ritchie, is to put the opening<br />
brace last on the line, and put the closing brace first, thusly:<br />
<br />
if (x is true) {<br />
we do y<br />
}<br />
<br />
This applies to all non-function statement blocks (if, switch, for,<br />
while, do). E.g.:<br />
<br />
switch (action) {<br />
case KOBJ_ADD:<br />
return &quot;add&quot;;<br />
case KOBJ_REMOVE:<br />
return &quot;remove&quot;;<br />
case KOBJ_CHANGE:<br />
return &quot;change&quot;;<br />
default:<br />
return NULL;<br />
}<br />
<br />
However, there is one special case, namely functions: they have the<br />
opening brace at the beginning of the next line, thus:<br />
<br />
int function(int x)<br />
{<br />
body of function<br />
}<br />
<br />
Heretic people all over the world have claimed that this inconsistency<br />
is ... well ... inconsistent, but all right-thinking people know that<br />
(a) K&amp;R are _right_ and (b) K&amp;R are right. Besides, functions are<br />
special anyway (you can't nest them in C).<br />
<br />
Note that the closing brace is empty on a line of its own, _except_ in<br />
the cases where it is followed by a continuation of the same statement,<br />
ie a &quot;while&quot; in a do-statement or an &quot;else&quot; in an if-statement, like<br />
this:<br />
<br />
do {<br />
body of do-loop<br />
} while (condition);<br />
<br />
and<br />
<br />
if (x == y) {<br />
..<br />
} else if (x &gt; y) {<br />
...<br />
} else {<br />
....<br />
}<br />
<br />
Rationale: K&amp;R.<br />
<br />
Also, note that this brace-placement also minimizes the number of empty<br />
(or almost empty) lines, without any loss of readability. Thus, as the<br />
supply of new-lines on your screen is not a renewable resource (think<br />
25-line terminal screens here), you have more empty lines to put<br />
comments on.<br />
<br />
Do not unnecessarily use braces where a single statement will do.<br />
<br />
if (condition)<br />
action();<br />
<br />
and<br />
<br />
if (condition)<br />
do_this();<br />
else<br />
do_that();<br />
<br />
This does not apply if only one branch of a conditional statement is a single<br />
statement; in the latter case use braces in both branches:<br />
<br />
if (condition) {<br />
do_this();<br />
do_that();<br />
} else {<br />
otherwise();<br />
}<br />
<br />
=== Spaces ===<br />
<br />
Linux kernel style for use of spaces depends (mostly) on<br />
function-versus-keyword usage. Use a space after (most) keywords. The<br />
notable exceptions are sizeof, typeof, alignof, and __attribute__, which look<br />
somewhat like functions (and are usually used with parentheses in Linux,<br />
although they are not required in the language, as in: &quot;sizeof info&quot; after<br />
&quot;struct fileinfo info;&quot; is declared).<br />
<br />
So use a space after these keywords:<br />
if, switch, case, for, do, while<br />
but not with sizeof, typeof, alignof, or __attribute__. E.g.,<br />
s = sizeof(struct file);<br />
<br />
Do not add spaces around (inside) parenthesized expressions. This example is<br />
*bad*:<br />
<br />
s = sizeof( struct file );<br />
<br />
When declaring pointer data or a function that returns a pointer type, the<br />
preferred use of '*' is adjacent to the data name or function name and not<br />
adjacent to the type name. Examples:<br />
<br />
char *linux_banner;<br />
unsigned long long memparse(char *ptr, char **retptr);<br />
char *match_strdup(substring_t *s);<br />
<br />
Use one space around (on each side of) most binary and ternary operators,<br />
such as any of these:<br />
<br />
= + - &lt; &gt; * / % | &amp; ^ &lt;= &gt;= == != ? :<br />
<br />
but no space after unary operators:<br />
&amp; * + - ~ ! sizeof typeof alignof __attribute__ defined<br />
<br />
no space before the postfix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
no space after the prefix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
and no space around the '.' and &quot;-&gt;&quot; structure member operators.<br />
<br />
Do not leave trailing whitespace at the ends of lines. Some editors with<br />
&quot;smart&quot; indentation will insert whitespace at the beginning of new lines as<br />
appropriate, so you can start typing the next line of code right away.<br />
However, some such editors do not remove the whitespace if you end up not<br />
putting a line of code there, such as if you leave a blank line. As a result,<br />
you end up with lines containing trailing whitespace.<br />
<br />
Git will warn you about patches that introduce trailing whitespace, and can<br />
optionally strip the trailing whitespace for you; however, if applying a series<br />
of patches, this may make later patches in the series fail by changing their<br />
context lines.<br />
<br />
== Naming ==<br />
<br />
C is a Spartan language, and so should your naming be. Unlike Modula-2<br />
and Pascal programmers, C programmers do not use cute names like<br />
ThisVariableIsATemporaryCounter. A C programmer would call that<br />
variable &quot;tmp&quot;, which is much easier to write, and not the least more<br />
difficult to understand.<br />
<br />
HOWEVER, while mixed-case names are frowned upon, descriptive names for<br />
global variables are a must. To call a global function &quot;foo&quot; is a<br />
shooting offense.<br />
<br />
GLOBAL variables (to be used only if you _really_ need them) need to<br />
have descriptive names, as do global functions. If you have a function<br />
that counts the number of active users, you should call that<br />
&quot;count_active_users()&quot; or similar, you should _not_ call it &quot;cntusr()&quot;.<br />
<br />
Encoding the type of a function into the name (so-called Hungarian<br />
notation) is brain damaged - the compiler knows the types anyway and can<br />
check those, and it only confuses the programmer. No wonder MicroSoft<br />
makes buggy programs.<br />
<br />
LOCAL variable names should be short, and to the point. If you have<br />
some random integer loop counter, it should probably be called &quot;i&quot;.<br />
Calling it &quot;loop_counter&quot; is non-productive, if there is no chance of it<br />
being mis-understood. Similarly, &quot;tmp&quot; can be just about any type of<br />
variable that is used to hold a temporary value.<br />
<br />
If you are afraid to mix up your local variable names, you have another<br />
problem, which is called the function-growth-hormone-imbalance syndrome.<br />
See chapter 6 (Functions).<br />
<br />
<br />
== Typedefs ==<br />
<br />
Please don't use things like &quot;vps_t&quot;.<br />
<br />
It's a _mistake_ to use typedef for structures and pointers. When you see a<br />
<br />
vps_t a;<br />
<br />
in the source, what does it mean?<br />
<br />
In contrast, if it says<br />
<br />
struct virtual_container *a;<br />
<br />
you can actually tell what &quot;a&quot; is.<br />
<br />
Lots of people think that typedefs &quot;help readability&quot;. Not so. They are<br />
useful only for:<br />
<br />
(a) totally opaque objects (where the typedef is actively used to _hide_ what the object is).<br />
<br />
Example: &quot;pte_t&quot; etc. opaque objects that you can only access using<br />
the proper accessor functions.<br />
<br />
NOTE! Opaqueness and &quot;accessor functions&quot; are not good in themselves.<br />
The reason we have them for things like pte_t etc. is that there<br />
really is absolutely _zero_ portably accessible information there.<br />
<br />
(b) Clear integer types, where the abstraction _helps_ avoid confusion<br />
whether it is &quot;int&quot; or &quot;long&quot;.<br />
<br />
u8/u16/u32 are perfectly fine typedefs, although they fit into<br />
category (d) better than here.<br />
<br />
NOTE! Again - there needs to be a _reason_ for this. If something is<br />
&quot;unsigned long&quot;, then there's no reason to do<br />
<br />
typedef unsigned long myflags_t;<br />
<br />
but if there is a clear reason for why it under certain circumstances<br />
might be an &quot;unsigned int&quot; and under other configurations might be<br />
&quot;unsigned long&quot;, then by all means go ahead and use a typedef.<br />
<br />
(c) when you use sparse to literally create a _new_ type for<br />
type-checking.<br />
<br />
(d) New types which are identical to standard C99 types, in certain<br />
exceptional circumstances.<br />
<br />
Although it would only take a short amount of time for the eyes and<br />
brain to become accustomed to the standard types like 'uint32_t',<br />
some people object to their use anyway.<br />
<br />
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their<br />
signed equivalents which are identical to standard types are<br />
permitted -- although they are not mandatory in new code of your<br />
own.<br />
<br />
When editing existing code which already uses one or the other set<br />
of types, you should conform to the existing choices in that code.<br />
<br />
(e) Types safe for use in userspace.<br />
<br />
In certain structures which are visible to userspace, we cannot<br />
require C99 types and cannot use the 'u32' form above. Thus, we<br />
use __u32 and similar types in all structures which are shared<br />
with userspace.<br />
<br />
Maybe there are other cases too, but the rule should basically be to NEVER<br />
EVER use a typedef unless you can clearly match one of those rules.<br />
<br />
<br />
In general, a pointer, or a struct that has elements that can reasonably<br />
be directly accessed should _never_ be a typedef.<br />
<br />
== Functions ==<br />
<br />
Functions should be short and sweet, and do just one thing. They should<br />
fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,<br />
as we all know), and do one thing and do that well.<br />
<br />
The maximum length of a function is inversely proportional to the<br />
complexity and indentation level of that function. So, if you have a<br />
conceptually simple function that is just one long (but simple)<br />
case-statement, where you have to do lots of small things for a lot of<br />
different cases, it's OK to have a longer function.<br />
<br />
However, if you have a complex function, and you suspect that a<br />
less-than-gifted first-year high-school student might not even<br />
understand what the function is all about, you should adhere to the<br />
maximum limits all the more closely. Use helper functions with<br />
descriptive names (you can ask the compiler to in-line them if you think<br />
it's performance-critical, and it will probably do a better job of it<br />
than you would have done).<br />
<br />
Another measure of the function is the number of local variables. They<br />
shouldn't exceed 5-10, or you're doing something wrong. Re-think the<br />
function, and split it into smaller pieces. A human brain can<br />
generally easily keep track of about 7 different things, anything more<br />
and it gets confused. You know you're brilliant, but maybe you'd like<br />
to understand what you did 2 weeks from now.<br />
<br />
In source files, separate functions with one blank line. If the function is<br />
exported, the EXPORT* macro for it should follow immediately after the closing<br />
function brace line. E.g.:<br />
<br />
int system_is_up(void)<br />
{<br />
return system_state == SYSTEM_RUNNING;<br />
}<br />
EXPORT_SYMBOL(system_is_up);<br />
<br />
In function prototypes, include parameter names with their data types.<br />
Although this is not required by the C language, it is preferred in Linux<br />
because it is a simple way to add valuable information for the reader.<br />
<br />
<br />
== Centralized exiting of functions ==<br />
<br />
Albeit deprecated by some people, the equivalent of the goto statement is<br />
used frequently by compilers in form of the unconditional jump instruction.<br />
<br />
The goto statement comes in handy when a function exits from multiple<br />
locations and some common work such as cleanup has to be done. If there is no<br />
cleanup needed then just return directly.<br />
<br />
The rationale is:<br />
<br />
- unconditional statements are easier to understand and follow<br />
- nesting is reduced<br />
- errors by not updating individual exit points when making<br />
modifications are prevented<br />
- saves the compiler work to optimize redundant code away ;)<br />
<br />
int fun(int a)<br />
{<br />
int result = 0;<br />
char *buffer = kmalloc(SIZE);<br />
<br />
if (buffer == NULL)<br />
return -ENOMEM;<br />
<br />
if (condition1) {<br />
while (loop1) {<br />
...<br />
}<br />
result = 1;<br />
goto out;<br />
}<br />
...<br />
out:<br />
kfree(buffer);<br />
return result;<br />
}<br />
<br />
== Commenting ==<br />
<br />
Comments are good, but there is also a danger of over-commenting. NEVER<br />
try to explain HOW your code works in a comment: it's much better to<br />
write the code so that the _working_ is obvious, and it's a waste of<br />
time to explain badly written code.<br />
<br />
Generally, you want your comments to tell WHAT your code does, not HOW.<br />
Also, try to avoid putting comments inside a function body: if the<br />
function is so complex that you need to separately comment parts of it,<br />
you should probably go back to chapter 6 for a while. You can make<br />
small comments to note or warn about something particularly clever (or<br />
ugly), but try to avoid excess. Instead, put the comments at the head<br />
of the function, telling people what it does, and possibly WHY it does<br />
it.<br />
<br />
When commenting the kernel API functions, please use the kernel-doc format.<br />
See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc<br />
for details.<br />
<br />
coreboot style for comments is the C89 &quot;/* ... */&quot; style.<br />
You may use C99-style &quot;// ...&quot; comments.<br />
<br />
The preferred style for long (multi-line) comments is:<br />
<br />
/*<br />
* This is the preferred style for multi-line<br />
* comments in the Linux kernel source code.<br />
* Please use it consistently.<br />
*<br />
* Description: A column of asterisks on the left side,<br />
* with beginning and ending almost-blank lines.<br />
*/<br />
<br />
For files in net/ and drivers/net/ the preferred style for long (multi-line)<br />
comments is a little different.<br />
<br />
/* The preferred comment style for files in net/ and drivers/net<br />
* looks like this.<br />
*<br />
* It is nearly the same as the generally preferred comment style,<br />
* but there is no initial almost-blank line.<br />
*/<br />
<br />
It's also important to comment data, whether they are basic types or derived<br />
types. To this end, use just one data declaration per line (no commas for<br />
multiple data declarations). This leaves you room for a small comment on each<br />
item, explaining its use.<br />
<br />
<br />
== You've made a mess of it ==<br />
<br />
That's OK, we all do. You've probably been told by your long-time Unix<br />
user helper that &quot;GNU emacs&quot; automatically formats the C sources for<br />
you, and you've noticed that yes, it does do that, but the defaults it<br />
uses are less than desirable (in fact, they are worse than random<br />
typing - an infinite number of monkeys typing into GNU emacs would never<br />
make a good program).<br />
<br />
So, you can either get rid of GNU emacs, or change it to use saner<br />
values. To do the latter, you can stick the following in your .emacs file:<br />
<br />
(defun c-lineup-arglist-tabs-only (ignored)<br />
&quot;Line up argument lists by tabs, not spaces&quot;<br />
(let* ((anchor (c-langelem-pos c-syntactic-element))<br />
(column (c-langelem-2nd-pos c-syntactic-element))<br />
(offset (- (1+ column) anchor))<br />
(steps (floor offset c-basic-offset)))<br />
(* (max steps 1)<br />
c-basic-offset)))<br />
<br />
(add-hook 'c-mode-common-hook<br />
(lambda ()<br />
;; Add kernel style<br />
(c-add-style<br />
&quot;linux-tabs-only&quot;<br />
'(&quot;linux&quot; (c-offsets-alist<br />
(arglist-cont-nonempty<br />
c-lineup-gcc-asm-reg<br />
c-lineup-arglist-tabs-only))))))<br />
<br />
(add-hook 'c-mode-hook<br />
(lambda ()<br />
(let ((filename (buffer-file-name)))<br />
;; Enable kernel mode for the appropriate files<br />
(when (and filename<br />
(string-match (expand-file-name &quot;~/src/linux-trees&quot;)<br />
filename))<br />
(setq indent-tabs-mode t)<br />
(c-set-style &quot;linux-tabs-only&quot;)))))<br />
<br />
This will make emacs go better with the kernel coding style for C<br />
files below ~/src/linux-trees.<br />
<br />
But even if you fail in getting emacs to do sane formatting, not<br />
everything is lost: use &quot;indent&quot;.<br />
<br />
Now, again, GNU indent has the same brain-dead settings that GNU emacs<br />
has, which is why you need to give it a few command line options.<br />
However, that's not too bad, because even the makers of GNU indent<br />
recognize the authority of K&amp;R (the GNU people aren't evil, they are<br />
just severely misguided in this matter), so you just give indent the<br />
options &quot;-kr -i8&quot; (stands for &quot;K&amp;R, 8 character indents&quot;), or use<br />
&quot;scripts/Lindent&quot;, which indents in the latest style.<br />
<br />
&quot;indent&quot; has a lot of options, and especially when it comes to comment<br />
re-formatting you may want to take a look at the man page. But<br />
remember: &quot;indent&quot; is not a fix for bad programming.<br />
<br />
<br />
== Kconfig configuration files ==<br />
<br />
For all of the Kconfig* configuration files throughout the source tree,<br />
the indentation is somewhat different. Lines under a &quot;config&quot; definition<br />
are indented with one tab, while help text is indented an additional two<br />
spaces. Example:<br />
<br />
config AUDIT<br />
bool &quot;Auditing support&quot;<br />
depends on NET<br />
help<br />
Enable auditing infrastructure that can be used with another<br />
kernel subsystem, such as SELinux (which requires this for<br />
logging of avc messages output). Does not do system-call<br />
auditing without CONFIG_AUDITSYSCALL.<br />
<br />
Seriously dangerous features (such as write support for certain<br />
filesystems) should advertise this prominently in their prompt string:<br />
<br />
config ADFS_FS_RW<br />
bool &quot;ADFS write support (DANGEROUS)&quot;<br />
depends on ADFS_FS<br />
...<br />
<br />
For full documentation on the configuration files, see the file<br />
Documentation/kbuild/kconfig-language.txt.<br />
<br />
<br />
== Data structures ==<br />
<br />
Data structures that have visibility outside the single-threaded<br />
environment they are created and destroyed in should always have<br />
reference counts. In the kernel, garbage collection doesn't exist (and<br />
outside the kernel garbage collection is slow and inefficient), which<br />
means that you absolutely _have_ to reference count all your uses.<br />
<br />
Reference counting means that you can avoid locking, and allows multiple<br />
users to have access to the data structure in parallel - and not having<br />
to worry about the structure suddenly going away from under them just<br />
because they slept or did something else for a while.<br />
<br />
Note that locking is _not_ a replacement for reference counting.<br />
Locking is used to keep data structures coherent, while reference<br />
counting is a memory management technique. Usually both are needed, and<br />
they are not to be confused with each other.<br />
<br />
Many data structures can indeed have two levels of reference counting,<br />
when there are users of different &quot;classes&quot;. The subclass count counts<br />
the number of subclass users, and decrements the global count just once<br />
when the subclass count goes to zero.<br />
<br />
Examples of this kind of &quot;multi-level-reference-counting&quot; can be found in<br />
memory management (&quot;struct mm_struct&quot;: mm_users and mm_count), and in<br />
filesystem code (&quot;struct super_block&quot;: s_count and s_active).<br />
<br />
Remember: if another thread can find your data structure, and you don't<br />
have a reference count on it, you almost certainly have a bug.<br />
<br />
<br />
== Macros, Enums and RTL ==<br />
<br />
Names of macros defining constants and labels in enums are capitalized.<br />
<br />
#define CONSTANT 0x12345<br />
<br />
Enums are preferred when defining several related constants.<br />
<br />
CAPITALIZED macro names are appreciated but macros resembling functions<br />
may be named in lower case.<br />
<br />
Generally, inline functions are preferable to macros resembling functions.<br />
<br />
Macros with multiple statements should be enclosed in a do - while block:<br />
<br />
#define macrofun(a, b, c) \<br />
do { \<br />
if (a == 5) \<br />
do_this(b, c); \<br />
} while (0)<br />
<br />
Things to avoid when using macros:<br />
<br />
1) macros that affect control flow:<br />
<br />
#define FOO(x) \<br />
do { \<br />
if (blah(x) &lt; 0) \<br />
return -EBUGGERED; \<br />
} while(0)<br />
<br />
is a _very_ bad idea. It looks like a function call but exits the &quot;calling&quot;<br />
function; don't break the internal parsers of those who will read the code.<br />
<br />
2) macros that depend on having a local variable with a magic name:<br />
<br />
#define FOO(val) bar(index, val)<br />
<br />
might look like a good thing, but it's confusing as hell when one reads the<br />
code and it's prone to breakage from seemingly innocent changes.<br />
<br />
3) macros with arguments that are used as l-values: FOO(x) = y; will<br />
bite you if somebody e.g. turns FOO into an inline function.<br />
<br />
4) forgetting about precedence: macros defining constants using expressions<br />
must enclose the expression in parentheses. Beware of similar issues with<br />
macros using parameters.<br />
<br />
#define CONSTANT 0x4000<br />
#define CONSTEXP (CONSTANT | 3)<br />
<br />
The cpp manual deals with macros exhaustively. The gcc internals manual also<br />
covers RTL which is used frequently with assembly language in the kernel.<br />
<br />
<br />
== Printing kernel messages ==<br />
<br />
Kernel developers like to be seen as literate. Do mind the spelling<br />
of kernel messages to make a good impression. Do not use crippled<br />
words like &quot;dont&quot;; use &quot;do not&quot; or &quot;don't&quot; instead. Make the messages<br />
concise, clear, and unambiguous.<br />
<br />
Kernel messages do not have to be terminated with a period.<br />
<br />
Printing numbers in parentheses (%d) adds no value and should be avoided.<br />
<br />
There are a number of driver model diagnostic macros in &lt;linux/device.h&gt;<br />
which you should use to make sure messages are matched to the right device<br />
and driver, and are tagged with the right level: dev_err(), dev_warn(),<br />
dev_info(), and so forth. For messages that aren't associated with a<br />
particular device, &lt;linux/printk.h&gt; defines pr_debug() and pr_info().<br />
<br />
Coming up with good debugging messages can be quite a challenge; and once<br />
you have them, they can be a huge help for remote troubleshooting. Such<br />
messages should be compiled out when the DEBUG symbol is not defined (that<br />
is, by default they are not included). When you use dev_dbg() or pr_debug(),<br />
that's automatic. Many subsystems have Kconfig options to turn on -DDEBUG.<br />
A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to the<br />
ones already enabled by DEBUG.<br />
<br />
<br />
== Allocating memory ==<br />
<br />
The kernel provides the following general purpose memory allocators:<br />
kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and<br />
vzalloc(). Please refer to the API documentation for further information<br />
about them.<br />
<br />
The preferred form for passing a size of a struct is the following:<br />
<br />
p = kmalloc(sizeof(*p), ...);<br />
<br />
The alternative form where struct name is spelled out hurts readability and<br />
introduces an opportunity for a bug when the pointer variable type is changed<br />
but the corresponding sizeof that is passed to a memory allocator is not.<br />
<br />
Casting the return value which is a void pointer is redundant. The conversion<br />
from void pointer to any other pointer type is guaranteed by the C programming<br />
language.<br />
<br />
The preferred form for allocating an array is the following:<br />
<br />
p = kmalloc_array(n, sizeof(...), ...);<br />
<br />
The preferred form for allocating a zeroed array is the following:<br />
<br />
p = kcalloc(n, sizeof(...), ...);<br />
<br />
Both forms check for overflow on the allocation size n * sizeof(...),<br />
and return NULL if that occurred.<br />
<br />
<br />
== The inline disease ==<br />
<br />
There appears to be a common misperception that gcc has a magic &quot;make me<br />
faster&quot; speedup option called &quot;inline&quot;. While the use of inlines can be<br />
appropriate (for example as a means of replacing macros, see Chapter 12), it<br />
very often is not. Abundant use of the inline keyword leads to a much bigger<br />
kernel, which in turn slows the system as a whole down, due to a bigger<br />
icache footprint for the CPU and simply because there is less memory<br />
available for the pagecache. Just think about it; a pagecache miss causes a<br />
disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles<br />
that can go into these 5 milliseconds.<br />
<br />
A reasonable rule of thumb is to not put inline at functions that have more<br />
than 3 lines of code in them. An exception to this rule are the cases where<br />
a parameter is known to be a compiletime constant, and as a result of this<br />
constantness you *know* the compiler will be able to optimize most of your<br />
function away at compile time. For a good example of this later case, see<br />
the kmalloc() inline function.<br />
<br />
Often people argue that adding inline to functions that are static and used<br />
only once is always a win since there is no space tradeoff. While this is<br />
technically correct, gcc is capable of inlining these automatically without<br />
help, and the maintenance issue of removing the inline when a second user<br />
appears outweighs the potential value of the hint that tells gcc to do<br />
something it would have done anyway.<br />
<br />
<br />
== Function return values and names ==<br />
<br />
Functions can return values of many different kinds, and one of the<br />
most common is a value indicating whether the function succeeded or<br />
failed. Such a value can be represented as an error-code integer<br />
(-Exxx = failure, 0 = success) or a &quot;succeeded&quot; boolean (0 = failure,<br />
non-zero = success).<br />
<br />
Mixing up these two sorts of representations is a fertile source of<br />
difficult-to-find bugs. If the C language included a strong distinction<br />
between integers and booleans then the compiler would find these mistakes<br />
for us... but it doesn't. To help prevent such bugs, always follow this<br />
convention:<br />
<br />
If the name of a function is an action or an imperative command,<br />
the function should return an error-code integer. If the name<br />
is a predicate, the function should return a &quot;succeeded&quot; boolean.<br />
<br />
For example, &quot;add work&quot; is a command, and the add_work() function returns 0<br />
for success or -EBUSY for failure. In the same way, &quot;PCI device present&quot; is<br />
a predicate, and the pci_dev_present() function returns 1 if it succeeds in<br />
finding a matching device or 0 if it doesn't.<br />
<br />
All EXPORTed functions must respect this convention, and so should all<br />
public functions. Private (static) functions need not, but it is<br />
recommended that they do.<br />
<br />
Functions whose return value is the actual result of a computation, rather<br />
than an indication of whether the computation succeeded, are not subject to<br />
this rule. Generally they indicate failure by returning some out-of-range<br />
result. Typical examples would be functions that return pointers; they use<br />
NULL or the ERR_PTR mechanism to report failure.<br />
<br />
<br />
== Don't re-invent the kernel macros ==<br />
<br />
The header file include/linux/kernel.h contains a number of macros that<br />
you should use, rather than explicitly coding some variant of them yourself.<br />
For example, if you need to calculate the length of an array, take advantage<br />
of the macro<br />
<br />
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))<br />
<br />
Similarly, if you need to calculate the size of some structure member, use<br />
<br />
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)-&gt;f))<br />
<br />
There are also min() and max() macros that do strict type checking if you<br />
need them. Feel free to peruse that header file to see what else is already<br />
defined that you shouldn't reproduce in your code.<br />
<br />
<br />
== Editor modelines and other cruft ==<br />
<br />
Some editors can interpret configuration information embedded in source files,<br />
indicated with special markers. For example, emacs interprets lines marked<br />
like this:<br />
<br />
-*- mode: c -*-<br />
<br />
Or like this:<br />
<br />
/*<br />
Local Variables:<br />
compile-command: &quot;gcc -DMAGIC_DEBUG_FLAG foo.c&quot;<br />
End:<br />
*/<br />
<br />
Vim interprets markers that look like this:<br />
<br />
/* vim:set sw=8 noet */<br />
<br />
Do not include any of these in source files. People have their own personal<br />
editor configurations, and your source files should not override them. This<br />
includes markers for indentation and mode configuration. People may use their<br />
own custom mode, or may have some other magic method for making indentation<br />
work correctly.<br />
<br />
<br />
== Inline assembly ==<br />
<br />
In architecture-specific code, you may need to use inline assembly to interface<br />
with CPU or platform functionality. Don't hesitate to do so when necessary.<br />
However, don't use inline assembly gratuitously when C can do the job. You can<br />
and should poke hardware from C when possible.<br />
<br />
Consider writing simple helper functions that wrap common bits of inline<br />
assembly, rather than repeatedly writing them with slight variations. Remember<br />
that inline assembly can use C parameters.<br />
<br />
Large, non-trivial assembly functions should go in .S files, with corresponding<br />
C prototypes defined in C header files. The C prototypes for assembly<br />
functions should use &quot;asmlinkage&quot;.<br />
<br />
You may need to mark your asm statement as volatile, to prevent GCC from<br />
removing it if GCC doesn't notice any side effects. You don't always need to<br />
do so, though, and doing so unnecessarily can limit optimization.<br />
<br />
When writing a single inline assembly statement containing multiple<br />
instructions, put each instruction on a separate line in a separate quoted<br />
string, and end each string except the last with \n\t to properly indent the<br />
next instruction in the assembly output:<br />
<br />
asm (&quot;magic %reg1, #42\n\t&quot;<br />
&quot;more_magic %reg2, %reg3&quot;<br />
: /* outputs */ : /* inputs */ : /* clobbers */);<br />
<br />
<br />
<br />
== References ==<br />
<br />
The C Programming Language, Second Edition<br />
by Brian W. Kernighan and Dennis M. Ritchie.<br />
Prentice Hall, Inc., 1988.<br />
ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).<br />
URL: http://cm.bell-labs.com/cm/cs/cbook/<br />
<br />
The Practice of Programming<br />
by Brian W. Kernighan and Rob Pike.<br />
Addison-Wesley, Inc., 1999.<br />
ISBN 0-201-61586-X.<br />
URL: http://cm.bell-labs.com/cm/cs/tpop/<br />
<br />
GNU manuals - where in compliance with K&amp;R and this text - for cpp, gcc,<br />
gcc internals and indent, all available from http://www.gnu.org/manual/<br />
<br />
WG14 is the international standardization working group for the programming<br />
language C, URL: http://www.open-std.org/JTC1/SC22/WG14/<br />
<br />
Kernel CodingStyle, by greg@kroah.com at OLS 2002:<br />
http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/</div>Stepanhttp://www.coreboot.org/index.php?title=Coding_Style&diff=12306Coding Style2013-12-05T18:44:43Z<p>Stepan: /* Placing Braces and Spaces */</p>
<hr />
<div>This is a short document describing the preferred coding style for the<br />
coreboot project. It is in many ways exactly the same as the Linux kernel<br />
coding style. In fact, most of this document has been copied from the<br />
[http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/Documentation/CodingStyle?id=HEAD Linux kernel coding style]<br />
<br />
Please at least consider the points made here.<br />
<br />
First off, I'd suggest printing out a copy of the GNU coding standards,<br />
and NOT read it. Burn them, it's a great symbolic gesture.<br />
<br />
Anyway, here goes:<br />
<br />
<br />
== Indentation ==<br />
<br />
Tabs are 8 characters, and thus indentations are also 8 characters.<br />
There are heretic movements that try to make indentations 4 (or even 2!)<br />
characters deep, and that is akin to trying to define the value of PI to<br />
be 3.<br />
<br />
Rationale: The whole idea behind indentation is to clearly define where<br />
a block of control starts and ends. Especially when you've been looking<br />
at your screen for 20 straight hours, you'll find it a lot easier to see<br />
how the indentation works if you have large indentations.<br />
<br />
Now, some people will claim that having 8-character indentations makes<br />
the code move too far to the right, and makes it hard to read on a<br />
80-character terminal screen. The answer to that is that if you need<br />
more than 3 levels of indentation, you're screwed anyway, and should fix<br />
your program.<br />
<br />
In short, 8-char indents make things easier to read, and have the added<br />
benefit of warning you when you're nesting your functions too deep.<br />
Heed that warning.<br />
<br />
The preferred way to ease multiple indentation levels in a switch statement is<br />
to align the &quot;switch&quot; and its subordinate &quot;case&quot; labels in the same column<br />
instead of &quot;double-indenting&quot; the &quot;case&quot; labels. E.g.:<br />
<br />
switch (suffix) {<br />
case 'G':<br />
case 'g':<br />
mem &lt;&lt;= 30;<br />
break;<br />
case 'M':<br />
case 'm':<br />
mem &lt;&lt;= 20;<br />
break;<br />
case 'K':<br />
case 'k':<br />
mem &lt;&lt;= 10;<br />
/* fall through */<br />
default:<br />
break;<br />
}<br />
<br />
<br />
Don't put multiple statements on a single line unless you have<br />
something to hide:<br />
<br />
if (condition) do_this;<br />
do_something_everytime;<br />
<br />
Don't put multiple assignments on a single line either. Kernel coding style<br />
is super simple. Avoid tricky expressions.<br />
<br />
Outside of comments, documentation and except in Kconfig, spaces are never<br />
used for indentation, and the above example is deliberately broken.<br />
<br />
Get a decent editor and don't leave whitespace at the end of lines.<br />
<br />
== Breaking long lines and strings ==<br />
<br />
Coding style is all about readability and maintainability using commonly<br />
available tools.<br />
<br />
The limit on the length of lines is 80 columns and this is a strongly<br />
preferred limit.<br />
<br />
Statements longer than 80 columns will be broken into sensible chunks, unless<br />
exceeding 80 columns significantly increases readability and does not hide<br />
information. Descendants are always substantially shorter than the parent and<br />
are placed substantially to the right. The same applies to function headers<br />
with a long argument list. However, never break user-visible strings such as<br />
printk messages, because that breaks the ability to grep for them.<br />
<br />
<br />
== Placing Braces and Spaces ==<br />
<br />
The other issue that always comes up in C styling is the placement of<br />
braces. Unlike the indent size, there are few technical reasons to<br />
choose one placement strategy over the other, but the preferred way, as<br />
shown to us by the prophets Kernighan and Ritchie, is to put the opening<br />
brace last on the line, and put the closing brace first, thusly:<br />
<br />
if (x is true) {<br />
we do y<br />
}<br />
<br />
This applies to all non-function statement blocks (if, switch, for,<br />
while, do). E.g.:<br />
<br />
switch (action) {<br />
case KOBJ_ADD:<br />
return &quot;add&quot;;<br />
case KOBJ_REMOVE:<br />
return &quot;remove&quot;;<br />
case KOBJ_CHANGE:<br />
return &quot;change&quot;;<br />
default:<br />
return NULL;<br />
}<br />
<br />
However, there is one special case, namely functions: they have the<br />
opening brace at the beginning of the next line, thus:<br />
<br />
int function(int x)<br />
{<br />
body of function<br />
}<br />
<br />
Heretic people all over the world have claimed that this inconsistency<br />
is ... well ... inconsistent, but all right-thinking people know that<br />
(a) K&amp;R are _right_ and (b) K&amp;R are right. Besides, functions are<br />
special anyway (you can't nest them in C).<br />
<br />
Note that the closing brace is empty on a line of its own, _except_ in<br />
the cases where it is followed by a continuation of the same statement,<br />
ie a &quot;while&quot; in a do-statement or an &quot;else&quot; in an if-statement, like<br />
this:<br />
<br />
do {<br />
body of do-loop<br />
} while (condition);<br />
<br />
and<br />
<br />
if (x == y) {<br />
..<br />
} else if (x &gt; y) {<br />
...<br />
} else {<br />
....<br />
}<br />
<br />
Rationale: K&amp;R.<br />
<br />
Also, note that this brace-placement also minimizes the number of empty<br />
(or almost empty) lines, without any loss of readability. Thus, as the<br />
supply of new-lines on your screen is not a renewable resource (think<br />
25-line terminal screens here), you have more empty lines to put<br />
comments on.<br />
<br />
Do not unnecessarily use braces where a single statement will do.<br />
<br />
if (condition)<br />
action();<br />
<br />
and<br />
<br />
if (condition)<br />
do_this();<br />
else<br />
do_that();<br />
<br />
This does not apply if only one branch of a conditional statement is a single<br />
statement; in the latter case use braces in both branches:<br />
<br />
if (condition) {<br />
do_this();<br />
do_that();<br />
} else {<br />
otherwise();<br />
}<br />
<br />
=== Spaces ===<br />
<br />
Linux kernel style for use of spaces depends (mostly) on<br />
function-versus-keyword usage. Use a space after (most) keywords. The<br />
notable exceptions are sizeof, typeof, alignof, and __attribute__, which look<br />
somewhat like functions (and are usually used with parentheses in Linux,<br />
although they are not required in the language, as in: &quot;sizeof info&quot; after<br />
&quot;struct fileinfo info;&quot; is declared).<br />
<br />
So use a space after these keywords:<br />
if, switch, case, for, do, while<br />
but not with sizeof, typeof, alignof, or __attribute__. E.g.,<br />
s = sizeof(struct file);<br />
<br />
Do not add spaces around (inside) parenthesized expressions. This example is<br />
*bad*:<br />
<br />
s = sizeof( struct file );<br />
<br />
When declaring pointer data or a function that returns a pointer type, the<br />
preferred use of '*' is adjacent to the data name or function name and not<br />
adjacent to the type name. Examples:<br />
<br />
char *linux_banner;<br />
unsigned long long memparse(char *ptr, char **retptr);<br />
char *match_strdup(substring_t *s);<br />
<br />
Use one space around (on each side of) most binary and ternary operators,<br />
such as any of these:<br />
<br />
= + - &lt; &gt; * / % | &amp; ^ &lt;= &gt;= == != ? :<br />
<br />
but no space after unary operators:<br />
&amp; * + - ~ ! sizeof typeof alignof __attribute__ defined<br />
<br />
no space before the postfix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
no space after the prefix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
and no space around the '.' and &quot;-&gt;&quot; structure member operators.<br />
<br />
Do not leave trailing whitespace at the ends of lines. Some editors with<br />
&quot;smart&quot; indentation will insert whitespace at the beginning of new lines as<br />
appropriate, so you can start typing the next line of code right away.<br />
However, some such editors do not remove the whitespace if you end up not<br />
putting a line of code there, such as if you leave a blank line. As a result,<br />
you end up with lines containing trailing whitespace.<br />
<br />
Git will warn you about patches that introduce trailing whitespace, and can<br />
optionally strip the trailing whitespace for you; however, if applying a series<br />
of patches, this may make later patches in the series fail by changing their<br />
context lines.<br />
<br />
== Naming ==<br />
<br />
C is a Spartan language, and so should your naming be. Unlike Modula-2<br />
and Pascal programmers, C programmers do not use cute names like<br />
ThisVariableIsATemporaryCounter. A C programmer would call that<br />
variable &quot;tmp&quot;, which is much easier to write, and not the least more<br />
difficult to understand.<br />
<br />
HOWEVER, while mixed-case names are frowned upon, descriptive names for<br />
global variables are a must. To call a global function &quot;foo&quot; is a<br />
shooting offense.<br />
<br />
GLOBAL variables (to be used only if you _really_ need them) need to<br />
have descriptive names, as do global functions. If you have a function<br />
that counts the number of active users, you should call that<br />
&quot;count_active_users()&quot; or similar, you should _not_ call it &quot;cntusr()&quot;.<br />
<br />
Encoding the type of a function into the name (so-called Hungarian<br />
notation) is brain damaged - the compiler knows the types anyway and can<br />
check those, and it only confuses the programmer. No wonder MicroSoft<br />
makes buggy programs.<br />
<br />
LOCAL variable names should be short, and to the point. If you have<br />
some random integer loop counter, it should probably be called &quot;i&quot;.<br />
Calling it &quot;loop_counter&quot; is non-productive, if there is no chance of it<br />
being mis-understood. Similarly, &quot;tmp&quot; can be just about any type of<br />
variable that is used to hold a temporary value.<br />
<br />
If you are afraid to mix up your local variable names, you have another<br />
problem, which is called the function-growth-hormone-imbalance syndrome.<br />
See chapter 6 (Functions).<br />
<br />
<br />
== Typedefs ==<br />
<br />
Please don't use things like &quot;vps_t&quot;.<br />
<br />
It's a _mistake_ to use typedef for structures and pointers. When you see a<br />
<br />
vps_t a;<br />
<br />
in the source, what does it mean?<br />
<br />
In contrast, if it says<br />
<br />
struct virtual_container *a;<br />
<br />
you can actually tell what &quot;a&quot; is.<br />
<br />
Lots of people think that typedefs &quot;help readability&quot;. Not so. They are<br />
useful only for:<br />
<br />
(a) totally opaque objects (where the typedef is actively used to _hide_<br />
what the object is).<br />
<br />
Example: &quot;pte_t&quot; etc. opaque objects that you can only access using<br />
the proper accessor functions.<br />
<br />
NOTE! Opaqueness and &quot;accessor functions&quot; are not good in themselves.<br />
The reason we have them for things like pte_t etc. is that there<br />
really is absolutely _zero_ portably accessible information there.<br />
<br />
(b) Clear integer types, where the abstraction _helps_ avoid confusion<br />
whether it is &quot;int&quot; or &quot;long&quot;.<br />
<br />
u8/u16/u32 are perfectly fine typedefs, although they fit into<br />
category (d) better than here.<br />
<br />
NOTE! Again - there needs to be a _reason_ for this. If something is<br />
&quot;unsigned long&quot;, then there's no reason to do<br />
<br />
typedef unsigned long myflags_t;<br />
<br />
but if there is a clear reason for why it under certain circumstances<br />
might be an &quot;unsigned int&quot; and under other configurations might be<br />
&quot;unsigned long&quot;, then by all means go ahead and use a typedef.<br />
<br />
(c) when you use sparse to literally create a _new_ type for<br />
type-checking.<br />
<br />
(d) New types which are identical to standard C99 types, in certain<br />
exceptional circumstances.<br />
<br />
Although it would only take a short amount of time for the eyes and<br />
brain to become accustomed to the standard types like 'uint32_t',<br />
some people object to their use anyway.<br />
<br />
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their<br />
signed equivalents which are identical to standard types are<br />
permitted -- although they are not mandatory in new code of your<br />
own.<br />
<br />
When editing existing code which already uses one or the other set<br />
of types, you should conform to the existing choices in that code.<br />
<br />
(e) Types safe for use in userspace.<br />
<br />
In certain structures which are visible to userspace, we cannot<br />
require C99 types and cannot use the 'u32' form above. Thus, we<br />
use __u32 and similar types in all structures which are shared<br />
with userspace.<br />
<br />
Maybe there are other cases too, but the rule should basically be to NEVER<br />
EVER use a typedef unless you can clearly match one of those rules.<br />
<br />
In general, a pointer, or a struct that has elements that can reasonably<br />
be directly accessed should _never_ be a typedef.<br />
<br />
<br />
== Functions ==<br />
<br />
Functions should be short and sweet, and do just one thing. They should<br />
fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,<br />
as we all know), and do one thing and do that well.<br />
<br />
The maximum length of a function is inversely proportional to the<br />
complexity and indentation level of that function. So, if you have a<br />
conceptually simple function that is just one long (but simple)<br />
case-statement, where you have to do lots of small things for a lot of<br />
different cases, it's OK to have a longer function.<br />
<br />
However, if you have a complex function, and you suspect that a<br />
less-than-gifted first-year high-school student might not even<br />
understand what the function is all about, you should adhere to the<br />
maximum limits all the more closely. Use helper functions with<br />
descriptive names (you can ask the compiler to in-line them if you think<br />
it's performance-critical, and it will probably do a better job of it<br />
than you would have done).<br />
<br />
Another measure of the function is the number of local variables. They<br />
shouldn't exceed 5-10, or you're doing something wrong. Re-think the<br />
function, and split it into smaller pieces. A human brain can<br />
generally easily keep track of about 7 different things, anything more<br />
and it gets confused. You know you're brilliant, but maybe you'd like<br />
to understand what you did 2 weeks from now.<br />
<br />
In source files, separate functions with one blank line. If the function is<br />
exported, the EXPORT* macro for it should follow immediately after the closing<br />
function brace line. E.g.:<br />
<br />
int system_is_up(void)<br />
{<br />
return system_state == SYSTEM_RUNNING;<br />
}<br />
EXPORT_SYMBOL(system_is_up);<br />
<br />
In function prototypes, include parameter names with their data types.<br />
Although this is not required by the C language, it is preferred in Linux<br />
because it is a simple way to add valuable information for the reader.<br />
<br />
<br />
== Centralized exiting of functions ==<br />
<br />
Albeit deprecated by some people, the equivalent of the goto statement is<br />
used frequently by compilers in form of the unconditional jump instruction.<br />
<br />
The goto statement comes in handy when a function exits from multiple<br />
locations and some common work such as cleanup has to be done. If there is no<br />
cleanup needed then just return directly.<br />
<br />
The rationale is:<br />
<br />
- unconditional statements are easier to understand and follow<br />
- nesting is reduced<br />
- errors by not updating individual exit points when making<br />
modifications are prevented<br />
- saves the compiler work to optimize redundant code away ;)<br />
<br />
int fun(int a)<br />
{<br />
int result = 0;<br />
char *buffer = kmalloc(SIZE);<br />
<br />
if (buffer == NULL)<br />
return -ENOMEM;<br />
<br />
if (condition1) {<br />
while (loop1) {<br />
...<br />
}<br />
result = 1;<br />
goto out;<br />
}<br />
...<br />
out:<br />
kfree(buffer);<br />
return result;<br />
}<br />
<br />
== Commenting ==<br />
<br />
Comments are good, but there is also a danger of over-commenting. NEVER<br />
try to explain HOW your code works in a comment: it's much better to<br />
write the code so that the _working_ is obvious, and it's a waste of<br />
time to explain badly written code.<br />
<br />
Generally, you want your comments to tell WHAT your code does, not HOW.<br />
Also, try to avoid putting comments inside a function body: if the<br />
function is so complex that you need to separately comment parts of it,<br />
you should probably go back to chapter 6 for a while. You can make<br />
small comments to note or warn about something particularly clever (or<br />
ugly), but try to avoid excess. Instead, put the comments at the head<br />
of the function, telling people what it does, and possibly WHY it does<br />
it.<br />
<br />
When commenting the kernel API functions, please use the kernel-doc format.<br />
See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc<br />
for details.<br />
<br />
coreboot style for comments is the C89 &quot;/* ... */&quot; style.<br />
You may use C99-style &quot;// ...&quot; comments.<br />
<br />
The preferred style for long (multi-line) comments is:<br />
<br />
/*<br />
* This is the preferred style for multi-line<br />
* comments in the Linux kernel source code.<br />
* Please use it consistently.<br />
*<br />
* Description: A column of asterisks on the left side,<br />
* with beginning and ending almost-blank lines.<br />
*/<br />
<br />
For files in net/ and drivers/net/ the preferred style for long (multi-line)<br />
comments is a little different.<br />
<br />
/* The preferred comment style for files in net/ and drivers/net<br />
* looks like this.<br />
*<br />
* It is nearly the same as the generally preferred comment style,<br />
* but there is no initial almost-blank line.<br />
*/<br />
<br />
It's also important to comment data, whether they are basic types or derived<br />
types. To this end, use just one data declaration per line (no commas for<br />
multiple data declarations). This leaves you room for a small comment on each<br />
item, explaining its use.<br />
<br />
<br />
== You've made a mess of it ==<br />
<br />
That's OK, we all do. You've probably been told by your long-time Unix<br />
user helper that &quot;GNU emacs&quot; automatically formats the C sources for<br />
you, and you've noticed that yes, it does do that, but the defaults it<br />
uses are less than desirable (in fact, they are worse than random<br />
typing - an infinite number of monkeys typing into GNU emacs would never<br />
make a good program).<br />
<br />
So, you can either get rid of GNU emacs, or change it to use saner<br />
values. To do the latter, you can stick the following in your .emacs file:<br />
<br />
(defun c-lineup-arglist-tabs-only (ignored)<br />
&quot;Line up argument lists by tabs, not spaces&quot;<br />
(let* ((anchor (c-langelem-pos c-syntactic-element))<br />
(column (c-langelem-2nd-pos c-syntactic-element))<br />
(offset (- (1+ column) anchor))<br />
(steps (floor offset c-basic-offset)))<br />
(* (max steps 1)<br />
c-basic-offset)))<br />
<br />
(add-hook 'c-mode-common-hook<br />
(lambda ()<br />
;; Add kernel style<br />
(c-add-style<br />
&quot;linux-tabs-only&quot;<br />
'(&quot;linux&quot; (c-offsets-alist<br />
(arglist-cont-nonempty<br />
c-lineup-gcc-asm-reg<br />
c-lineup-arglist-tabs-only))))))<br />
<br />
(add-hook 'c-mode-hook<br />
(lambda ()<br />
(let ((filename (buffer-file-name)))<br />
;; Enable kernel mode for the appropriate files<br />
(when (and filename<br />
(string-match (expand-file-name &quot;~/src/linux-trees&quot;)<br />
filename))<br />
(setq indent-tabs-mode t)<br />
(c-set-style &quot;linux-tabs-only&quot;)))))<br />
<br />
This will make emacs go better with the kernel coding style for C<br />
files below ~/src/linux-trees.<br />
<br />
But even if you fail in getting emacs to do sane formatting, not<br />
everything is lost: use &quot;indent&quot;.<br />
<br />
Now, again, GNU indent has the same brain-dead settings that GNU emacs<br />
has, which is why you need to give it a few command line options.<br />
However, that's not too bad, because even the makers of GNU indent<br />
recognize the authority of K&amp;R (the GNU people aren't evil, they are<br />
just severely misguided in this matter), so you just give indent the<br />
options &quot;-kr -i8&quot; (stands for &quot;K&amp;R, 8 character indents&quot;), or use<br />
&quot;scripts/Lindent&quot;, which indents in the latest style.<br />
<br />
&quot;indent&quot; has a lot of options, and especially when it comes to comment<br />
re-formatting you may want to take a look at the man page. But<br />
remember: &quot;indent&quot; is not a fix for bad programming.<br />
<br />
<br />
== Kconfig configuration files ==<br />
<br />
For all of the Kconfig* configuration files throughout the source tree,<br />
the indentation is somewhat different. Lines under a &quot;config&quot; definition<br />
are indented with one tab, while help text is indented an additional two<br />
spaces. Example:<br />
<br />
config AUDIT<br />
bool &quot;Auditing support&quot;<br />
depends on NET<br />
help<br />
Enable auditing infrastructure that can be used with another<br />
kernel subsystem, such as SELinux (which requires this for<br />
logging of avc messages output). Does not do system-call<br />
auditing without CONFIG_AUDITSYSCALL.<br />
<br />
Seriously dangerous features (such as write support for certain<br />
filesystems) should advertise this prominently in their prompt string:<br />
<br />
config ADFS_FS_RW<br />
bool &quot;ADFS write support (DANGEROUS)&quot;<br />
depends on ADFS_FS<br />
...<br />
<br />
For full documentation on the configuration files, see the file<br />
Documentation/kbuild/kconfig-language.txt.<br />
<br />
<br />
== Data structures ==<br />
<br />
Data structures that have visibility outside the single-threaded<br />
environment they are created and destroyed in should always have<br />
reference counts. In the kernel, garbage collection doesn't exist (and<br />
outside the kernel garbage collection is slow and inefficient), which<br />
means that you absolutely _have_ to reference count all your uses.<br />
<br />
Reference counting means that you can avoid locking, and allows multiple<br />
users to have access to the data structure in parallel - and not having<br />
to worry about the structure suddenly going away from under them just<br />
because they slept or did something else for a while.<br />
<br />
Note that locking is _not_ a replacement for reference counting.<br />
Locking is used to keep data structures coherent, while reference<br />
counting is a memory management technique. Usually both are needed, and<br />
they are not to be confused with each other.<br />
<br />
Many data structures can indeed have two levels of reference counting,<br />
when there are users of different &quot;classes&quot;. The subclass count counts<br />
the number of subclass users, and decrements the global count just once<br />
when the subclass count goes to zero.<br />
<br />
Examples of this kind of &quot;multi-level-reference-counting&quot; can be found in<br />
memory management (&quot;struct mm_struct&quot;: mm_users and mm_count), and in<br />
filesystem code (&quot;struct super_block&quot;: s_count and s_active).<br />
<br />
Remember: if another thread can find your data structure, and you don't<br />
have a reference count on it, you almost certainly have a bug.<br />
<br />
<br />
== Macros, Enums and RTL ==<br />
<br />
Names of macros defining constants and labels in enums are capitalized.<br />
<br />
#define CONSTANT 0x12345<br />
<br />
Enums are preferred when defining several related constants.<br />
<br />
CAPITALIZED macro names are appreciated but macros resembling functions<br />
may be named in lower case.<br />
<br />
Generally, inline functions are preferable to macros resembling functions.<br />
<br />
Macros with multiple statements should be enclosed in a do - while block:<br />
<br />
#define macrofun(a, b, c) \<br />
do { \<br />
if (a == 5) \<br />
do_this(b, c); \<br />
} while (0)<br />
<br />
Things to avoid when using macros:<br />
<br />
1) macros that affect control flow:<br />
<br />
#define FOO(x) \<br />
do { \<br />
if (blah(x) &lt; 0) \<br />
return -EBUGGERED; \<br />
} while(0)<br />
<br />
is a _very_ bad idea. It looks like a function call but exits the &quot;calling&quot;<br />
function; don't break the internal parsers of those who will read the code.<br />
<br />
2) macros that depend on having a local variable with a magic name:<br />
<br />
#define FOO(val) bar(index, val)<br />
<br />
might look like a good thing, but it's confusing as hell when one reads the<br />
code and it's prone to breakage from seemingly innocent changes.<br />
<br />
3) macros with arguments that are used as l-values: FOO(x) = y; will<br />
bite you if somebody e.g. turns FOO into an inline function.<br />
<br />
4) forgetting about precedence: macros defining constants using expressions<br />
must enclose the expression in parentheses. Beware of similar issues with<br />
macros using parameters.<br />
<br />
#define CONSTANT 0x4000<br />
#define CONSTEXP (CONSTANT | 3)<br />
<br />
The cpp manual deals with macros exhaustively. The gcc internals manual also<br />
covers RTL which is used frequently with assembly language in the kernel.<br />
<br />
<br />
== Printing kernel messages ==<br />
<br />
Kernel developers like to be seen as literate. Do mind the spelling<br />
of kernel messages to make a good impression. Do not use crippled<br />
words like &quot;dont&quot;; use &quot;do not&quot; or &quot;don't&quot; instead. Make the messages<br />
concise, clear, and unambiguous.<br />
<br />
Kernel messages do not have to be terminated with a period.<br />
<br />
Printing numbers in parentheses (%d) adds no value and should be avoided.<br />
<br />
There are a number of driver model diagnostic macros in &lt;linux/device.h&gt;<br />
which you should use to make sure messages are matched to the right device<br />
and driver, and are tagged with the right level: dev_err(), dev_warn(),<br />
dev_info(), and so forth. For messages that aren't associated with a<br />
particular device, &lt;linux/printk.h&gt; defines pr_debug() and pr_info().<br />
<br />
Coming up with good debugging messages can be quite a challenge; and once<br />
you have them, they can be a huge help for remote troubleshooting. Such<br />
messages should be compiled out when the DEBUG symbol is not defined (that<br />
is, by default they are not included). When you use dev_dbg() or pr_debug(),<br />
that's automatic. Many subsystems have Kconfig options to turn on -DDEBUG.<br />
A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to the<br />
ones already enabled by DEBUG.<br />
<br />
<br />
== Allocating memory ==<br />
<br />
The kernel provides the following general purpose memory allocators:<br />
kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and<br />
vzalloc(). Please refer to the API documentation for further information<br />
about them.<br />
<br />
The preferred form for passing a size of a struct is the following:<br />
<br />
p = kmalloc(sizeof(*p), ...);<br />
<br />
The alternative form where struct name is spelled out hurts readability and<br />
introduces an opportunity for a bug when the pointer variable type is changed<br />
but the corresponding sizeof that is passed to a memory allocator is not.<br />
<br />
Casting the return value which is a void pointer is redundant. The conversion<br />
from void pointer to any other pointer type is guaranteed by the C programming<br />
language.<br />
<br />
The preferred form for allocating an array is the following:<br />
<br />
p = kmalloc_array(n, sizeof(...), ...);<br />
<br />
The preferred form for allocating a zeroed array is the following:<br />
<br />
p = kcalloc(n, sizeof(...), ...);<br />
<br />
Both forms check for overflow on the allocation size n * sizeof(...),<br />
and return NULL if that occurred.<br />
<br />
<br />
== The inline disease ==<br />
<br />
There appears to be a common misperception that gcc has a magic &quot;make me<br />
faster&quot; speedup option called &quot;inline&quot;. While the use of inlines can be<br />
appropriate (for example as a means of replacing macros, see Chapter 12), it<br />
very often is not. Abundant use of the inline keyword leads to a much bigger<br />
kernel, which in turn slows the system as a whole down, due to a bigger<br />
icache footprint for the CPU and simply because there is less memory<br />
available for the pagecache. Just think about it; a pagecache miss causes a<br />
disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles<br />
that can go into these 5 milliseconds.<br />
<br />
A reasonable rule of thumb is to not put inline at functions that have more<br />
than 3 lines of code in them. An exception to this rule are the cases where<br />
a parameter is known to be a compiletime constant, and as a result of this<br />
constantness you *know* the compiler will be able to optimize most of your<br />
function away at compile time. For a good example of this later case, see<br />
the kmalloc() inline function.<br />
<br />
Often people argue that adding inline to functions that are static and used<br />
only once is always a win since there is no space tradeoff. While this is<br />
technically correct, gcc is capable of inlining these automatically without<br />
help, and the maintenance issue of removing the inline when a second user<br />
appears outweighs the potential value of the hint that tells gcc to do<br />
something it would have done anyway.<br />
<br />
<br />
== Function return values and names ==<br />
<br />
Functions can return values of many different kinds, and one of the<br />
most common is a value indicating whether the function succeeded or<br />
failed. Such a value can be represented as an error-code integer<br />
(-Exxx = failure, 0 = success) or a &quot;succeeded&quot; boolean (0 = failure,<br />
non-zero = success).<br />
<br />
Mixing up these two sorts of representations is a fertile source of<br />
difficult-to-find bugs. If the C language included a strong distinction<br />
between integers and booleans then the compiler would find these mistakes<br />
for us... but it doesn't. To help prevent such bugs, always follow this<br />
convention:<br />
<br />
If the name of a function is an action or an imperative command,<br />
the function should return an error-code integer. If the name<br />
is a predicate, the function should return a &quot;succeeded&quot; boolean.<br />
<br />
For example, &quot;add work&quot; is a command, and the add_work() function returns 0<br />
for success or -EBUSY for failure. In the same way, &quot;PCI device present&quot; is<br />
a predicate, and the pci_dev_present() function returns 1 if it succeeds in<br />
finding a matching device or 0 if it doesn't.<br />
<br />
All EXPORTed functions must respect this convention, and so should all<br />
public functions. Private (static) functions need not, but it is<br />
recommended that they do.<br />
<br />
Functions whose return value is the actual result of a computation, rather<br />
than an indication of whether the computation succeeded, are not subject to<br />
this rule. Generally they indicate failure by returning some out-of-range<br />
result. Typical examples would be functions that return pointers; they use<br />
NULL or the ERR_PTR mechanism to report failure.<br />
<br />
<br />
== Don't re-invent the kernel macros ==<br />
<br />
The header file include/linux/kernel.h contains a number of macros that<br />
you should use, rather than explicitly coding some variant of them yourself.<br />
For example, if you need to calculate the length of an array, take advantage<br />
of the macro<br />
<br />
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))<br />
<br />
Similarly, if you need to calculate the size of some structure member, use<br />
<br />
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)-&gt;f))<br />
<br />
There are also min() and max() macros that do strict type checking if you<br />
need them. Feel free to peruse that header file to see what else is already<br />
defined that you shouldn't reproduce in your code.<br />
<br />
<br />
== Editor modelines and other cruft ==<br />
<br />
Some editors can interpret configuration information embedded in source files,<br />
indicated with special markers. For example, emacs interprets lines marked<br />
like this:<br />
<br />
-*- mode: c -*-<br />
<br />
Or like this:<br />
<br />
/*<br />
Local Variables:<br />
compile-command: &quot;gcc -DMAGIC_DEBUG_FLAG foo.c&quot;<br />
End:<br />
*/<br />
<br />
Vim interprets markers that look like this:<br />
<br />
/* vim:set sw=8 noet */<br />
<br />
Do not include any of these in source files. People have their own personal<br />
editor configurations, and your source files should not override them. This<br />
includes markers for indentation and mode configuration. People may use their<br />
own custom mode, or may have some other magic method for making indentation<br />
work correctly.<br />
<br />
<br />
== Inline assembly ==<br />
<br />
In architecture-specific code, you may need to use inline assembly to interface<br />
with CPU or platform functionality. Don't hesitate to do so when necessary.<br />
However, don't use inline assembly gratuitously when C can do the job. You can<br />
and should poke hardware from C when possible.<br />
<br />
Consider writing simple helper functions that wrap common bits of inline<br />
assembly, rather than repeatedly writing them with slight variations. Remember<br />
that inline assembly can use C parameters.<br />
<br />
Large, non-trivial assembly functions should go in .S files, with corresponding<br />
C prototypes defined in C header files. The C prototypes for assembly<br />
functions should use &quot;asmlinkage&quot;.<br />
<br />
You may need to mark your asm statement as volatile, to prevent GCC from<br />
removing it if GCC doesn't notice any side effects. You don't always need to<br />
do so, though, and doing so unnecessarily can limit optimization.<br />
<br />
When writing a single inline assembly statement containing multiple<br />
instructions, put each instruction on a separate line in a separate quoted<br />
string, and end each string except the last with \n\t to properly indent the<br />
next instruction in the assembly output:<br />
<br />
asm (&quot;magic %reg1, #42\n\t&quot;<br />
&quot;more_magic %reg2, %reg3&quot;<br />
: /* outputs */ : /* inputs */ : /* clobbers */);<br />
<br />
<br />
<br />
== References ==<br />
<br />
The C Programming Language, Second Edition<br />
by Brian W. Kernighan and Dennis M. Ritchie.<br />
Prentice Hall, Inc., 1988.<br />
ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).<br />
URL: http://cm.bell-labs.com/cm/cs/cbook/<br />
<br />
The Practice of Programming<br />
by Brian W. Kernighan and Rob Pike.<br />
Addison-Wesley, Inc., 1999.<br />
ISBN 0-201-61586-X.<br />
URL: http://cm.bell-labs.com/cm/cs/tpop/<br />
<br />
GNU manuals - where in compliance with K&amp;R and this text - for cpp, gcc,<br />
gcc internals and indent, all available from http://www.gnu.org/manual/<br />
<br />
WG14 is the international standardization working group for the programming<br />
language C, URL: http://www.open-std.org/JTC1/SC22/WG14/<br />
<br />
Kernel CodingStyle, by greg@kroah.com at OLS 2002:<br />
http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/</div>Stepanhttp://www.coreboot.org/index.php?title=Coding_Style&diff=12305Coding Style2013-12-05T18:43:02Z<p>Stepan: /* Indentation */</p>
<hr />
<div>This is a short document describing the preferred coding style for the<br />
coreboot project. It is in many ways exactly the same as the Linux kernel<br />
coding style. In fact, most of this document has been copied from the<br />
[http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/Documentation/CodingStyle?id=HEAD Linux kernel coding style]<br />
<br />
Please at least consider the points made here.<br />
<br />
First off, I'd suggest printing out a copy of the GNU coding standards,<br />
and NOT read it. Burn them, it's a great symbolic gesture.<br />
<br />
Anyway, here goes:<br />
<br />
<br />
== Indentation ==<br />
<br />
Tabs are 8 characters, and thus indentations are also 8 characters.<br />
There are heretic movements that try to make indentations 4 (or even 2!)<br />
characters deep, and that is akin to trying to define the value of PI to<br />
be 3.<br />
<br />
Rationale: The whole idea behind indentation is to clearly define where<br />
a block of control starts and ends. Especially when you've been looking<br />
at your screen for 20 straight hours, you'll find it a lot easier to see<br />
how the indentation works if you have large indentations.<br />
<br />
Now, some people will claim that having 8-character indentations makes<br />
the code move too far to the right, and makes it hard to read on a<br />
80-character terminal screen. The answer to that is that if you need<br />
more than 3 levels of indentation, you're screwed anyway, and should fix<br />
your program.<br />
<br />
In short, 8-char indents make things easier to read, and have the added<br />
benefit of warning you when you're nesting your functions too deep.<br />
Heed that warning.<br />
<br />
The preferred way to ease multiple indentation levels in a switch statement is<br />
to align the &quot;switch&quot; and its subordinate &quot;case&quot; labels in the same column<br />
instead of &quot;double-indenting&quot; the &quot;case&quot; labels. E.g.:<br />
<br />
switch (suffix) {<br />
case 'G':<br />
case 'g':<br />
mem &lt;&lt;= 30;<br />
break;<br />
case 'M':<br />
case 'm':<br />
mem &lt;&lt;= 20;<br />
break;<br />
case 'K':<br />
case 'k':<br />
mem &lt;&lt;= 10;<br />
/* fall through */<br />
default:<br />
break;<br />
}<br />
<br />
<br />
Don't put multiple statements on a single line unless you have<br />
something to hide:<br />
<br />
if (condition) do_this;<br />
do_something_everytime;<br />
<br />
Don't put multiple assignments on a single line either. Kernel coding style<br />
is super simple. Avoid tricky expressions.<br />
<br />
Outside of comments, documentation and except in Kconfig, spaces are never<br />
used for indentation, and the above example is deliberately broken.<br />
<br />
Get a decent editor and don't leave whitespace at the end of lines.<br />
<br />
== Breaking long lines and strings ==<br />
<br />
Coding style is all about readability and maintainability using commonly<br />
available tools.<br />
<br />
The limit on the length of lines is 80 columns and this is a strongly<br />
preferred limit.<br />
<br />
Statements longer than 80 columns will be broken into sensible chunks, unless<br />
exceeding 80 columns significantly increases readability and does not hide<br />
information. Descendants are always substantially shorter than the parent and<br />
are placed substantially to the right. The same applies to function headers<br />
with a long argument list. However, never break user-visible strings such as<br />
printk messages, because that breaks the ability to grep for them.<br />
<br />
<br />
== Placing Braces and Spaces ==<br />
<br />
The other issue that always comes up in C styling is the placement of<br />
braces. Unlike the indent size, there are few technical reasons to<br />
choose one placement strategy over the other, but the preferred way, as<br />
shown to us by the prophets Kernighan and Ritchie, is to put the opening<br />
brace last on the line, and put the closing brace first, thusly:<br />
<br />
if (x is true) {<br />
we do y<br />
}<br />
<br />
This applies to all non-function statement blocks (if, switch, for,<br />
while, do). E.g.:<br />
<br />
switch (action) {<br />
case KOBJ_ADD:<br />
return &quot;add&quot;;<br />
case KOBJ_REMOVE:<br />
return &quot;remove&quot;;<br />
case KOBJ_CHANGE:<br />
return &quot;change&quot;;<br />
default:<br />
return NULL;<br />
}<br />
<br />
However, there is one special case, namely functions: they have the<br />
opening brace at the beginning of the next line, thus:<br />
<br />
int function(int x)<br />
{<br />
body of function<br />
}<br />
<br />
Heretic people all over the world have claimed that this inconsistency<br />
is ... well ... inconsistent, but all right-thinking people know that<br />
(a) K&amp;R are _right_ and (b) K&amp;R are right. Besides, functions are<br />
special anyway (you can't nest them in C).<br />
<br />
Note that the closing brace is empty on a line of its own, _except_ in<br />
the cases where it is followed by a continuation of the same statement,<br />
ie a &quot;while&quot; in a do-statement or an &quot;else&quot; in an if-statement, like<br />
this:<br />
<br />
do {<br />
body of do-loop<br />
} while (condition);<br />
<br />
and<br />
<br />
if (x == y) {<br />
..<br />
} else if (x &gt; y) {<br />
...<br />
} else {<br />
....<br />
}<br />
<br />
Rationale: K&amp;R.<br />
<br />
Also, note that this brace-placement also minimizes the number of empty<br />
(or almost empty) lines, without any loss of readability. Thus, as the<br />
supply of new-lines on your screen is not a renewable resource (think<br />
25-line terminal screens here), you have more empty lines to put<br />
comments on.<br />
<br />
Do not unnecessarily use braces where a single statement will do.<br />
<br />
if (condition)<br />
action();<br />
<br />
and<br />
<br />
if (condition)<br />
do_this();<br />
else<br />
do_that();<br />
<br />
This does not apply if only one branch of a conditional statement is a single<br />
statement; in the latter case use braces in both branches:<br />
<br />
if (condition) {<br />
do_this();<br />
do_that();<br />
} else {<br />
otherwise();<br />
}<br />
<br />
=== Spaces ===<br />
<br />
Linux kernel style for use of spaces depends (mostly) on<br />
function-versus-keyword usage. Use a space after (most) keywords. The<br />
notable exceptions are sizeof, typeof, alignof, and __attribute__, which look<br />
somewhat like functions (and are usually used with parentheses in Linux,<br />
although they are not required in the language, as in: &quot;sizeof info&quot; after<br />
&quot;struct fileinfo info;&quot; is declared).<br />
<br />
So use a space after these keywords:<br />
if, switch, case, for, do, while<br />
but not with sizeof, typeof, alignof, or __attribute__. E.g.,<br />
s = sizeof(struct file);<br />
<br />
Do not add spaces around (inside) parenthesized expressions. This example is<br />
*bad*:<br />
<br />
s = sizeof( struct file );<br />
<br />
When declaring pointer data or a function that returns a pointer type, the<br />
preferred use of '*' is adjacent to the data name or function name and not<br />
adjacent to the type name. Examples:<br />
<br />
char *linux_banner;<br />
unsigned long long memparse(char *ptr, char **retptr);<br />
char *match_strdup(substring_t *s);<br />
<br />
Use one space around (on each side of) most binary and ternary operators,<br />
such as any of these:<br />
<br />
= + - &lt; &gt; * / % | &amp; ^ &lt;= &gt;= == != ? :<br />
<br />
but no space after unary operators:<br />
&amp; * + - ~ ! sizeof typeof alignof __attribute__ defined<br />
<br />
no space before the postfix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
no space after the prefix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
and no space around the '.' and &quot;-&gt;&quot; structure member operators.<br />
<br />
Do not leave trailing whitespace at the ends of lines. Some editors with<br />
&quot;smart&quot; indentation will insert whitespace at the beginning of new lines as<br />
appropriate, so you can start typing the next line of code right away.<br />
However, some such editors do not remove the whitespace if you end up not<br />
putting a line of code there, such as if you leave a blank line. As a result,<br />
you end up with lines containing trailing whitespace.<br />
<br />
Git will warn you about patches that introduce trailing whitespace, and can<br />
optionally strip the trailing whitespace for you; however, if applying a series<br />
of patches, this may make later patches in the series fail by changing their<br />
context lines.<br />
<br />
<br />
== Naming ==<br />
<br />
C is a Spartan language, and so should your naming be. Unlike Modula-2<br />
and Pascal programmers, C programmers do not use cute names like<br />
ThisVariableIsATemporaryCounter. A C programmer would call that<br />
variable &quot;tmp&quot;, which is much easier to write, and not the least more<br />
difficult to understand.<br />
<br />
HOWEVER, while mixed-case names are frowned upon, descriptive names for<br />
global variables are a must. To call a global function &quot;foo&quot; is a<br />
shooting offense.<br />
<br />
GLOBAL variables (to be used only if you _really_ need them) need to<br />
have descriptive names, as do global functions. If you have a function<br />
that counts the number of active users, you should call that<br />
&quot;count_active_users()&quot; or similar, you should _not_ call it &quot;cntusr()&quot;.<br />
<br />
Encoding the type of a function into the name (so-called Hungarian<br />
notation) is brain damaged - the compiler knows the types anyway and can<br />
check those, and it only confuses the programmer. No wonder MicroSoft<br />
makes buggy programs.<br />
<br />
LOCAL variable names should be short, and to the point. If you have<br />
some random integer loop counter, it should probably be called &quot;i&quot;.<br />
Calling it &quot;loop_counter&quot; is non-productive, if there is no chance of it<br />
being mis-understood. Similarly, &quot;tmp&quot; can be just about any type of<br />
variable that is used to hold a temporary value.<br />
<br />
If you are afraid to mix up your local variable names, you have another<br />
problem, which is called the function-growth-hormone-imbalance syndrome.<br />
See chapter 6 (Functions).<br />
<br />
<br />
== Typedefs ==<br />
<br />
Please don't use things like &quot;vps_t&quot;.<br />
<br />
It's a _mistake_ to use typedef for structures and pointers. When you see a<br />
<br />
vps_t a;<br />
<br />
in the source, what does it mean?<br />
<br />
In contrast, if it says<br />
<br />
struct virtual_container *a;<br />
<br />
you can actually tell what &quot;a&quot; is.<br />
<br />
Lots of people think that typedefs &quot;help readability&quot;. Not so. They are<br />
useful only for:<br />
<br />
(a) totally opaque objects (where the typedef is actively used to _hide_<br />
what the object is).<br />
<br />
Example: &quot;pte_t&quot; etc. opaque objects that you can only access using<br />
the proper accessor functions.<br />
<br />
NOTE! Opaqueness and &quot;accessor functions&quot; are not good in themselves.<br />
The reason we have them for things like pte_t etc. is that there<br />
really is absolutely _zero_ portably accessible information there.<br />
<br />
(b) Clear integer types, where the abstraction _helps_ avoid confusion<br />
whether it is &quot;int&quot; or &quot;long&quot;.<br />
<br />
u8/u16/u32 are perfectly fine typedefs, although they fit into<br />
category (d) better than here.<br />
<br />
NOTE! Again - there needs to be a _reason_ for this. If something is<br />
&quot;unsigned long&quot;, then there's no reason to do<br />
<br />
typedef unsigned long myflags_t;<br />
<br />
but if there is a clear reason for why it under certain circumstances<br />
might be an &quot;unsigned int&quot; and under other configurations might be<br />
&quot;unsigned long&quot;, then by all means go ahead and use a typedef.<br />
<br />
(c) when you use sparse to literally create a _new_ type for<br />
type-checking.<br />
<br />
(d) New types which are identical to standard C99 types, in certain<br />
exceptional circumstances.<br />
<br />
Although it would only take a short amount of time for the eyes and<br />
brain to become accustomed to the standard types like 'uint32_t',<br />
some people object to their use anyway.<br />
<br />
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their<br />
signed equivalents which are identical to standard types are<br />
permitted -- although they are not mandatory in new code of your<br />
own.<br />
<br />
When editing existing code which already uses one or the other set<br />
of types, you should conform to the existing choices in that code.<br />
<br />
(e) Types safe for use in userspace.<br />
<br />
In certain structures which are visible to userspace, we cannot<br />
require C99 types and cannot use the 'u32' form above. Thus, we<br />
use __u32 and similar types in all structures which are shared<br />
with userspace.<br />
<br />
Maybe there are other cases too, but the rule should basically be to NEVER<br />
EVER use a typedef unless you can clearly match one of those rules.<br />
<br />
In general, a pointer, or a struct that has elements that can reasonably<br />
be directly accessed should _never_ be a typedef.<br />
<br />
<br />
== Functions ==<br />
<br />
Functions should be short and sweet, and do just one thing. They should<br />
fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,<br />
as we all know), and do one thing and do that well.<br />
<br />
The maximum length of a function is inversely proportional to the<br />
complexity and indentation level of that function. So, if you have a<br />
conceptually simple function that is just one long (but simple)<br />
case-statement, where you have to do lots of small things for a lot of<br />
different cases, it's OK to have a longer function.<br />
<br />
However, if you have a complex function, and you suspect that a<br />
less-than-gifted first-year high-school student might not even<br />
understand what the function is all about, you should adhere to the<br />
maximum limits all the more closely. Use helper functions with<br />
descriptive names (you can ask the compiler to in-line them if you think<br />
it's performance-critical, and it will probably do a better job of it<br />
than you would have done).<br />
<br />
Another measure of the function is the number of local variables. They<br />
shouldn't exceed 5-10, or you're doing something wrong. Re-think the<br />
function, and split it into smaller pieces. A human brain can<br />
generally easily keep track of about 7 different things, anything more<br />
and it gets confused. You know you're brilliant, but maybe you'd like<br />
to understand what you did 2 weeks from now.<br />
<br />
In source files, separate functions with one blank line. If the function is<br />
exported, the EXPORT* macro for it should follow immediately after the closing<br />
function brace line. E.g.:<br />
<br />
int system_is_up(void)<br />
{<br />
return system_state == SYSTEM_RUNNING;<br />
}<br />
EXPORT_SYMBOL(system_is_up);<br />
<br />
In function prototypes, include parameter names with their data types.<br />
Although this is not required by the C language, it is preferred in Linux<br />
because it is a simple way to add valuable information for the reader.<br />
<br />
<br />
== Centralized exiting of functions ==<br />
<br />
Albeit deprecated by some people, the equivalent of the goto statement is<br />
used frequently by compilers in form of the unconditional jump instruction.<br />
<br />
The goto statement comes in handy when a function exits from multiple<br />
locations and some common work such as cleanup has to be done. If there is no<br />
cleanup needed then just return directly.<br />
<br />
The rationale is:<br />
<br />
- unconditional statements are easier to understand and follow<br />
- nesting is reduced<br />
- errors by not updating individual exit points when making<br />
modifications are prevented<br />
- saves the compiler work to optimize redundant code away ;)<br />
<br />
int fun(int a)<br />
{<br />
int result = 0;<br />
char *buffer = kmalloc(SIZE);<br />
<br />
if (buffer == NULL)<br />
return -ENOMEM;<br />
<br />
if (condition1) {<br />
while (loop1) {<br />
...<br />
}<br />
result = 1;<br />
goto out;<br />
}<br />
...<br />
out:<br />
kfree(buffer);<br />
return result;<br />
}<br />
<br />
== Commenting ==<br />
<br />
Comments are good, but there is also a danger of over-commenting. NEVER<br />
try to explain HOW your code works in a comment: it's much better to<br />
write the code so that the _working_ is obvious, and it's a waste of<br />
time to explain badly written code.<br />
<br />
Generally, you want your comments to tell WHAT your code does, not HOW.<br />
Also, try to avoid putting comments inside a function body: if the<br />
function is so complex that you need to separately comment parts of it,<br />
you should probably go back to chapter 6 for a while. You can make<br />
small comments to note or warn about something particularly clever (or<br />
ugly), but try to avoid excess. Instead, put the comments at the head<br />
of the function, telling people what it does, and possibly WHY it does<br />
it.<br />
<br />
When commenting the kernel API functions, please use the kernel-doc format.<br />
See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc<br />
for details.<br />
<br />
coreboot style for comments is the C89 &quot;/* ... */&quot; style.<br />
You may use C99-style &quot;// ...&quot; comments.<br />
<br />
The preferred style for long (multi-line) comments is:<br />
<br />
/*<br />
* This is the preferred style for multi-line<br />
* comments in the Linux kernel source code.<br />
* Please use it consistently.<br />
*<br />
* Description: A column of asterisks on the left side,<br />
* with beginning and ending almost-blank lines.<br />
*/<br />
<br />
For files in net/ and drivers/net/ the preferred style for long (multi-line)<br />
comments is a little different.<br />
<br />
/* The preferred comment style for files in net/ and drivers/net<br />
* looks like this.<br />
*<br />
* It is nearly the same as the generally preferred comment style,<br />
* but there is no initial almost-blank line.<br />
*/<br />
<br />
It's also important to comment data, whether they are basic types or derived<br />
types. To this end, use just one data declaration per line (no commas for<br />
multiple data declarations). This leaves you room for a small comment on each<br />
item, explaining its use.<br />
<br />
<br />
== You've made a mess of it ==<br />
<br />
That's OK, we all do. You've probably been told by your long-time Unix<br />
user helper that &quot;GNU emacs&quot; automatically formats the C sources for<br />
you, and you've noticed that yes, it does do that, but the defaults it<br />
uses are less than desirable (in fact, they are worse than random<br />
typing - an infinite number of monkeys typing into GNU emacs would never<br />
make a good program).<br />
<br />
So, you can either get rid of GNU emacs, or change it to use saner<br />
values. To do the latter, you can stick the following in your .emacs file:<br />
<br />
(defun c-lineup-arglist-tabs-only (ignored)<br />
&quot;Line up argument lists by tabs, not spaces&quot;<br />
(let* ((anchor (c-langelem-pos c-syntactic-element))<br />
(column (c-langelem-2nd-pos c-syntactic-element))<br />
(offset (- (1+ column) anchor))<br />
(steps (floor offset c-basic-offset)))<br />
(* (max steps 1)<br />
c-basic-offset)))<br />
<br />
(add-hook 'c-mode-common-hook<br />
(lambda ()<br />
;; Add kernel style<br />
(c-add-style<br />
&quot;linux-tabs-only&quot;<br />
'(&quot;linux&quot; (c-offsets-alist<br />
(arglist-cont-nonempty<br />
c-lineup-gcc-asm-reg<br />
c-lineup-arglist-tabs-only))))))<br />
<br />
(add-hook 'c-mode-hook<br />
(lambda ()<br />
(let ((filename (buffer-file-name)))<br />
;; Enable kernel mode for the appropriate files<br />
(when (and filename<br />
(string-match (expand-file-name &quot;~/src/linux-trees&quot;)<br />
filename))<br />
(setq indent-tabs-mode t)<br />
(c-set-style &quot;linux-tabs-only&quot;)))))<br />
<br />
This will make emacs go better with the kernel coding style for C<br />
files below ~/src/linux-trees.<br />
<br />
But even if you fail in getting emacs to do sane formatting, not<br />
everything is lost: use &quot;indent&quot;.<br />
<br />
Now, again, GNU indent has the same brain-dead settings that GNU emacs<br />
has, which is why you need to give it a few command line options.<br />
However, that's not too bad, because even the makers of GNU indent<br />
recognize the authority of K&amp;R (the GNU people aren't evil, they are<br />
just severely misguided in this matter), so you just give indent the<br />
options &quot;-kr -i8&quot; (stands for &quot;K&amp;R, 8 character indents&quot;), or use<br />
&quot;scripts/Lindent&quot;, which indents in the latest style.<br />
<br />
&quot;indent&quot; has a lot of options, and especially when it comes to comment<br />
re-formatting you may want to take a look at the man page. But<br />
remember: &quot;indent&quot; is not a fix for bad programming.<br />
<br />
<br />
== Kconfig configuration files ==<br />
<br />
For all of the Kconfig* configuration files throughout the source tree,<br />
the indentation is somewhat different. Lines under a &quot;config&quot; definition<br />
are indented with one tab, while help text is indented an additional two<br />
spaces. Example:<br />
<br />
config AUDIT<br />
bool &quot;Auditing support&quot;<br />
depends on NET<br />
help<br />
Enable auditing infrastructure that can be used with another<br />
kernel subsystem, such as SELinux (which requires this for<br />
logging of avc messages output). Does not do system-call<br />
auditing without CONFIG_AUDITSYSCALL.<br />
<br />
Seriously dangerous features (such as write support for certain<br />
filesystems) should advertise this prominently in their prompt string:<br />
<br />
config ADFS_FS_RW<br />
bool &quot;ADFS write support (DANGEROUS)&quot;<br />
depends on ADFS_FS<br />
...<br />
<br />
For full documentation on the configuration files, see the file<br />
Documentation/kbuild/kconfig-language.txt.<br />
<br />
<br />
== Data structures ==<br />
<br />
Data structures that have visibility outside the single-threaded<br />
environment they are created and destroyed in should always have<br />
reference counts. In the kernel, garbage collection doesn't exist (and<br />
outside the kernel garbage collection is slow and inefficient), which<br />
means that you absolutely _have_ to reference count all your uses.<br />
<br />
Reference counting means that you can avoid locking, and allows multiple<br />
users to have access to the data structure in parallel - and not having<br />
to worry about the structure suddenly going away from under them just<br />
because they slept or did something else for a while.<br />
<br />
Note that locking is _not_ a replacement for reference counting.<br />
Locking is used to keep data structures coherent, while reference<br />
counting is a memory management technique. Usually both are needed, and<br />
they are not to be confused with each other.<br />
<br />
Many data structures can indeed have two levels of reference counting,<br />
when there are users of different &quot;classes&quot;. The subclass count counts<br />
the number of subclass users, and decrements the global count just once<br />
when the subclass count goes to zero.<br />
<br />
Examples of this kind of &quot;multi-level-reference-counting&quot; can be found in<br />
memory management (&quot;struct mm_struct&quot;: mm_users and mm_count), and in<br />
filesystem code (&quot;struct super_block&quot;: s_count and s_active).<br />
<br />
Remember: if another thread can find your data structure, and you don't<br />
have a reference count on it, you almost certainly have a bug.<br />
<br />
<br />
== Macros, Enums and RTL ==<br />
<br />
Names of macros defining constants and labels in enums are capitalized.<br />
<br />
#define CONSTANT 0x12345<br />
<br />
Enums are preferred when defining several related constants.<br />
<br />
CAPITALIZED macro names are appreciated but macros resembling functions<br />
may be named in lower case.<br />
<br />
Generally, inline functions are preferable to macros resembling functions.<br />
<br />
Macros with multiple statements should be enclosed in a do - while block:<br />
<br />
#define macrofun(a, b, c) \<br />
do { \<br />
if (a == 5) \<br />
do_this(b, c); \<br />
} while (0)<br />
<br />
Things to avoid when using macros:<br />
<br />
1) macros that affect control flow:<br />
<br />
#define FOO(x) \<br />
do { \<br />
if (blah(x) &lt; 0) \<br />
return -EBUGGERED; \<br />
} while(0)<br />
<br />
is a _very_ bad idea. It looks like a function call but exits the &quot;calling&quot;<br />
function; don't break the internal parsers of those who will read the code.<br />
<br />
2) macros that depend on having a local variable with a magic name:<br />
<br />
#define FOO(val) bar(index, val)<br />
<br />
might look like a good thing, but it's confusing as hell when one reads the<br />
code and it's prone to breakage from seemingly innocent changes.<br />
<br />
3) macros with arguments that are used as l-values: FOO(x) = y; will<br />
bite you if somebody e.g. turns FOO into an inline function.<br />
<br />
4) forgetting about precedence: macros defining constants using expressions<br />
must enclose the expression in parentheses. Beware of similar issues with<br />
macros using parameters.<br />
<br />
#define CONSTANT 0x4000<br />
#define CONSTEXP (CONSTANT | 3)<br />
<br />
The cpp manual deals with macros exhaustively. The gcc internals manual also<br />
covers RTL which is used frequently with assembly language in the kernel.<br />
<br />
<br />
== Printing kernel messages ==<br />
<br />
Kernel developers like to be seen as literate. Do mind the spelling<br />
of kernel messages to make a good impression. Do not use crippled<br />
words like &quot;dont&quot;; use &quot;do not&quot; or &quot;don't&quot; instead. Make the messages<br />
concise, clear, and unambiguous.<br />
<br />
Kernel messages do not have to be terminated with a period.<br />
<br />
Printing numbers in parentheses (%d) adds no value and should be avoided.<br />
<br />
There are a number of driver model diagnostic macros in &lt;linux/device.h&gt;<br />
which you should use to make sure messages are matched to the right device<br />
and driver, and are tagged with the right level: dev_err(), dev_warn(),<br />
dev_info(), and so forth. For messages that aren't associated with a<br />
particular device, &lt;linux/printk.h&gt; defines pr_debug() and pr_info().<br />
<br />
Coming up with good debugging messages can be quite a challenge; and once<br />
you have them, they can be a huge help for remote troubleshooting. Such<br />
messages should be compiled out when the DEBUG symbol is not defined (that<br />
is, by default they are not included). When you use dev_dbg() or pr_debug(),<br />
that's automatic. Many subsystems have Kconfig options to turn on -DDEBUG.<br />
A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to the<br />
ones already enabled by DEBUG.<br />
<br />
<br />
== Allocating memory ==<br />
<br />
The kernel provides the following general purpose memory allocators:<br />
kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and<br />
vzalloc(). Please refer to the API documentation for further information<br />
about them.<br />
<br />
The preferred form for passing a size of a struct is the following:<br />
<br />
p = kmalloc(sizeof(*p), ...);<br />
<br />
The alternative form where struct name is spelled out hurts readability and<br />
introduces an opportunity for a bug when the pointer variable type is changed<br />
but the corresponding sizeof that is passed to a memory allocator is not.<br />
<br />
Casting the return value which is a void pointer is redundant. The conversion<br />
from void pointer to any other pointer type is guaranteed by the C programming<br />
language.<br />
<br />
The preferred form for allocating an array is the following:<br />
<br />
p = kmalloc_array(n, sizeof(...), ...);<br />
<br />
The preferred form for allocating a zeroed array is the following:<br />
<br />
p = kcalloc(n, sizeof(...), ...);<br />
<br />
Both forms check for overflow on the allocation size n * sizeof(...),<br />
and return NULL if that occurred.<br />
<br />
<br />
== The inline disease ==<br />
<br />
There appears to be a common misperception that gcc has a magic &quot;make me<br />
faster&quot; speedup option called &quot;inline&quot;. While the use of inlines can be<br />
appropriate (for example as a means of replacing macros, see Chapter 12), it<br />
very often is not. Abundant use of the inline keyword leads to a much bigger<br />
kernel, which in turn slows the system as a whole down, due to a bigger<br />
icache footprint for the CPU and simply because there is less memory<br />
available for the pagecache. Just think about it; a pagecache miss causes a<br />
disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles<br />
that can go into these 5 milliseconds.<br />
<br />
A reasonable rule of thumb is to not put inline at functions that have more<br />
than 3 lines of code in them. An exception to this rule are the cases where<br />
a parameter is known to be a compiletime constant, and as a result of this<br />
constantness you *know* the compiler will be able to optimize most of your<br />
function away at compile time. For a good example of this later case, see<br />
the kmalloc() inline function.<br />
<br />
Often people argue that adding inline to functions that are static and used<br />
only once is always a win since there is no space tradeoff. While this is<br />
technically correct, gcc is capable of inlining these automatically without<br />
help, and the maintenance issue of removing the inline when a second user<br />
appears outweighs the potential value of the hint that tells gcc to do<br />
something it would have done anyway.<br />
<br />
<br />
== Function return values and names ==<br />
<br />
Functions can return values of many different kinds, and one of the<br />
most common is a value indicating whether the function succeeded or<br />
failed. Such a value can be represented as an error-code integer<br />
(-Exxx = failure, 0 = success) or a &quot;succeeded&quot; boolean (0 = failure,<br />
non-zero = success).<br />
<br />
Mixing up these two sorts of representations is a fertile source of<br />
difficult-to-find bugs. If the C language included a strong distinction<br />
between integers and booleans then the compiler would find these mistakes<br />
for us... but it doesn't. To help prevent such bugs, always follow this<br />
convention:<br />
<br />
If the name of a function is an action or an imperative command,<br />
the function should return an error-code integer. If the name<br />
is a predicate, the function should return a &quot;succeeded&quot; boolean.<br />
<br />
For example, &quot;add work&quot; is a command, and the add_work() function returns 0<br />
for success or -EBUSY for failure. In the same way, &quot;PCI device present&quot; is<br />
a predicate, and the pci_dev_present() function returns 1 if it succeeds in<br />
finding a matching device or 0 if it doesn't.<br />
<br />
All EXPORTed functions must respect this convention, and so should all<br />
public functions. Private (static) functions need not, but it is<br />
recommended that they do.<br />
<br />
Functions whose return value is the actual result of a computation, rather<br />
than an indication of whether the computation succeeded, are not subject to<br />
this rule. Generally they indicate failure by returning some out-of-range<br />
result. Typical examples would be functions that return pointers; they use<br />
NULL or the ERR_PTR mechanism to report failure.<br />
<br />
<br />
== Don't re-invent the kernel macros ==<br />
<br />
The header file include/linux/kernel.h contains a number of macros that<br />
you should use, rather than explicitly coding some variant of them yourself.<br />
For example, if you need to calculate the length of an array, take advantage<br />
of the macro<br />
<br />
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))<br />
<br />
Similarly, if you need to calculate the size of some structure member, use<br />
<br />
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)-&gt;f))<br />
<br />
There are also min() and max() macros that do strict type checking if you<br />
need them. Feel free to peruse that header file to see what else is already<br />
defined that you shouldn't reproduce in your code.<br />
<br />
<br />
== Editor modelines and other cruft ==<br />
<br />
Some editors can interpret configuration information embedded in source files,<br />
indicated with special markers. For example, emacs interprets lines marked<br />
like this:<br />
<br />
-*- mode: c -*-<br />
<br />
Or like this:<br />
<br />
/*<br />
Local Variables:<br />
compile-command: &quot;gcc -DMAGIC_DEBUG_FLAG foo.c&quot;<br />
End:<br />
*/<br />
<br />
Vim interprets markers that look like this:<br />
<br />
/* vim:set sw=8 noet */<br />
<br />
Do not include any of these in source files. People have their own personal<br />
editor configurations, and your source files should not override them. This<br />
includes markers for indentation and mode configuration. People may use their<br />
own custom mode, or may have some other magic method for making indentation<br />
work correctly.<br />
<br />
<br />
== Inline assembly ==<br />
<br />
In architecture-specific code, you may need to use inline assembly to interface<br />
with CPU or platform functionality. Don't hesitate to do so when necessary.<br />
However, don't use inline assembly gratuitously when C can do the job. You can<br />
and should poke hardware from C when possible.<br />
<br />
Consider writing simple helper functions that wrap common bits of inline<br />
assembly, rather than repeatedly writing them with slight variations. Remember<br />
that inline assembly can use C parameters.<br />
<br />
Large, non-trivial assembly functions should go in .S files, with corresponding<br />
C prototypes defined in C header files. The C prototypes for assembly<br />
functions should use &quot;asmlinkage&quot;.<br />
<br />
You may need to mark your asm statement as volatile, to prevent GCC from<br />
removing it if GCC doesn't notice any side effects. You don't always need to<br />
do so, though, and doing so unnecessarily can limit optimization.<br />
<br />
When writing a single inline assembly statement containing multiple<br />
instructions, put each instruction on a separate line in a separate quoted<br />
string, and end each string except the last with \n\t to properly indent the<br />
next instruction in the assembly output:<br />
<br />
asm (&quot;magic %reg1, #42\n\t&quot;<br />
&quot;more_magic %reg2, %reg3&quot;<br />
: /* outputs */ : /* inputs */ : /* clobbers */);<br />
<br />
<br />
<br />
== References ==<br />
<br />
The C Programming Language, Second Edition<br />
by Brian W. Kernighan and Dennis M. Ritchie.<br />
Prentice Hall, Inc., 1988.<br />
ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).<br />
URL: http://cm.bell-labs.com/cm/cs/cbook/<br />
<br />
The Practice of Programming<br />
by Brian W. Kernighan and Rob Pike.<br />
Addison-Wesley, Inc., 1999.<br />
ISBN 0-201-61586-X.<br />
URL: http://cm.bell-labs.com/cm/cs/tpop/<br />
<br />
GNU manuals - where in compliance with K&amp;R and this text - for cpp, gcc,<br />
gcc internals and indent, all available from http://www.gnu.org/manual/<br />
<br />
WG14 is the international standardization working group for the programming<br />
language C, URL: http://www.open-std.org/JTC1/SC22/WG14/<br />
<br />
Kernel CodingStyle, by greg@kroah.com at OLS 2002:<br />
http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/</div>Stepanhttp://www.coreboot.org/index.php?title=Coding_Style&diff=12304Coding Style2013-12-05T18:42:18Z<p>Stepan: </p>
<hr />
<div>This is a short document describing the preferred coding style for the<br />
coreboot project. It is in many ways exactly the same as the Linux kernel<br />
coding style. In fact, most of this document has been copied from the<br />
[http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/Documentation/CodingStyle?id=HEAD Linux kernel coding style]<br />
<br />
Please at least consider the points made here.<br />
<br />
First off, I'd suggest printing out a copy of the GNU coding standards,<br />
and NOT read it. Burn them, it's a great symbolic gesture.<br />
<br />
Anyway, here goes:<br />
<br />
<br />
== Indentation ==<br />
<br />
Tabs are 8 characters, and thus indentations are also 8 characters.<br />
There are heretic movements that try to make indentations 4 (or even 2!)<br />
characters deep, and that is akin to trying to define the value of PI to<br />
be 3.<br />
<br />
Rationale: The whole idea behind indentation is to clearly define where<br />
a block of control starts and ends. Especially when you've been looking<br />
at your screen for 20 straight hours, you'll find it a lot easier to see<br />
how the indentation works if you have large indentations.<br />
<br />
Now, some people will claim that having 8-character indentations makes<br />
the code move too far to the right, and makes it hard to read on a<br />
80-character terminal screen. The answer to that is that if you need<br />
more than 3 levels of indentation, you're screwed anyway, and should fix<br />
your program.<br />
<br />
In short, 8-char indents make things easier to read, and have the added<br />
benefit of warning you when you're nesting your functions too deep.<br />
Heed that warning.<br />
<br />
The preferred way to ease multiple indentation levels in a switch statement is<br />
to align the &quot;switch&quot; and its subordinate &quot;case&quot; labels in the same column<br />
instead of &quot;double-indenting&quot; the &quot;case&quot; labels. E.g.:<br />
<br />
switch (suffix) {<br />
case 'G':<br />
case 'g':<br />
mem &lt;&lt;= 30;<br />
break;<br />
case 'M':<br />
case 'm':<br />
mem &lt;&lt;= 20;<br />
break;<br />
case 'K':<br />
case 'k':<br />
mem &lt;&lt;= 10;<br />
/* fall through */<br />
default:<br />
break;<br />
}<br />
<br />
<br />
Don't put multiple statements on a single line unless you have<br />
something to hide:<br />
<br />
if (condition) do_this;<br />
do_something_everytime;<br />
<br />
Don't put multiple assignments on a single line either. Kernel coding style<br />
is super simple. Avoid tricky expressions.<br />
<br />
Outside of comments, documentation and except in Kconfig, spaces are never<br />
used for indentation, and the above example is deliberately broken.<br />
<br />
Get a decent editor and don't leave whitespace at the end of lines.<br />
<br />
<br />
== Breaking long lines and strings ==<br />
<br />
Coding style is all about readability and maintainability using commonly<br />
available tools.<br />
<br />
The limit on the length of lines is 80 columns and this is a strongly<br />
preferred limit.<br />
<br />
Statements longer than 80 columns will be broken into sensible chunks, unless<br />
exceeding 80 columns significantly increases readability and does not hide<br />
information. Descendants are always substantially shorter than the parent and<br />
are placed substantially to the right. The same applies to function headers<br />
with a long argument list. However, never break user-visible strings such as<br />
printk messages, because that breaks the ability to grep for them.<br />
<br />
<br />
== Placing Braces and Spaces ==<br />
<br />
The other issue that always comes up in C styling is the placement of<br />
braces. Unlike the indent size, there are few technical reasons to<br />
choose one placement strategy over the other, but the preferred way, as<br />
shown to us by the prophets Kernighan and Ritchie, is to put the opening<br />
brace last on the line, and put the closing brace first, thusly:<br />
<br />
if (x is true) {<br />
we do y<br />
}<br />
<br />
This applies to all non-function statement blocks (if, switch, for,<br />
while, do). E.g.:<br />
<br />
switch (action) {<br />
case KOBJ_ADD:<br />
return &quot;add&quot;;<br />
case KOBJ_REMOVE:<br />
return &quot;remove&quot;;<br />
case KOBJ_CHANGE:<br />
return &quot;change&quot;;<br />
default:<br />
return NULL;<br />
}<br />
<br />
However, there is one special case, namely functions: they have the<br />
opening brace at the beginning of the next line, thus:<br />
<br />
int function(int x)<br />
{<br />
body of function<br />
}<br />
<br />
Heretic people all over the world have claimed that this inconsistency<br />
is ... well ... inconsistent, but all right-thinking people know that<br />
(a) K&amp;R are _right_ and (b) K&amp;R are right. Besides, functions are<br />
special anyway (you can't nest them in C).<br />
<br />
Note that the closing brace is empty on a line of its own, _except_ in<br />
the cases where it is followed by a continuation of the same statement,<br />
ie a &quot;while&quot; in a do-statement or an &quot;else&quot; in an if-statement, like<br />
this:<br />
<br />
do {<br />
body of do-loop<br />
} while (condition);<br />
<br />
and<br />
<br />
if (x == y) {<br />
..<br />
} else if (x &gt; y) {<br />
...<br />
} else {<br />
....<br />
}<br />
<br />
Rationale: K&amp;R.<br />
<br />
Also, note that this brace-placement also minimizes the number of empty<br />
(or almost empty) lines, without any loss of readability. Thus, as the<br />
supply of new-lines on your screen is not a renewable resource (think<br />
25-line terminal screens here), you have more empty lines to put<br />
comments on.<br />
<br />
Do not unnecessarily use braces where a single statement will do.<br />
<br />
if (condition)<br />
action();<br />
<br />
and<br />
<br />
if (condition)<br />
do_this();<br />
else<br />
do_that();<br />
<br />
This does not apply if only one branch of a conditional statement is a single<br />
statement; in the latter case use braces in both branches:<br />
<br />
if (condition) {<br />
do_this();<br />
do_that();<br />
} else {<br />
otherwise();<br />
}<br />
<br />
=== Spaces ===<br />
<br />
Linux kernel style for use of spaces depends (mostly) on<br />
function-versus-keyword usage. Use a space after (most) keywords. The<br />
notable exceptions are sizeof, typeof, alignof, and __attribute__, which look<br />
somewhat like functions (and are usually used with parentheses in Linux,<br />
although they are not required in the language, as in: &quot;sizeof info&quot; after<br />
&quot;struct fileinfo info;&quot; is declared).<br />
<br />
So use a space after these keywords:<br />
if, switch, case, for, do, while<br />
but not with sizeof, typeof, alignof, or __attribute__. E.g.,<br />
s = sizeof(struct file);<br />
<br />
Do not add spaces around (inside) parenthesized expressions. This example is<br />
*bad*:<br />
<br />
s = sizeof( struct file );<br />
<br />
When declaring pointer data or a function that returns a pointer type, the<br />
preferred use of '*' is adjacent to the data name or function name and not<br />
adjacent to the type name. Examples:<br />
<br />
char *linux_banner;<br />
unsigned long long memparse(char *ptr, char **retptr);<br />
char *match_strdup(substring_t *s);<br />
<br />
Use one space around (on each side of) most binary and ternary operators,<br />
such as any of these:<br />
<br />
= + - &lt; &gt; * / % | &amp; ^ &lt;= &gt;= == != ? :<br />
<br />
but no space after unary operators:<br />
&amp; * + - ~ ! sizeof typeof alignof __attribute__ defined<br />
<br />
no space before the postfix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
no space after the prefix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
and no space around the '.' and &quot;-&gt;&quot; structure member operators.<br />
<br />
Do not leave trailing whitespace at the ends of lines. Some editors with<br />
&quot;smart&quot; indentation will insert whitespace at the beginning of new lines as<br />
appropriate, so you can start typing the next line of code right away.<br />
However, some such editors do not remove the whitespace if you end up not<br />
putting a line of code there, such as if you leave a blank line. As a result,<br />
you end up with lines containing trailing whitespace.<br />
<br />
Git will warn you about patches that introduce trailing whitespace, and can<br />
optionally strip the trailing whitespace for you; however, if applying a series<br />
of patches, this may make later patches in the series fail by changing their<br />
context lines.<br />
<br />
<br />
== Naming ==<br />
<br />
C is a Spartan language, and so should your naming be. Unlike Modula-2<br />
and Pascal programmers, C programmers do not use cute names like<br />
ThisVariableIsATemporaryCounter. A C programmer would call that<br />
variable &quot;tmp&quot;, which is much easier to write, and not the least more<br />
difficult to understand.<br />
<br />
HOWEVER, while mixed-case names are frowned upon, descriptive names for<br />
global variables are a must. To call a global function &quot;foo&quot; is a<br />
shooting offense.<br />
<br />
GLOBAL variables (to be used only if you _really_ need them) need to<br />
have descriptive names, as do global functions. If you have a function<br />
that counts the number of active users, you should call that<br />
&quot;count_active_users()&quot; or similar, you should _not_ call it &quot;cntusr()&quot;.<br />
<br />
Encoding the type of a function into the name (so-called Hungarian<br />
notation) is brain damaged - the compiler knows the types anyway and can<br />
check those, and it only confuses the programmer. No wonder MicroSoft<br />
makes buggy programs.<br />
<br />
LOCAL variable names should be short, and to the point. If you have<br />
some random integer loop counter, it should probably be called &quot;i&quot;.<br />
Calling it &quot;loop_counter&quot; is non-productive, if there is no chance of it<br />
being mis-understood. Similarly, &quot;tmp&quot; can be just about any type of<br />
variable that is used to hold a temporary value.<br />
<br />
If you are afraid to mix up your local variable names, you have another<br />
problem, which is called the function-growth-hormone-imbalance syndrome.<br />
See chapter 6 (Functions).<br />
<br />
<br />
== Typedefs ==<br />
<br />
Please don't use things like &quot;vps_t&quot;.<br />
<br />
It's a _mistake_ to use typedef for structures and pointers. When you see a<br />
<br />
vps_t a;<br />
<br />
in the source, what does it mean?<br />
<br />
In contrast, if it says<br />
<br />
struct virtual_container *a;<br />
<br />
you can actually tell what &quot;a&quot; is.<br />
<br />
Lots of people think that typedefs &quot;help readability&quot;. Not so. They are<br />
useful only for:<br />
<br />
(a) totally opaque objects (where the typedef is actively used to _hide_<br />
what the object is).<br />
<br />
Example: &quot;pte_t&quot; etc. opaque objects that you can only access using<br />
the proper accessor functions.<br />
<br />
NOTE! Opaqueness and &quot;accessor functions&quot; are not good in themselves.<br />
The reason we have them for things like pte_t etc. is that there<br />
really is absolutely _zero_ portably accessible information there.<br />
<br />
(b) Clear integer types, where the abstraction _helps_ avoid confusion<br />
whether it is &quot;int&quot; or &quot;long&quot;.<br />
<br />
u8/u16/u32 are perfectly fine typedefs, although they fit into<br />
category (d) better than here.<br />
<br />
NOTE! Again - there needs to be a _reason_ for this. If something is<br />
&quot;unsigned long&quot;, then there's no reason to do<br />
<br />
typedef unsigned long myflags_t;<br />
<br />
but if there is a clear reason for why it under certain circumstances<br />
might be an &quot;unsigned int&quot; and under other configurations might be<br />
&quot;unsigned long&quot;, then by all means go ahead and use a typedef.<br />
<br />
(c) when you use sparse to literally create a _new_ type for<br />
type-checking.<br />
<br />
(d) New types which are identical to standard C99 types, in certain<br />
exceptional circumstances.<br />
<br />
Although it would only take a short amount of time for the eyes and<br />
brain to become accustomed to the standard types like 'uint32_t',<br />
some people object to their use anyway.<br />
<br />
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their<br />
signed equivalents which are identical to standard types are<br />
permitted -- although they are not mandatory in new code of your<br />
own.<br />
<br />
When editing existing code which already uses one or the other set<br />
of types, you should conform to the existing choices in that code.<br />
<br />
(e) Types safe for use in userspace.<br />
<br />
In certain structures which are visible to userspace, we cannot<br />
require C99 types and cannot use the 'u32' form above. Thus, we<br />
use __u32 and similar types in all structures which are shared<br />
with userspace.<br />
<br />
Maybe there are other cases too, but the rule should basically be to NEVER<br />
EVER use a typedef unless you can clearly match one of those rules.<br />
<br />
In general, a pointer, or a struct that has elements that can reasonably<br />
be directly accessed should _never_ be a typedef.<br />
<br />
<br />
== Functions ==<br />
<br />
Functions should be short and sweet, and do just one thing. They should<br />
fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,<br />
as we all know), and do one thing and do that well.<br />
<br />
The maximum length of a function is inversely proportional to the<br />
complexity and indentation level of that function. So, if you have a<br />
conceptually simple function that is just one long (but simple)<br />
case-statement, where you have to do lots of small things for a lot of<br />
different cases, it's OK to have a longer function.<br />
<br />
However, if you have a complex function, and you suspect that a<br />
less-than-gifted first-year high-school student might not even<br />
understand what the function is all about, you should adhere to the<br />
maximum limits all the more closely. Use helper functions with<br />
descriptive names (you can ask the compiler to in-line them if you think<br />
it's performance-critical, and it will probably do a better job of it<br />
than you would have done).<br />
<br />
Another measure of the function is the number of local variables. They<br />
shouldn't exceed 5-10, or you're doing something wrong. Re-think the<br />
function, and split it into smaller pieces. A human brain can<br />
generally easily keep track of about 7 different things, anything more<br />
and it gets confused. You know you're brilliant, but maybe you'd like<br />
to understand what you did 2 weeks from now.<br />
<br />
In source files, separate functions with one blank line. If the function is<br />
exported, the EXPORT* macro for it should follow immediately after the closing<br />
function brace line. E.g.:<br />
<br />
int system_is_up(void)<br />
{<br />
return system_state == SYSTEM_RUNNING;<br />
}<br />
EXPORT_SYMBOL(system_is_up);<br />
<br />
In function prototypes, include parameter names with their data types.<br />
Although this is not required by the C language, it is preferred in Linux<br />
because it is a simple way to add valuable information for the reader.<br />
<br />
<br />
== Centralized exiting of functions ==<br />
<br />
Albeit deprecated by some people, the equivalent of the goto statement is<br />
used frequently by compilers in form of the unconditional jump instruction.<br />
<br />
The goto statement comes in handy when a function exits from multiple<br />
locations and some common work such as cleanup has to be done. If there is no<br />
cleanup needed then just return directly.<br />
<br />
The rationale is:<br />
<br />
- unconditional statements are easier to understand and follow<br />
- nesting is reduced<br />
- errors by not updating individual exit points when making<br />
modifications are prevented<br />
- saves the compiler work to optimize redundant code away ;)<br />
<br />
int fun(int a)<br />
{<br />
int result = 0;<br />
char *buffer = kmalloc(SIZE);<br />
<br />
if (buffer == NULL)<br />
return -ENOMEM;<br />
<br />
if (condition1) {<br />
while (loop1) {<br />
...<br />
}<br />
result = 1;<br />
goto out;<br />
}<br />
...<br />
out:<br />
kfree(buffer);<br />
return result;<br />
}<br />
<br />
== Commenting ==<br />
<br />
Comments are good, but there is also a danger of over-commenting. NEVER<br />
try to explain HOW your code works in a comment: it's much better to<br />
write the code so that the _working_ is obvious, and it's a waste of<br />
time to explain badly written code.<br />
<br />
Generally, you want your comments to tell WHAT your code does, not HOW.<br />
Also, try to avoid putting comments inside a function body: if the<br />
function is so complex that you need to separately comment parts of it,<br />
you should probably go back to chapter 6 for a while. You can make<br />
small comments to note or warn about something particularly clever (or<br />
ugly), but try to avoid excess. Instead, put the comments at the head<br />
of the function, telling people what it does, and possibly WHY it does<br />
it.<br />
<br />
When commenting the kernel API functions, please use the kernel-doc format.<br />
See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc<br />
for details.<br />
<br />
coreboot style for comments is the C89 &quot;/* ... */&quot; style.<br />
You may use C99-style &quot;// ...&quot; comments.<br />
<br />
The preferred style for long (multi-line) comments is:<br />
<br />
/*<br />
* This is the preferred style for multi-line<br />
* comments in the Linux kernel source code.<br />
* Please use it consistently.<br />
*<br />
* Description: A column of asterisks on the left side,<br />
* with beginning and ending almost-blank lines.<br />
*/<br />
<br />
For files in net/ and drivers/net/ the preferred style for long (multi-line)<br />
comments is a little different.<br />
<br />
/* The preferred comment style for files in net/ and drivers/net<br />
* looks like this.<br />
*<br />
* It is nearly the same as the generally preferred comment style,<br />
* but there is no initial almost-blank line.<br />
*/<br />
<br />
It's also important to comment data, whether they are basic types or derived<br />
types. To this end, use just one data declaration per line (no commas for<br />
multiple data declarations). This leaves you room for a small comment on each<br />
item, explaining its use.<br />
<br />
<br />
== You've made a mess of it ==<br />
<br />
That's OK, we all do. You've probably been told by your long-time Unix<br />
user helper that &quot;GNU emacs&quot; automatically formats the C sources for<br />
you, and you've noticed that yes, it does do that, but the defaults it<br />
uses are less than desirable (in fact, they are worse than random<br />
typing - an infinite number of monkeys typing into GNU emacs would never<br />
make a good program).<br />
<br />
So, you can either get rid of GNU emacs, or change it to use saner<br />
values. To do the latter, you can stick the following in your .emacs file:<br />
<br />
(defun c-lineup-arglist-tabs-only (ignored)<br />
&quot;Line up argument lists by tabs, not spaces&quot;<br />
(let* ((anchor (c-langelem-pos c-syntactic-element))<br />
(column (c-langelem-2nd-pos c-syntactic-element))<br />
(offset (- (1+ column) anchor))<br />
(steps (floor offset c-basic-offset)))<br />
(* (max steps 1)<br />
c-basic-offset)))<br />
<br />
(add-hook 'c-mode-common-hook<br />
(lambda ()<br />
;; Add kernel style<br />
(c-add-style<br />
&quot;linux-tabs-only&quot;<br />
'(&quot;linux&quot; (c-offsets-alist<br />
(arglist-cont-nonempty<br />
c-lineup-gcc-asm-reg<br />
c-lineup-arglist-tabs-only))))))<br />
<br />
(add-hook 'c-mode-hook<br />
(lambda ()<br />
(let ((filename (buffer-file-name)))<br />
;; Enable kernel mode for the appropriate files<br />
(when (and filename<br />
(string-match (expand-file-name &quot;~/src/linux-trees&quot;)<br />
filename))<br />
(setq indent-tabs-mode t)<br />
(c-set-style &quot;linux-tabs-only&quot;)))))<br />
<br />
This will make emacs go better with the kernel coding style for C<br />
files below ~/src/linux-trees.<br />
<br />
But even if you fail in getting emacs to do sane formatting, not<br />
everything is lost: use &quot;indent&quot;.<br />
<br />
Now, again, GNU indent has the same brain-dead settings that GNU emacs<br />
has, which is why you need to give it a few command line options.<br />
However, that's not too bad, because even the makers of GNU indent<br />
recognize the authority of K&amp;R (the GNU people aren't evil, they are<br />
just severely misguided in this matter), so you just give indent the<br />
options &quot;-kr -i8&quot; (stands for &quot;K&amp;R, 8 character indents&quot;), or use<br />
&quot;scripts/Lindent&quot;, which indents in the latest style.<br />
<br />
&quot;indent&quot; has a lot of options, and especially when it comes to comment<br />
re-formatting you may want to take a look at the man page. But<br />
remember: &quot;indent&quot; is not a fix for bad programming.<br />
<br />
<br />
== Kconfig configuration files ==<br />
<br />
For all of the Kconfig* configuration files throughout the source tree,<br />
the indentation is somewhat different. Lines under a &quot;config&quot; definition<br />
are indented with one tab, while help text is indented an additional two<br />
spaces. Example:<br />
<br />
config AUDIT<br />
bool &quot;Auditing support&quot;<br />
depends on NET<br />
help<br />
Enable auditing infrastructure that can be used with another<br />
kernel subsystem, such as SELinux (which requires this for<br />
logging of avc messages output). Does not do system-call<br />
auditing without CONFIG_AUDITSYSCALL.<br />
<br />
Seriously dangerous features (such as write support for certain<br />
filesystems) should advertise this prominently in their prompt string:<br />
<br />
config ADFS_FS_RW<br />
bool &quot;ADFS write support (DANGEROUS)&quot;<br />
depends on ADFS_FS<br />
...<br />
<br />
For full documentation on the configuration files, see the file<br />
Documentation/kbuild/kconfig-language.txt.<br />
<br />
<br />
== Data structures ==<br />
<br />
Data structures that have visibility outside the single-threaded<br />
environment they are created and destroyed in should always have<br />
reference counts. In the kernel, garbage collection doesn't exist (and<br />
outside the kernel garbage collection is slow and inefficient), which<br />
means that you absolutely _have_ to reference count all your uses.<br />
<br />
Reference counting means that you can avoid locking, and allows multiple<br />
users to have access to the data structure in parallel - and not having<br />
to worry about the structure suddenly going away from under them just<br />
because they slept or did something else for a while.<br />
<br />
Note that locking is _not_ a replacement for reference counting.<br />
Locking is used to keep data structures coherent, while reference<br />
counting is a memory management technique. Usually both are needed, and<br />
they are not to be confused with each other.<br />
<br />
Many data structures can indeed have two levels of reference counting,<br />
when there are users of different &quot;classes&quot;. The subclass count counts<br />
the number of subclass users, and decrements the global count just once<br />
when the subclass count goes to zero.<br />
<br />
Examples of this kind of &quot;multi-level-reference-counting&quot; can be found in<br />
memory management (&quot;struct mm_struct&quot;: mm_users and mm_count), and in<br />
filesystem code (&quot;struct super_block&quot;: s_count and s_active).<br />
<br />
Remember: if another thread can find your data structure, and you don't<br />
have a reference count on it, you almost certainly have a bug.<br />
<br />
<br />
== Macros, Enums and RTL ==<br />
<br />
Names of macros defining constants and labels in enums are capitalized.<br />
<br />
#define CONSTANT 0x12345<br />
<br />
Enums are preferred when defining several related constants.<br />
<br />
CAPITALIZED macro names are appreciated but macros resembling functions<br />
may be named in lower case.<br />
<br />
Generally, inline functions are preferable to macros resembling functions.<br />
<br />
Macros with multiple statements should be enclosed in a do - while block:<br />
<br />
#define macrofun(a, b, c) \<br />
do { \<br />
if (a == 5) \<br />
do_this(b, c); \<br />
} while (0)<br />
<br />
Things to avoid when using macros:<br />
<br />
1) macros that affect control flow:<br />
<br />
#define FOO(x) \<br />
do { \<br />
if (blah(x) &lt; 0) \<br />
return -EBUGGERED; \<br />
} while(0)<br />
<br />
is a _very_ bad idea. It looks like a function call but exits the &quot;calling&quot;<br />
function; don't break the internal parsers of those who will read the code.<br />
<br />
2) macros that depend on having a local variable with a magic name:<br />
<br />
#define FOO(val) bar(index, val)<br />
<br />
might look like a good thing, but it's confusing as hell when one reads the<br />
code and it's prone to breakage from seemingly innocent changes.<br />
<br />
3) macros with arguments that are used as l-values: FOO(x) = y; will<br />
bite you if somebody e.g. turns FOO into an inline function.<br />
<br />
4) forgetting about precedence: macros defining constants using expressions<br />
must enclose the expression in parentheses. Beware of similar issues with<br />
macros using parameters.<br />
<br />
#define CONSTANT 0x4000<br />
#define CONSTEXP (CONSTANT | 3)<br />
<br />
The cpp manual deals with macros exhaustively. The gcc internals manual also<br />
covers RTL which is used frequently with assembly language in the kernel.<br />
<br />
<br />
== Printing kernel messages ==<br />
<br />
Kernel developers like to be seen as literate. Do mind the spelling<br />
of kernel messages to make a good impression. Do not use crippled<br />
words like &quot;dont&quot;; use &quot;do not&quot; or &quot;don't&quot; instead. Make the messages<br />
concise, clear, and unambiguous.<br />
<br />
Kernel messages do not have to be terminated with a period.<br />
<br />
Printing numbers in parentheses (%d) adds no value and should be avoided.<br />
<br />
There are a number of driver model diagnostic macros in &lt;linux/device.h&gt;<br />
which you should use to make sure messages are matched to the right device<br />
and driver, and are tagged with the right level: dev_err(), dev_warn(),<br />
dev_info(), and so forth. For messages that aren't associated with a<br />
particular device, &lt;linux/printk.h&gt; defines pr_debug() and pr_info().<br />
<br />
Coming up with good debugging messages can be quite a challenge; and once<br />
you have them, they can be a huge help for remote troubleshooting. Such<br />
messages should be compiled out when the DEBUG symbol is not defined (that<br />
is, by default they are not included). When you use dev_dbg() or pr_debug(),<br />
that's automatic. Many subsystems have Kconfig options to turn on -DDEBUG.<br />
A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to the<br />
ones already enabled by DEBUG.<br />
<br />
<br />
== Allocating memory ==<br />
<br />
The kernel provides the following general purpose memory allocators:<br />
kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and<br />
vzalloc(). Please refer to the API documentation for further information<br />
about them.<br />
<br />
The preferred form for passing a size of a struct is the following:<br />
<br />
p = kmalloc(sizeof(*p), ...);<br />
<br />
The alternative form where struct name is spelled out hurts readability and<br />
introduces an opportunity for a bug when the pointer variable type is changed<br />
but the corresponding sizeof that is passed to a memory allocator is not.<br />
<br />
Casting the return value which is a void pointer is redundant. The conversion<br />
from void pointer to any other pointer type is guaranteed by the C programming<br />
language.<br />
<br />
The preferred form for allocating an array is the following:<br />
<br />
p = kmalloc_array(n, sizeof(...), ...);<br />
<br />
The preferred form for allocating a zeroed array is the following:<br />
<br />
p = kcalloc(n, sizeof(...), ...);<br />
<br />
Both forms check for overflow on the allocation size n * sizeof(...),<br />
and return NULL if that occurred.<br />
<br />
<br />
== The inline disease ==<br />
<br />
There appears to be a common misperception that gcc has a magic &quot;make me<br />
faster&quot; speedup option called &quot;inline&quot;. While the use of inlines can be<br />
appropriate (for example as a means of replacing macros, see Chapter 12), it<br />
very often is not. Abundant use of the inline keyword leads to a much bigger<br />
kernel, which in turn slows the system as a whole down, due to a bigger<br />
icache footprint for the CPU and simply because there is less memory<br />
available for the pagecache. Just think about it; a pagecache miss causes a<br />
disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles<br />
that can go into these 5 milliseconds.<br />
<br />
A reasonable rule of thumb is to not put inline at functions that have more<br />
than 3 lines of code in them. An exception to this rule are the cases where<br />
a parameter is known to be a compiletime constant, and as a result of this<br />
constantness you *know* the compiler will be able to optimize most of your<br />
function away at compile time. For a good example of this later case, see<br />
the kmalloc() inline function.<br />
<br />
Often people argue that adding inline to functions that are static and used<br />
only once is always a win since there is no space tradeoff. While this is<br />
technically correct, gcc is capable of inlining these automatically without<br />
help, and the maintenance issue of removing the inline when a second user<br />
appears outweighs the potential value of the hint that tells gcc to do<br />
something it would have done anyway.<br />
<br />
<br />
== Function return values and names ==<br />
<br />
Functions can return values of many different kinds, and one of the<br />
most common is a value indicating whether the function succeeded or<br />
failed. Such a value can be represented as an error-code integer<br />
(-Exxx = failure, 0 = success) or a &quot;succeeded&quot; boolean (0 = failure,<br />
non-zero = success).<br />
<br />
Mixing up these two sorts of representations is a fertile source of<br />
difficult-to-find bugs. If the C language included a strong distinction<br />
between integers and booleans then the compiler would find these mistakes<br />
for us... but it doesn't. To help prevent such bugs, always follow this<br />
convention:<br />
<br />
If the name of a function is an action or an imperative command,<br />
the function should return an error-code integer. If the name<br />
is a predicate, the function should return a &quot;succeeded&quot; boolean.<br />
<br />
For example, &quot;add work&quot; is a command, and the add_work() function returns 0<br />
for success or -EBUSY for failure. In the same way, &quot;PCI device present&quot; is<br />
a predicate, and the pci_dev_present() function returns 1 if it succeeds in<br />
finding a matching device or 0 if it doesn't.<br />
<br />
All EXPORTed functions must respect this convention, and so should all<br />
public functions. Private (static) functions need not, but it is<br />
recommended that they do.<br />
<br />
Functions whose return value is the actual result of a computation, rather<br />
than an indication of whether the computation succeeded, are not subject to<br />
this rule. Generally they indicate failure by returning some out-of-range<br />
result. Typical examples would be functions that return pointers; they use<br />
NULL or the ERR_PTR mechanism to report failure.<br />
<br />
<br />
== Don't re-invent the kernel macros ==<br />
<br />
The header file include/linux/kernel.h contains a number of macros that<br />
you should use, rather than explicitly coding some variant of them yourself.<br />
For example, if you need to calculate the length of an array, take advantage<br />
of the macro<br />
<br />
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))<br />
<br />
Similarly, if you need to calculate the size of some structure member, use<br />
<br />
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)-&gt;f))<br />
<br />
There are also min() and max() macros that do strict type checking if you<br />
need them. Feel free to peruse that header file to see what else is already<br />
defined that you shouldn't reproduce in your code.<br />
<br />
<br />
== Editor modelines and other cruft ==<br />
<br />
Some editors can interpret configuration information embedded in source files,<br />
indicated with special markers. For example, emacs interprets lines marked<br />
like this:<br />
<br />
-*- mode: c -*-<br />
<br />
Or like this:<br />
<br />
/*<br />
Local Variables:<br />
compile-command: &quot;gcc -DMAGIC_DEBUG_FLAG foo.c&quot;<br />
End:<br />
*/<br />
<br />
Vim interprets markers that look like this:<br />
<br />
/* vim:set sw=8 noet */<br />
<br />
Do not include any of these in source files. People have their own personal<br />
editor configurations, and your source files should not override them. This<br />
includes markers for indentation and mode configuration. People may use their<br />
own custom mode, or may have some other magic method for making indentation<br />
work correctly.<br />
<br />
<br />
== Inline assembly ==<br />
<br />
In architecture-specific code, you may need to use inline assembly to interface<br />
with CPU or platform functionality. Don't hesitate to do so when necessary.<br />
However, don't use inline assembly gratuitously when C can do the job. You can<br />
and should poke hardware from C when possible.<br />
<br />
Consider writing simple helper functions that wrap common bits of inline<br />
assembly, rather than repeatedly writing them with slight variations. Remember<br />
that inline assembly can use C parameters.<br />
<br />
Large, non-trivial assembly functions should go in .S files, with corresponding<br />
C prototypes defined in C header files. The C prototypes for assembly<br />
functions should use &quot;asmlinkage&quot;.<br />
<br />
You may need to mark your asm statement as volatile, to prevent GCC from<br />
removing it if GCC doesn't notice any side effects. You don't always need to<br />
do so, though, and doing so unnecessarily can limit optimization.<br />
<br />
When writing a single inline assembly statement containing multiple<br />
instructions, put each instruction on a separate line in a separate quoted<br />
string, and end each string except the last with \n\t to properly indent the<br />
next instruction in the assembly output:<br />
<br />
asm (&quot;magic %reg1, #42\n\t&quot;<br />
&quot;more_magic %reg2, %reg3&quot;<br />
: /* outputs */ : /* inputs */ : /* clobbers */);<br />
<br />
<br />
<br />
== References ==<br />
<br />
The C Programming Language, Second Edition<br />
by Brian W. Kernighan and Dennis M. Ritchie.<br />
Prentice Hall, Inc., 1988.<br />
ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).<br />
URL: http://cm.bell-labs.com/cm/cs/cbook/<br />
<br />
The Practice of Programming<br />
by Brian W. Kernighan and Rob Pike.<br />
Addison-Wesley, Inc., 1999.<br />
ISBN 0-201-61586-X.<br />
URL: http://cm.bell-labs.com/cm/cs/tpop/<br />
<br />
GNU manuals - where in compliance with K&amp;R and this text - for cpp, gcc,<br />
gcc internals and indent, all available from http://www.gnu.org/manual/<br />
<br />
WG14 is the international standardization working group for the programming<br />
language C, URL: http://www.open-std.org/JTC1/SC22/WG14/<br />
<br />
Kernel CodingStyle, by greg@kroah.com at OLS 2002:<br />
http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/</div>Stepanhttp://www.coreboot.org/index.php?title=Development_Guidelines&diff=12303Development Guidelines2013-12-05T18:41:34Z<p>Stepan: /* Coding Style */</p>
<hr />
<div>= Development Environment =<br />
<br />
== Required Toolchain ==<br />
<br />
The easiest way to get a working toolchain is to run &lt;code&gt;make crossgcc&lt;/code&gt; in the toplevel directory of a coreboot checkout. Linux distributions usually modify their compilers in ways incompatible with coreboot. If in doubt, use our toolchain.<br />
<br />
The toolchain consists of:<br />
* GNU development environment:<br />
** [http://gcc.gnu.org/ GCC with G++]<br />
** [http://www.kernel.org/pub/linux/devel/binutils/ binutils]<br />
* libncurses*-dev<br />
* [http://www.acpica.org/downloads/ IASL], now part of the '''ACPICA''' download (package ''pmtools'' or ''iasl'' in many distributions)<br />
<br />
= Coding Guidelines =<br />
<br />
== General Guidelines ==<br />
<br />
* Encapsulate and isolate assembly language<br />
* Code shall not be &quot;commented out&quot;<br />
* No use of floating-point arithmetics<br />
* No hiding of identifiers defined in outer scopes<br />
* Typedefs are unique (device_t?)<br />
* Functions shall have prototype declarations<br />
* Local functions should be declared static<br />
* No definitions in header files<br />
* All variables are assigned before use<br />
* All objects should have fully qualified types (''unsigned int'' instead of ''unsigned'')<br />
* We suggest trying to import more such rules, such as additional ones described in [http://www.misra.org.uk/index.htm MISRA-C 2004] (''Guidelines for the use of C in critical systems'')<br />
<br />
== Comments ==<br />
<br />
=== References ===<br />
<br />
If you are referencing a data sheet or other documentation in the code, please add the name or document number in addition to the URL. Vendors just ''love'' to rearrange their websites (and some remove documentation on their old products altogether)! If we have the name/number (or even just the filename of the PDF) at least there's a chance to google for it again (either on the vendor's site or on some archive).<br />
<br />
== Coding Style ==<br />
<br />
* We use the coreboot [[Coding Style]] throughout the project.<br />
* You can use the 'indent' tool to fix the coding style like this:<br />
indent -npro -kr -i8 -ts8 -sob -l80 -ss -ncs *.[ch]<br />
:Do not trust 'indent' blindly, though. It sometimes gets things wrong. Manual corrections may be required.<br />
<br />
== The 80 character limit ==<br />
<br />
Lines larger than 80 columns should be broken down into readable pieces. This includes not only source files, but also Makefiles, Kconfig files, and any file meant to be edited by a human. We recommend setting your editor to show the 80th character limit.<br />
This limit is not a relic from long forgotten times, but a very practical and efficient way to organize code and increase productivity. Several files can be edited on the same monitor, without the need to side-scroll. Side-scrolling source files is inefficient, time-consuming, and uncomfortable. On average, 95% of source lines are shorter than 80 characters, so limiting the line length is this manner is not only _not_ an impediment, it also gets you to think on how to best organize the code.<br />
<br />
= Documentation Guidelines =<br />
<br />
== General Guidelines and Tips ==<br />
<br />
* Documentation should be put into the wiki and/or in the code as Doxygen comments<br />
* Avoid using different styles and looks of documentation<br />
* Document ''why'' and ''what'', not ''how'' (No comments like ''/* add one to i */'')<br />
* Document assumptions, stipulations etc...<br />
* Document design and concepts!<br />
* Not lots of documentation but good documentation<br />
* Structured documentation<br />
* Focus: Whom are you addressing in your documentation? Write documentation for users, developers, vendors, ...<br />
<br />
== Automatic documentation ==<br />
<br />
* Doxygen-generated API- and code documentation is available at http://qa.coreboot.org/docs/. This documentation is updated on every 10th checkin.<br />
* To create a Doxygen comment, write<br />
/**<br />
* Sample comment.<br />
*/<br />
:or<br />
/** Sample comment. */<br />
* There are a few commands that describe what kind of comment you are adding:<br />
::@param &amp;mdash; input parameters of a function<br />
::@return &amp;mdash; return value of a function<br />
* A list of all commands is available at http://www.stack.nl/~dimitri/doxygen/commands.html<br />
<br />
Full example:<br />
<br />
/**<br />
* Calculate the length of a string.<br />
*<br />
* @param str The input string.<br />
* @return The length of the string, not including the final NUL character.<br />
*/<br />
static inline size_t strlen(const char *str)<br />
{<br />
/* ... */<br />
}<br />
<br />
= Testing =<br />
<br />
Every commit will be processed by the autobuild and autotest system available at http://qa.coreboot.org/. In addition please run autobuild yourself before submitting patches.<br />
<br />
== autobuild ==<br />
<br />
Autobuild can be found at [http://review.coreboot.org/gitweb?p=coreboot.git;a=tree;f=util/abuild;hb=HEAD coreboot/util/abuild]. <br />
<br />
Please run ''abuild'' '''before''' you commit.<br />
<br />
Autobuild is also running on every check-in to the repository. The results of this build are also available at http://qa.coreboot.org/.<br />
<br />
== autotest ==<br />
<br />
We can also run automatic tests on boards, if we find contributors willing to have a board automatically managed by our QA system. This requires a permanent connection to the net, a host system and some special circuitry. If interested, please contact us using the [[Mailinglist|mailing list]].<br />
<br />
= How to contribute =<br />
<br />
== Creating Patches ==<br />
<br />
* We use gerrit for change management, using the instance on http://review.coreboot.org/<br />
* While not necessary with gerrit, '''make sure that your change is against current master'''. Patches that fail on merge (after some developer looked at it and approved it) might linger around until '''you''' update it.<br />
* Rebase, if necessary, '''then test''' again. You might be the only contributor with that specific mainboard.<br />
* Make sure all new and modified files contain the [[Development Guidelines#Common_License_Header|proper license headers]] (see below).<br />
* Make sure all added files are actually within the commit.<br />
* Make one commit per logical change.<br />
* For more details on using gerrit, see our [[Git]] documentation. Things are somewhat different (eg. it's normal to rebase changes that were already pushed).<br />
* Double-check that your changes are correct, and that the commit only contains what you think it contains.<br />
<br />
== Sign-off Procedure ==<br />
<br />
We employ a similar sign-off procedure for coreboot <br />
[http://web.archive.org/web/20070306195036/http://osdlab.org/newsroom/press_releases/2004/2004_05_24_dco.html as the Linux developers] do.<br />
Please add a note such as<br />
Signed-off-by: Random J Developer &lt;random@developer.example.org&gt;<br />
to your email/patch if you agree with the following Developer's Certificate of Origin 1.1.<br />
<br />
Patches without a Signed-off-by cannot be pushed to gerrit!<br />
<br />
&lt;span style=&quot;color:red&quot;&gt;You have to use your real name in the Signed-off-by line and in any copyright notices you add.&lt;/span&gt; Patches without an associated real name cannot be committed!<br />
<br />
'''Developer's Certificate of Origin 1.1:'''<br />
<br />
By making a contribution to this project, I certify that:&lt;br /&gt;<br />
(a) The contribution was created in whole or in part by me and I have<br />
the right to submit it under the open source license indicated in the file; or&lt;br /&gt;<br />
(b) The contribution is based upon previous work that, to the best of my<br />
knowledge, is covered under an appropriate open source license and I have the<br />
right under that license to submit that work with modifications, whether created<br />
in whole or in part by me, under the same open source license (unless I am<br />
permitted to submit under a different license), as indicated in the file; or&lt;br /&gt;<br />
(c) The contribution was provided directly to me by some other person who<br />
certified (a), (b) or (c) and I have not modified it; and&lt;br /&gt;<br />
(d) In the case of each of (a), (b), or (c), I understand and agree that<br />
this project and the contribution are public and that a record of the contribution<br />
(including all personal information I submit with it, including my sign-off) is<br />
maintained indefinitely and may be redistributed consistent with this project or the<br />
open source license indicated in the file.<br />
<br />
&lt;small&gt;Note: The [http://web.archive.org/web/20070306195036/http://osdlab.org/newsroom/press_releases/2004/2004_05_24_dco.html Developer's Certificate of Origin 1.1] is licensed under the terms of the [http://creativecommons.org/licenses/by-sa/2.5/ Creative Commons Attribution-ShareAlike 2.5 License].&lt;/small&gt;<br />
<br />
== Reviews ==<br />
<br />
* Send your patch to [[Git|gerrit]] for review.<br />
** Provide useful commit messages. Explain what the change does and why. Our short intro to [[Git|git]] explains the format in more detail.<br />
** Add a single line containing your &quot;[[Development Guidelines#Sign-off_Procedure|sign-off]]&quot; after the description of the patch (&lt;code&gt;git commit -s&lt;/code&gt; helps, but make sure you understand and comply with the DCO).<br />
*** Example: ''Signed-off-by: John Doe &lt;john@example.com&gt;''<br />
* The developers will review and/or test your change and send comments or suggestions. Please push updated patches as described in &quot;[[Git#Evolving_patches|evolving patches]]&quot;.<br />
* If the change looks ok to one or more developers, they will approve and submit it to the master branch.<br />
<br />
= Bug-Tracker =<br />
<br />
'''note: the bug tracker is dead. more or less.'''<br />
<br />
= License Issues =<br />
<br />
* Contributed code must be GPL'd (preferrably 'GPLv2 or any later version', but 'GPLv2' is fine, too). At the very minimum the code must have a GPL-compatible license.<br />
<br />
== Common License Header ==<br />
<br />
Please quote the full GPL license header text in every file, as shown below. It should contain:<br />
<br />
* The '''year(s)''' when the code was written or modified and a '''copyright note''' of you (or your company, if you are contributing as part of your employment, and thus the copyright belongs to your company). Also, please provide an '''email address''' so that you can be contacted if questions arise.<br />
** Example:<br />
::''Copyright (C) 2006 John Doe &lt;john@example.com&gt;''<br />
::''Copyright (C) 2004-2006 Company, Inc.''<br />
* An extra line which lists the '''author of the code, if the copyright holder is not the same as the author''' (e.g. if you work for a company and the company owns the copyright).<br />
** Example:<br />
::''Copyright (C) 2004-2006 Company, Inc.''<br />
::''(Written by Janet Doe &lt;janet@example.com&gt; for Company, Inc.)''<br />
* The full '''GPL header''' as shown below.<br />
<br />
'''Complete example for *.c and *.h files:'''<br />
<br />
/*<br />
* This file is part of the coreboot project.<br />
*<br />
* Copyright (C) 2003-2005 John Doe &lt;john@example.com&gt;<br />
* Copyright (C) 2005 Jane Doe &lt;jane@example.com&gt;<br />
* Copyright (C) 2006 Company, Inc.<br />
* (Written by Janet Doe &lt;janet@example.com&gt; for Company, Inc.)<br />
* Copyright (C) 2007 Joe Doe &lt;joe@example.com&gt;<br />
*<br />
* This program is free software; you can redistribute it and/or modify<br />
* it under the terms of the GNU General Public License as published by<br />
* the Free Software Foundation; either version 2 of the License, or<br />
* (at your option) any later version.<br />
*<br />
* This program is distributed in the hope that it will be useful,<br />
* but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br />
* GNU General Public License for more details.<br />
*<br />
* You should have received a copy of the GNU General Public License<br />
* along with this program; if not, write to the Free Software<br />
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA<br />
*/<br />
<br />
'''Complete example for Makefiles, config files, Python files, shell scripts etc.:'''<br />
<br />
##<br />
## This file is part of the coreboot project.<br />
##<br />
## Copyright (C) 2003-2005 John Doe &lt;john@example.com&gt;<br />
## Copyright (C) 2005 Jane Doe &lt;jane@example.com&gt;<br />
## Copyright (C) 2006 Company, Inc.<br />
## (Written by Janet Doe &lt;janet@example.com&gt; for Company, Inc.)<br />
## Copyright (C) 2007 Joe Doe &lt;joe@example.com&gt;<br />
##<br />
## This program is free software; you can redistribute it and/or modify<br />
## it under the terms of the GNU General Public License as published by<br />
## the Free Software Foundation; either version 2 of the License, or<br />
## (at your option) any later version.<br />
##<br />
## This program is distributed in the hope that it will be useful,<br />
## but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br />
## GNU General Public License for more details.<br />
##<br />
## You should have received a copy of the GNU General Public License<br />
## along with this program; if not, write to the Free Software<br />
## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA<br />
##</div>Stepanhttp://www.coreboot.org/index.php?title=Coding_Style&diff=12302Coding Style2013-12-05T18:39:22Z<p>Stepan: </p>
<hr />
<div>This is a short document describing the preferred coding style for the<br />
coreboot project. It is in many ways exactly the same as the Linux kernel<br />
coding style. In fact, most of this document has been copied from<br />
http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/Documentation/CodingStyle?id=HEAD<br />
Please at least consider the points made here.<br />
<br />
First off, I'd suggest printing out a copy of the GNU coding standards,<br />
and NOT read it. Burn them, it's a great symbolic gesture.<br />
<br />
Anyway, here goes:<br />
<br />
<br />
== Indentation ==<br />
<br />
Tabs are 8 characters, and thus indentations are also 8 characters.<br />
There are heretic movements that try to make indentations 4 (or even 2!)<br />
characters deep, and that is akin to trying to define the value of PI to<br />
be 3.<br />
<br />
Rationale: The whole idea behind indentation is to clearly define where<br />
a block of control starts and ends. Especially when you've been looking<br />
at your screen for 20 straight hours, you'll find it a lot easier to see<br />
how the indentation works if you have large indentations.<br />
<br />
Now, some people will claim that having 8-character indentations makes<br />
the code move too far to the right, and makes it hard to read on a<br />
80-character terminal screen. The answer to that is that if you need<br />
more than 3 levels of indentation, you're screwed anyway, and should fix<br />
your program.<br />
<br />
In short, 8-char indents make things easier to read, and have the added<br />
benefit of warning you when you're nesting your functions too deep.<br />
Heed that warning.<br />
<br />
The preferred way to ease multiple indentation levels in a switch statement is<br />
to align the &quot;switch&quot; and its subordinate &quot;case&quot; labels in the same column<br />
instead of &quot;double-indenting&quot; the &quot;case&quot; labels. E.g.:<br />
<br />
switch (suffix) {<br />
case 'G':<br />
case 'g':<br />
mem &lt;&lt;= 30;<br />
break;<br />
case 'M':<br />
case 'm':<br />
mem &lt;&lt;= 20;<br />
break;<br />
case 'K':<br />
case 'k':<br />
mem &lt;&lt;= 10;<br />
/* fall through */<br />
default:<br />
break;<br />
}<br />
<br />
<br />
Don't put multiple statements on a single line unless you have<br />
something to hide:<br />
<br />
if (condition) do_this;<br />
do_something_everytime;<br />
<br />
Don't put multiple assignments on a single line either. Kernel coding style<br />
is super simple. Avoid tricky expressions.<br />
<br />
Outside of comments, documentation and except in Kconfig, spaces are never<br />
used for indentation, and the above example is deliberately broken.<br />
<br />
Get a decent editor and don't leave whitespace at the end of lines.<br />
<br />
<br />
== Breaking long lines and strings ==<br />
<br />
Coding style is all about readability and maintainability using commonly<br />
available tools.<br />
<br />
The limit on the length of lines is 80 columns and this is a strongly<br />
preferred limit.<br />
<br />
Statements longer than 80 columns will be broken into sensible chunks, unless<br />
exceeding 80 columns significantly increases readability and does not hide<br />
information. Descendants are always substantially shorter than the parent and<br />
are placed substantially to the right. The same applies to function headers<br />
with a long argument list. However, never break user-visible strings such as<br />
printk messages, because that breaks the ability to grep for them.<br />
<br />
<br />
== Placing Braces and Spaces ==<br />
<br />
The other issue that always comes up in C styling is the placement of<br />
braces. Unlike the indent size, there are few technical reasons to<br />
choose one placement strategy over the other, but the preferred way, as<br />
shown to us by the prophets Kernighan and Ritchie, is to put the opening<br />
brace last on the line, and put the closing brace first, thusly:<br />
<br />
if (x is true) {<br />
we do y<br />
}<br />
<br />
This applies to all non-function statement blocks (if, switch, for,<br />
while, do). E.g.:<br />
<br />
switch (action) {<br />
case KOBJ_ADD:<br />
return &quot;add&quot;;<br />
case KOBJ_REMOVE:<br />
return &quot;remove&quot;;<br />
case KOBJ_CHANGE:<br />
return &quot;change&quot;;<br />
default:<br />
return NULL;<br />
}<br />
<br />
However, there is one special case, namely functions: they have the<br />
opening brace at the beginning of the next line, thus:<br />
<br />
int function(int x)<br />
{<br />
body of function<br />
}<br />
<br />
Heretic people all over the world have claimed that this inconsistency<br />
is ... well ... inconsistent, but all right-thinking people know that<br />
(a) K&amp;R are _right_ and (b) K&amp;R are right. Besides, functions are<br />
special anyway (you can't nest them in C).<br />
<br />
Note that the closing brace is empty on a line of its own, _except_ in<br />
the cases where it is followed by a continuation of the same statement,<br />
ie a &quot;while&quot; in a do-statement or an &quot;else&quot; in an if-statement, like<br />
this:<br />
<br />
do {<br />
body of do-loop<br />
} while (condition);<br />
<br />
and<br />
<br />
if (x == y) {<br />
..<br />
} else if (x &gt; y) {<br />
...<br />
} else {<br />
....<br />
}<br />
<br />
Rationale: K&amp;R.<br />
<br />
Also, note that this brace-placement also minimizes the number of empty<br />
(or almost empty) lines, without any loss of readability. Thus, as the<br />
supply of new-lines on your screen is not a renewable resource (think<br />
25-line terminal screens here), you have more empty lines to put<br />
comments on.<br />
<br />
Do not unnecessarily use braces where a single statement will do.<br />
<br />
if (condition)<br />
action();<br />
<br />
and<br />
<br />
if (condition)<br />
do_this();<br />
else<br />
do_that();<br />
<br />
This does not apply if only one branch of a conditional statement is a single<br />
statement; in the latter case use braces in both branches:<br />
<br />
if (condition) {<br />
do_this();<br />
do_that();<br />
} else {<br />
otherwise();<br />
}<br />
<br />
=== Spaces ===<br />
<br />
Linux kernel style for use of spaces depends (mostly) on<br />
function-versus-keyword usage. Use a space after (most) keywords. The<br />
notable exceptions are sizeof, typeof, alignof, and __attribute__, which look<br />
somewhat like functions (and are usually used with parentheses in Linux,<br />
although they are not required in the language, as in: &quot;sizeof info&quot; after<br />
&quot;struct fileinfo info;&quot; is declared).<br />
<br />
So use a space after these keywords:<br />
if, switch, case, for, do, while<br />
but not with sizeof, typeof, alignof, or __attribute__. E.g.,<br />
s = sizeof(struct file);<br />
<br />
Do not add spaces around (inside) parenthesized expressions. This example is<br />
*bad*:<br />
<br />
s = sizeof( struct file );<br />
<br />
When declaring pointer data or a function that returns a pointer type, the<br />
preferred use of '*' is adjacent to the data name or function name and not<br />
adjacent to the type name. Examples:<br />
<br />
char *linux_banner;<br />
unsigned long long memparse(char *ptr, char **retptr);<br />
char *match_strdup(substring_t *s);<br />
<br />
Use one space around (on each side of) most binary and ternary operators,<br />
such as any of these:<br />
<br />
= + - &lt; &gt; * / % | &amp; ^ &lt;= &gt;= == != ? :<br />
<br />
but no space after unary operators:<br />
&amp; * + - ~ ! sizeof typeof alignof __attribute__ defined<br />
<br />
no space before the postfix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
no space after the prefix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
and no space around the '.' and &quot;-&gt;&quot; structure member operators.<br />
<br />
Do not leave trailing whitespace at the ends of lines. Some editors with<br />
&quot;smart&quot; indentation will insert whitespace at the beginning of new lines as<br />
appropriate, so you can start typing the next line of code right away.<br />
However, some such editors do not remove the whitespace if you end up not<br />
putting a line of code there, such as if you leave a blank line. As a result,<br />
you end up with lines containing trailing whitespace.<br />
<br />
Git will warn you about patches that introduce trailing whitespace, and can<br />
optionally strip the trailing whitespace for you; however, if applying a series<br />
of patches, this may make later patches in the series fail by changing their<br />
context lines.<br />
<br />
<br />
== Naming ==<br />
<br />
C is a Spartan language, and so should your naming be. Unlike Modula-2<br />
and Pascal programmers, C programmers do not use cute names like<br />
ThisVariableIsATemporaryCounter. A C programmer would call that<br />
variable &quot;tmp&quot;, which is much easier to write, and not the least more<br />
difficult to understand.<br />
<br />
HOWEVER, while mixed-case names are frowned upon, descriptive names for<br />
global variables are a must. To call a global function &quot;foo&quot; is a<br />
shooting offense.<br />
<br />
GLOBAL variables (to be used only if you _really_ need them) need to<br />
have descriptive names, as do global functions. If you have a function<br />
that counts the number of active users, you should call that<br />
&quot;count_active_users()&quot; or similar, you should _not_ call it &quot;cntusr()&quot;.<br />
<br />
Encoding the type of a function into the name (so-called Hungarian<br />
notation) is brain damaged - the compiler knows the types anyway and can<br />
check those, and it only confuses the programmer. No wonder MicroSoft<br />
makes buggy programs.<br />
<br />
LOCAL variable names should be short, and to the point. If you have<br />
some random integer loop counter, it should probably be called &quot;i&quot;.<br />
Calling it &quot;loop_counter&quot; is non-productive, if there is no chance of it<br />
being mis-understood. Similarly, &quot;tmp&quot; can be just about any type of<br />
variable that is used to hold a temporary value.<br />
<br />
If you are afraid to mix up your local variable names, you have another<br />
problem, which is called the function-growth-hormone-imbalance syndrome.<br />
See chapter 6 (Functions).<br />
<br />
<br />
== Typedefs ==<br />
<br />
Please don't use things like &quot;vps_t&quot;.<br />
<br />
It's a _mistake_ to use typedef for structures and pointers. When you see a<br />
<br />
vps_t a;<br />
<br />
in the source, what does it mean?<br />
<br />
In contrast, if it says<br />
<br />
struct virtual_container *a;<br />
<br />
you can actually tell what &quot;a&quot; is.<br />
<br />
Lots of people think that typedefs &quot;help readability&quot;. Not so. They are<br />
useful only for:<br />
<br />
(a) totally opaque objects (where the typedef is actively used to _hide_<br />
what the object is).<br />
<br />
Example: &quot;pte_t&quot; etc. opaque objects that you can only access using<br />
the proper accessor functions.<br />
<br />
NOTE! Opaqueness and &quot;accessor functions&quot; are not good in themselves.<br />
The reason we have them for things like pte_t etc. is that there<br />
really is absolutely _zero_ portably accessible information there.<br />
<br />
(b) Clear integer types, where the abstraction _helps_ avoid confusion<br />
whether it is &quot;int&quot; or &quot;long&quot;.<br />
<br />
u8/u16/u32 are perfectly fine typedefs, although they fit into<br />
category (d) better than here.<br />
<br />
NOTE! Again - there needs to be a _reason_ for this. If something is<br />
&quot;unsigned long&quot;, then there's no reason to do<br />
<br />
typedef unsigned long myflags_t;<br />
<br />
but if there is a clear reason for why it under certain circumstances<br />
might be an &quot;unsigned int&quot; and under other configurations might be<br />
&quot;unsigned long&quot;, then by all means go ahead and use a typedef.<br />
<br />
(c) when you use sparse to literally create a _new_ type for<br />
type-checking.<br />
<br />
(d) New types which are identical to standard C99 types, in certain<br />
exceptional circumstances.<br />
<br />
Although it would only take a short amount of time for the eyes and<br />
brain to become accustomed to the standard types like 'uint32_t',<br />
some people object to their use anyway.<br />
<br />
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their<br />
signed equivalents which are identical to standard types are<br />
permitted -- although they are not mandatory in new code of your<br />
own.<br />
<br />
When editing existing code which already uses one or the other set<br />
of types, you should conform to the existing choices in that code.<br />
<br />
(e) Types safe for use in userspace.<br />
<br />
In certain structures which are visible to userspace, we cannot<br />
require C99 types and cannot use the 'u32' form above. Thus, we<br />
use __u32 and similar types in all structures which are shared<br />
with userspace.<br />
<br />
Maybe there are other cases too, but the rule should basically be to NEVER<br />
EVER use a typedef unless you can clearly match one of those rules.<br />
<br />
In general, a pointer, or a struct that has elements that can reasonably<br />
be directly accessed should _never_ be a typedef.<br />
<br />
<br />
== Functions ==<br />
<br />
Functions should be short and sweet, and do just one thing. They should<br />
fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,<br />
as we all know), and do one thing and do that well.<br />
<br />
The maximum length of a function is inversely proportional to the<br />
complexity and indentation level of that function. So, if you have a<br />
conceptually simple function that is just one long (but simple)<br />
case-statement, where you have to do lots of small things for a lot of<br />
different cases, it's OK to have a longer function.<br />
<br />
However, if you have a complex function, and you suspect that a<br />
less-than-gifted first-year high-school student might not even<br />
understand what the function is all about, you should adhere to the<br />
maximum limits all the more closely. Use helper functions with<br />
descriptive names (you can ask the compiler to in-line them if you think<br />
it's performance-critical, and it will probably do a better job of it<br />
than you would have done).<br />
<br />
Another measure of the function is the number of local variables. They<br />
shouldn't exceed 5-10, or you're doing something wrong. Re-think the<br />
function, and split it into smaller pieces. A human brain can<br />
generally easily keep track of about 7 different things, anything more<br />
and it gets confused. You know you're brilliant, but maybe you'd like<br />
to understand what you did 2 weeks from now.<br />
<br />
In source files, separate functions with one blank line. If the function is<br />
exported, the EXPORT* macro for it should follow immediately after the closing<br />
function brace line. E.g.:<br />
<br />
int system_is_up(void)<br />
{<br />
return system_state == SYSTEM_RUNNING;<br />
}<br />
EXPORT_SYMBOL(system_is_up);<br />
<br />
In function prototypes, include parameter names with their data types.<br />
Although this is not required by the C language, it is preferred in Linux<br />
because it is a simple way to add valuable information for the reader.<br />
<br />
<br />
== Centralized exiting of functions ==<br />
<br />
Albeit deprecated by some people, the equivalent of the goto statement is<br />
used frequently by compilers in form of the unconditional jump instruction.<br />
<br />
The goto statement comes in handy when a function exits from multiple<br />
locations and some common work such as cleanup has to be done. If there is no<br />
cleanup needed then just return directly.<br />
<br />
The rationale is:<br />
<br />
- unconditional statements are easier to understand and follow<br />
- nesting is reduced<br />
- errors by not updating individual exit points when making<br />
modifications are prevented<br />
- saves the compiler work to optimize redundant code away ;)<br />
<br />
int fun(int a)<br />
{<br />
int result = 0;<br />
char *buffer = kmalloc(SIZE);<br />
<br />
if (buffer == NULL)<br />
return -ENOMEM;<br />
<br />
if (condition1) {<br />
while (loop1) {<br />
...<br />
}<br />
result = 1;<br />
goto out;<br />
}<br />
...<br />
out:<br />
kfree(buffer);<br />
return result;<br />
}<br />
<br />
== Commenting ==<br />
<br />
Comments are good, but there is also a danger of over-commenting. NEVER<br />
try to explain HOW your code works in a comment: it's much better to<br />
write the code so that the _working_ is obvious, and it's a waste of<br />
time to explain badly written code.<br />
<br />
Generally, you want your comments to tell WHAT your code does, not HOW.<br />
Also, try to avoid putting comments inside a function body: if the<br />
function is so complex that you need to separately comment parts of it,<br />
you should probably go back to chapter 6 for a while. You can make<br />
small comments to note or warn about something particularly clever (or<br />
ugly), but try to avoid excess. Instead, put the comments at the head<br />
of the function, telling people what it does, and possibly WHY it does<br />
it.<br />
<br />
When commenting the kernel API functions, please use the kernel-doc format.<br />
See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc<br />
for details.<br />
<br />
coreboot style for comments is the C89 &quot;/* ... */&quot; style.<br />
You may use C99-style &quot;// ...&quot; comments.<br />
<br />
The preferred style for long (multi-line) comments is:<br />
<br />
/*<br />
* This is the preferred style for multi-line<br />
* comments in the Linux kernel source code.<br />
* Please use it consistently.<br />
*<br />
* Description: A column of asterisks on the left side,<br />
* with beginning and ending almost-blank lines.<br />
*/<br />
<br />
For files in net/ and drivers/net/ the preferred style for long (multi-line)<br />
comments is a little different.<br />
<br />
/* The preferred comment style for files in net/ and drivers/net<br />
* looks like this.<br />
*<br />
* It is nearly the same as the generally preferred comment style,<br />
* but there is no initial almost-blank line.<br />
*/<br />
<br />
It's also important to comment data, whether they are basic types or derived<br />
types. To this end, use just one data declaration per line (no commas for<br />
multiple data declarations). This leaves you room for a small comment on each<br />
item, explaining its use.<br />
<br />
<br />
== You've made a mess of it ==<br />
<br />
That's OK, we all do. You've probably been told by your long-time Unix<br />
user helper that &quot;GNU emacs&quot; automatically formats the C sources for<br />
you, and you've noticed that yes, it does do that, but the defaults it<br />
uses are less than desirable (in fact, they are worse than random<br />
typing - an infinite number of monkeys typing into GNU emacs would never<br />
make a good program).<br />
<br />
So, you can either get rid of GNU emacs, or change it to use saner<br />
values. To do the latter, you can stick the following in your .emacs file:<br />
<br />
(defun c-lineup-arglist-tabs-only (ignored)<br />
&quot;Line up argument lists by tabs, not spaces&quot;<br />
(let* ((anchor (c-langelem-pos c-syntactic-element))<br />
(column (c-langelem-2nd-pos c-syntactic-element))<br />
(offset (- (1+ column) anchor))<br />
(steps (floor offset c-basic-offset)))<br />
(* (max steps 1)<br />
c-basic-offset)))<br />
<br />
(add-hook 'c-mode-common-hook<br />
(lambda ()<br />
;; Add kernel style<br />
(c-add-style<br />
&quot;linux-tabs-only&quot;<br />
'(&quot;linux&quot; (c-offsets-alist<br />
(arglist-cont-nonempty<br />
c-lineup-gcc-asm-reg<br />
c-lineup-arglist-tabs-only))))))<br />
<br />
(add-hook 'c-mode-hook<br />
(lambda ()<br />
(let ((filename (buffer-file-name)))<br />
;; Enable kernel mode for the appropriate files<br />
(when (and filename<br />
(string-match (expand-file-name &quot;~/src/linux-trees&quot;)<br />
filename))<br />
(setq indent-tabs-mode t)<br />
(c-set-style &quot;linux-tabs-only&quot;)))))<br />
<br />
This will make emacs go better with the kernel coding style for C<br />
files below ~/src/linux-trees.<br />
<br />
But even if you fail in getting emacs to do sane formatting, not<br />
everything is lost: use &quot;indent&quot;.<br />
<br />
Now, again, GNU indent has the same brain-dead settings that GNU emacs<br />
has, which is why you need to give it a few command line options.<br />
However, that's not too bad, because even the makers of GNU indent<br />
recognize the authority of K&amp;R (the GNU people aren't evil, they are<br />
just severely misguided in this matter), so you just give indent the<br />
options &quot;-kr -i8&quot; (stands for &quot;K&amp;R, 8 character indents&quot;), or use<br />
&quot;scripts/Lindent&quot;, which indents in the latest style.<br />
<br />
&quot;indent&quot; has a lot of options, and especially when it comes to comment<br />
re-formatting you may want to take a look at the man page. But<br />
remember: &quot;indent&quot; is not a fix for bad programming.<br />
<br />
<br />
== Kconfig configuration files ==<br />
<br />
For all of the Kconfig* configuration files throughout the source tree,<br />
the indentation is somewhat different. Lines under a &quot;config&quot; definition<br />
are indented with one tab, while help text is indented an additional two<br />
spaces. Example:<br />
<br />
config AUDIT<br />
bool &quot;Auditing support&quot;<br />
depends on NET<br />
help<br />
Enable auditing infrastructure that can be used with another<br />
kernel subsystem, such as SELinux (which requires this for<br />
logging of avc messages output). Does not do system-call<br />
auditing without CONFIG_AUDITSYSCALL.<br />
<br />
Seriously dangerous features (such as write support for certain<br />
filesystems) should advertise this prominently in their prompt string:<br />
<br />
config ADFS_FS_RW<br />
bool &quot;ADFS write support (DANGEROUS)&quot;<br />
depends on ADFS_FS<br />
...<br />
<br />
For full documentation on the configuration files, see the file<br />
Documentation/kbuild/kconfig-language.txt.<br />
<br />
<br />
== Data structures ==<br />
<br />
Data structures that have visibility outside the single-threaded<br />
environment they are created and destroyed in should always have<br />
reference counts. In the kernel, garbage collection doesn't exist (and<br />
outside the kernel garbage collection is slow and inefficient), which<br />
means that you absolutely _have_ to reference count all your uses.<br />
<br />
Reference counting means that you can avoid locking, and allows multiple<br />
users to have access to the data structure in parallel - and not having<br />
to worry about the structure suddenly going away from under them just<br />
because they slept or did something else for a while.<br />
<br />
Note that locking is _not_ a replacement for reference counting.<br />
Locking is used to keep data structures coherent, while reference<br />
counting is a memory management technique. Usually both are needed, and<br />
they are not to be confused with each other.<br />
<br />
Many data structures can indeed have two levels of reference counting,<br />
when there are users of different &quot;classes&quot;. The subclass count counts<br />
the number of subclass users, and decrements the global count just once<br />
when the subclass count goes to zero.<br />
<br />
Examples of this kind of &quot;multi-level-reference-counting&quot; can be found in<br />
memory management (&quot;struct mm_struct&quot;: mm_users and mm_count), and in<br />
filesystem code (&quot;struct super_block&quot;: s_count and s_active).<br />
<br />
Remember: if another thread can find your data structure, and you don't<br />
have a reference count on it, you almost certainly have a bug.<br />
<br />
<br />
== Macros, Enums and RTL ==<br />
<br />
Names of macros defining constants and labels in enums are capitalized.<br />
<br />
#define CONSTANT 0x12345<br />
<br />
Enums are preferred when defining several related constants.<br />
<br />
CAPITALIZED macro names are appreciated but macros resembling functions<br />
may be named in lower case.<br />
<br />
Generally, inline functions are preferable to macros resembling functions.<br />
<br />
Macros with multiple statements should be enclosed in a do - while block:<br />
<br />
#define macrofun(a, b, c) \<br />
do { \<br />
if (a == 5) \<br />
do_this(b, c); \<br />
} while (0)<br />
<br />
Things to avoid when using macros:<br />
<br />
1) macros that affect control flow:<br />
<br />
#define FOO(x) \<br />
do { \<br />
if (blah(x) &lt; 0) \<br />
return -EBUGGERED; \<br />
} while(0)<br />
<br />
is a _very_ bad idea. It looks like a function call but exits the &quot;calling&quot;<br />
function; don't break the internal parsers of those who will read the code.<br />
<br />
2) macros that depend on having a local variable with a magic name:<br />
<br />
#define FOO(val) bar(index, val)<br />
<br />
might look like a good thing, but it's confusing as hell when one reads the<br />
code and it's prone to breakage from seemingly innocent changes.<br />
<br />
3) macros with arguments that are used as l-values: FOO(x) = y; will<br />
bite you if somebody e.g. turns FOO into an inline function.<br />
<br />
4) forgetting about precedence: macros defining constants using expressions<br />
must enclose the expression in parentheses. Beware of similar issues with<br />
macros using parameters.<br />
<br />
#define CONSTANT 0x4000<br />
#define CONSTEXP (CONSTANT | 3)<br />
<br />
The cpp manual deals with macros exhaustively. The gcc internals manual also<br />
covers RTL which is used frequently with assembly language in the kernel.<br />
<br />
<br />
== Printing kernel messages ==<br />
<br />
Kernel developers like to be seen as literate. Do mind the spelling<br />
of kernel messages to make a good impression. Do not use crippled<br />
words like &quot;dont&quot;; use &quot;do not&quot; or &quot;don't&quot; instead. Make the messages<br />
concise, clear, and unambiguous.<br />
<br />
Kernel messages do not have to be terminated with a period.<br />
<br />
Printing numbers in parentheses (%d) adds no value and should be avoided.<br />
<br />
There are a number of driver model diagnostic macros in &lt;linux/device.h&gt;<br />
which you should use to make sure messages are matched to the right device<br />
and driver, and are tagged with the right level: dev_err(), dev_warn(),<br />
dev_info(), and so forth. For messages that aren't associated with a<br />
particular device, &lt;linux/printk.h&gt; defines pr_debug() and pr_info().<br />
<br />
Coming up with good debugging messages can be quite a challenge; and once<br />
you have them, they can be a huge help for remote troubleshooting. Such<br />
messages should be compiled out when the DEBUG symbol is not defined (that<br />
is, by default they are not included). When you use dev_dbg() or pr_debug(),<br />
that's automatic. Many subsystems have Kconfig options to turn on -DDEBUG.<br />
A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to the<br />
ones already enabled by DEBUG.<br />
<br />
<br />
== Allocating memory ==<br />
<br />
The kernel provides the following general purpose memory allocators:<br />
kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and<br />
vzalloc(). Please refer to the API documentation for further information<br />
about them.<br />
<br />
The preferred form for passing a size of a struct is the following:<br />
<br />
p = kmalloc(sizeof(*p), ...);<br />
<br />
The alternative form where struct name is spelled out hurts readability and<br />
introduces an opportunity for a bug when the pointer variable type is changed<br />
but the corresponding sizeof that is passed to a memory allocator is not.<br />
<br />
Casting the return value which is a void pointer is redundant. The conversion<br />
from void pointer to any other pointer type is guaranteed by the C programming<br />
language.<br />
<br />
The preferred form for allocating an array is the following:<br />
<br />
p = kmalloc_array(n, sizeof(...), ...);<br />
<br />
The preferred form for allocating a zeroed array is the following:<br />
<br />
p = kcalloc(n, sizeof(...), ...);<br />
<br />
Both forms check for overflow on the allocation size n * sizeof(...),<br />
and return NULL if that occurred.<br />
<br />
<br />
== The inline disease ==<br />
<br />
There appears to be a common misperception that gcc has a magic &quot;make me<br />
faster&quot; speedup option called &quot;inline&quot;. While the use of inlines can be<br />
appropriate (for example as a means of replacing macros, see Chapter 12), it<br />
very often is not. Abundant use of the inline keyword leads to a much bigger<br />
kernel, which in turn slows the system as a whole down, due to a bigger<br />
icache footprint for the CPU and simply because there is less memory<br />
available for the pagecache. Just think about it; a pagecache miss causes a<br />
disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles<br />
that can go into these 5 milliseconds.<br />
<br />
A reasonable rule of thumb is to not put inline at functions that have more<br />
than 3 lines of code in them. An exception to this rule are the cases where<br />
a parameter is known to be a compiletime constant, and as a result of this<br />
constantness you *know* the compiler will be able to optimize most of your<br />
function away at compile time. For a good example of this later case, see<br />
the kmalloc() inline function.<br />
<br />
Often people argue that adding inline to functions that are static and used<br />
only once is always a win since there is no space tradeoff. While this is<br />
technically correct, gcc is capable of inlining these automatically without<br />
help, and the maintenance issue of removing the inline when a second user<br />
appears outweighs the potential value of the hint that tells gcc to do<br />
something it would have done anyway.<br />
<br />
<br />
== Function return values and names ==<br />
<br />
Functions can return values of many different kinds, and one of the<br />
most common is a value indicating whether the function succeeded or<br />
failed. Such a value can be represented as an error-code integer<br />
(-Exxx = failure, 0 = success) or a &quot;succeeded&quot; boolean (0 = failure,<br />
non-zero = success).<br />
<br />
Mixing up these two sorts of representations is a fertile source of<br />
difficult-to-find bugs. If the C language included a strong distinction<br />
between integers and booleans then the compiler would find these mistakes<br />
for us... but it doesn't. To help prevent such bugs, always follow this<br />
convention:<br />
<br />
If the name of a function is an action or an imperative command,<br />
the function should return an error-code integer. If the name<br />
is a predicate, the function should return a &quot;succeeded&quot; boolean.<br />
<br />
For example, &quot;add work&quot; is a command, and the add_work() function returns 0<br />
for success or -EBUSY for failure. In the same way, &quot;PCI device present&quot; is<br />
a predicate, and the pci_dev_present() function returns 1 if it succeeds in<br />
finding a matching device or 0 if it doesn't.<br />
<br />
All EXPORTed functions must respect this convention, and so should all<br />
public functions. Private (static) functions need not, but it is<br />
recommended that they do.<br />
<br />
Functions whose return value is the actual result of a computation, rather<br />
than an indication of whether the computation succeeded, are not subject to<br />
this rule. Generally they indicate failure by returning some out-of-range<br />
result. Typical examples would be functions that return pointers; they use<br />
NULL or the ERR_PTR mechanism to report failure.<br />
<br />
<br />
== Don't re-invent the kernel macros ==<br />
<br />
The header file include/linux/kernel.h contains a number of macros that<br />
you should use, rather than explicitly coding some variant of them yourself.<br />
For example, if you need to calculate the length of an array, take advantage<br />
of the macro<br />
<br />
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))<br />
<br />
Similarly, if you need to calculate the size of some structure member, use<br />
<br />
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)-&gt;f))<br />
<br />
There are also min() and max() macros that do strict type checking if you<br />
need them. Feel free to peruse that header file to see what else is already<br />
defined that you shouldn't reproduce in your code.<br />
<br />
<br />
== Editor modelines and other cruft ==<br />
<br />
Some editors can interpret configuration information embedded in source files,<br />
indicated with special markers. For example, emacs interprets lines marked<br />
like this:<br />
<br />
-*- mode: c -*-<br />
<br />
Or like this:<br />
<br />
/*<br />
Local Variables:<br />
compile-command: &quot;gcc -DMAGIC_DEBUG_FLAG foo.c&quot;<br />
End:<br />
*/<br />
<br />
Vim interprets markers that look like this:<br />
<br />
/* vim:set sw=8 noet */<br />
<br />
Do not include any of these in source files. People have their own personal<br />
editor configurations, and your source files should not override them. This<br />
includes markers for indentation and mode configuration. People may use their<br />
own custom mode, or may have some other magic method for making indentation<br />
work correctly.<br />
<br />
<br />
== Inline assembly ==<br />
<br />
In architecture-specific code, you may need to use inline assembly to interface<br />
with CPU or platform functionality. Don't hesitate to do so when necessary.<br />
However, don't use inline assembly gratuitously when C can do the job. You can<br />
and should poke hardware from C when possible.<br />
<br />
Consider writing simple helper functions that wrap common bits of inline<br />
assembly, rather than repeatedly writing them with slight variations. Remember<br />
that inline assembly can use C parameters.<br />
<br />
Large, non-trivial assembly functions should go in .S files, with corresponding<br />
C prototypes defined in C header files. The C prototypes for assembly<br />
functions should use &quot;asmlinkage&quot;.<br />
<br />
You may need to mark your asm statement as volatile, to prevent GCC from<br />
removing it if GCC doesn't notice any side effects. You don't always need to<br />
do so, though, and doing so unnecessarily can limit optimization.<br />
<br />
When writing a single inline assembly statement containing multiple<br />
instructions, put each instruction on a separate line in a separate quoted<br />
string, and end each string except the last with \n\t to properly indent the<br />
next instruction in the assembly output:<br />
<br />
asm (&quot;magic %reg1, #42\n\t&quot;<br />
&quot;more_magic %reg2, %reg3&quot;<br />
: /* outputs */ : /* inputs */ : /* clobbers */);<br />
<br />
<br />
<br />
== References ==<br />
<br />
The C Programming Language, Second Edition<br />
by Brian W. Kernighan and Dennis M. Ritchie.<br />
Prentice Hall, Inc., 1988.<br />
ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).<br />
URL: http://cm.bell-labs.com/cm/cs/cbook/<br />
<br />
The Practice of Programming<br />
by Brian W. Kernighan and Rob Pike.<br />
Addison-Wesley, Inc., 1999.<br />
ISBN 0-201-61586-X.<br />
URL: http://cm.bell-labs.com/cm/cs/tpop/<br />
<br />
GNU manuals - where in compliance with K&amp;R and this text - for cpp, gcc,<br />
gcc internals and indent, all available from http://www.gnu.org/manual/<br />
<br />
WG14 is the international standardization working group for the programming<br />
language C, URL: http://www.open-std.org/JTC1/SC22/WG14/<br />
<br />
Kernel CodingStyle, by greg@kroah.com at OLS 2002:<br />
http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/</div>Stepanhttp://www.coreboot.org/index.php?title=Coding_Style&diff=12301Coding Style2013-12-05T18:38:25Z<p>Stepan: Created page with &quot;= coreboot coding style = This is a short document describing the preferred coding style for the coreboot project. It is in many ways exactly the same as the Linux kernel co...&quot;</p>
<hr />
<div>= coreboot coding style =<br />
<br />
This is a short document describing the preferred coding style for the<br />
coreboot project. It is in many ways exactly the same as the Linux kernel<br />
coding style. Please at least consider the points made here.<br />
<br />
First off, I'd suggest printing out a copy of the GNU coding standards,<br />
and NOT read it. Burn them, it's a great symbolic gesture.<br />
<br />
Anyway, here goes:<br />
<br />
<br />
== Indentation ==<br />
<br />
Tabs are 8 characters, and thus indentations are also 8 characters.<br />
There are heretic movements that try to make indentations 4 (or even 2!)<br />
characters deep, and that is akin to trying to define the value of PI to<br />
be 3.<br />
<br />
Rationale: The whole idea behind indentation is to clearly define where<br />
a block of control starts and ends. Especially when you've been looking<br />
at your screen for 20 straight hours, you'll find it a lot easier to see<br />
how the indentation works if you have large indentations.<br />
<br />
Now, some people will claim that having 8-character indentations makes<br />
the code move too far to the right, and makes it hard to read on a<br />
80-character terminal screen. The answer to that is that if you need<br />
more than 3 levels of indentation, you're screwed anyway, and should fix<br />
your program.<br />
<br />
In short, 8-char indents make things easier to read, and have the added<br />
benefit of warning you when you're nesting your functions too deep.<br />
Heed that warning.<br />
<br />
The preferred way to ease multiple indentation levels in a switch statement is<br />
to align the &quot;switch&quot; and its subordinate &quot;case&quot; labels in the same column<br />
instead of &quot;double-indenting&quot; the &quot;case&quot; labels. E.g.:<br />
<br />
switch (suffix) {<br />
case 'G':<br />
case 'g':<br />
mem &lt;&lt;= 30;<br />
break;<br />
case 'M':<br />
case 'm':<br />
mem &lt;&lt;= 20;<br />
break;<br />
case 'K':<br />
case 'k':<br />
mem &lt;&lt;= 10;<br />
/* fall through */<br />
default:<br />
break;<br />
}<br />
<br />
<br />
Don't put multiple statements on a single line unless you have<br />
something to hide:<br />
<br />
if (condition) do_this;<br />
do_something_everytime;<br />
<br />
Don't put multiple assignments on a single line either. Kernel coding style<br />
is super simple. Avoid tricky expressions.<br />
<br />
Outside of comments, documentation and except in Kconfig, spaces are never<br />
used for indentation, and the above example is deliberately broken.<br />
<br />
Get a decent editor and don't leave whitespace at the end of lines.<br />
<br />
<br />
== Breaking long lines and strings ==<br />
<br />
Coding style is all about readability and maintainability using commonly<br />
available tools.<br />
<br />
The limit on the length of lines is 80 columns and this is a strongly<br />
preferred limit.<br />
<br />
Statements longer than 80 columns will be broken into sensible chunks, unless<br />
exceeding 80 columns significantly increases readability and does not hide<br />
information. Descendants are always substantially shorter than the parent and<br />
are placed substantially to the right. The same applies to function headers<br />
with a long argument list. However, never break user-visible strings such as<br />
printk messages, because that breaks the ability to grep for them.<br />
<br />
<br />
== Placing Braces and Spaces ==<br />
<br />
The other issue that always comes up in C styling is the placement of<br />
braces. Unlike the indent size, there are few technical reasons to<br />
choose one placement strategy over the other, but the preferred way, as<br />
shown to us by the prophets Kernighan and Ritchie, is to put the opening<br />
brace last on the line, and put the closing brace first, thusly:<br />
<br />
if (x is true) {<br />
we do y<br />
}<br />
<br />
This applies to all non-function statement blocks (if, switch, for,<br />
while, do). E.g.:<br />
<br />
switch (action) {<br />
case KOBJ_ADD:<br />
return &quot;add&quot;;<br />
case KOBJ_REMOVE:<br />
return &quot;remove&quot;;<br />
case KOBJ_CHANGE:<br />
return &quot;change&quot;;<br />
default:<br />
return NULL;<br />
}<br />
<br />
However, there is one special case, namely functions: they have the<br />
opening brace at the beginning of the next line, thus:<br />
<br />
int function(int x)<br />
{<br />
body of function<br />
}<br />
<br />
Heretic people all over the world have claimed that this inconsistency<br />
is ... well ... inconsistent, but all right-thinking people know that<br />
(a) K&amp;R are _right_ and (b) K&amp;R are right. Besides, functions are<br />
special anyway (you can't nest them in C).<br />
<br />
Note that the closing brace is empty on a line of its own, _except_ in<br />
the cases where it is followed by a continuation of the same statement,<br />
ie a &quot;while&quot; in a do-statement or an &quot;else&quot; in an if-statement, like<br />
this:<br />
<br />
do {<br />
body of do-loop<br />
} while (condition);<br />
<br />
and<br />
<br />
if (x == y) {<br />
..<br />
} else if (x &gt; y) {<br />
...<br />
} else {<br />
....<br />
}<br />
<br />
Rationale: K&amp;R.<br />
<br />
Also, note that this brace-placement also minimizes the number of empty<br />
(or almost empty) lines, without any loss of readability. Thus, as the<br />
supply of new-lines on your screen is not a renewable resource (think<br />
25-line terminal screens here), you have more empty lines to put<br />
comments on.<br />
<br />
Do not unnecessarily use braces where a single statement will do.<br />
<br />
if (condition)<br />
action();<br />
<br />
and<br />
<br />
if (condition)<br />
do_this();<br />
else<br />
do_that();<br />
<br />
This does not apply if only one branch of a conditional statement is a single<br />
statement; in the latter case use braces in both branches:<br />
<br />
if (condition) {<br />
do_this();<br />
do_that();<br />
} else {<br />
otherwise();<br />
}<br />
<br />
=== Spaces ===<br />
<br />
Linux kernel style for use of spaces depends (mostly) on<br />
function-versus-keyword usage. Use a space after (most) keywords. The<br />
notable exceptions are sizeof, typeof, alignof, and __attribute__, which look<br />
somewhat like functions (and are usually used with parentheses in Linux,<br />
although they are not required in the language, as in: &quot;sizeof info&quot; after<br />
&quot;struct fileinfo info;&quot; is declared).<br />
<br />
So use a space after these keywords:<br />
if, switch, case, for, do, while<br />
but not with sizeof, typeof, alignof, or __attribute__. E.g.,<br />
s = sizeof(struct file);<br />
<br />
Do not add spaces around (inside) parenthesized expressions. This example is<br />
*bad*:<br />
<br />
s = sizeof( struct file );<br />
<br />
When declaring pointer data or a function that returns a pointer type, the<br />
preferred use of '*' is adjacent to the data name or function name and not<br />
adjacent to the type name. Examples:<br />
<br />
char *linux_banner;<br />
unsigned long long memparse(char *ptr, char **retptr);<br />
char *match_strdup(substring_t *s);<br />
<br />
Use one space around (on each side of) most binary and ternary operators,<br />
such as any of these:<br />
<br />
= + - &lt; &gt; * / % | &amp; ^ &lt;= &gt;= == != ? :<br />
<br />
but no space after unary operators:<br />
&amp; * + - ~ ! sizeof typeof alignof __attribute__ defined<br />
<br />
no space before the postfix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
no space after the prefix increment &amp; decrement unary operators:<br />
++ --<br />
<br />
and no space around the '.' and &quot;-&gt;&quot; structure member operators.<br />
<br />
Do not leave trailing whitespace at the ends of lines. Some editors with<br />
&quot;smart&quot; indentation will insert whitespace at the beginning of new lines as<br />
appropriate, so you can start typing the next line of code right away.<br />
However, some such editors do not remove the whitespace if you end up not<br />
putting a line of code there, such as if you leave a blank line. As a result,<br />
you end up with lines containing trailing whitespace.<br />
<br />
Git will warn you about patches that introduce trailing whitespace, and can<br />
optionally strip the trailing whitespace for you; however, if applying a series<br />
of patches, this may make later patches in the series fail by changing their<br />
context lines.<br />
<br />
<br />
== Naming ==<br />
<br />
C is a Spartan language, and so should your naming be. Unlike Modula-2<br />
and Pascal programmers, C programmers do not use cute names like<br />
ThisVariableIsATemporaryCounter. A C programmer would call that<br />
variable &quot;tmp&quot;, which is much easier to write, and not the least more<br />
difficult to understand.<br />
<br />
HOWEVER, while mixed-case names are frowned upon, descriptive names for<br />
global variables are a must. To call a global function &quot;foo&quot; is a<br />
shooting offense.<br />
<br />
GLOBAL variables (to be used only if you _really_ need them) need to<br />
have descriptive names, as do global functions. If you have a function<br />
that counts the number of active users, you should call that<br />
&quot;count_active_users()&quot; or similar, you should _not_ call it &quot;cntusr()&quot;.<br />
<br />
Encoding the type of a function into the name (so-called Hungarian<br />
notation) is brain damaged - the compiler knows the types anyway and can<br />
check those, and it only confuses the programmer. No wonder MicroSoft<br />
makes buggy programs.<br />
<br />
LOCAL variable names should be short, and to the point. If you have<br />
some random integer loop counter, it should probably be called &quot;i&quot;.<br />
Calling it &quot;loop_counter&quot; is non-productive, if there is no chance of it<br />
being mis-understood. Similarly, &quot;tmp&quot; can be just about any type of<br />
variable that is used to hold a temporary value.<br />
<br />
If you are afraid to mix up your local variable names, you have another<br />
problem, which is called the function-growth-hormone-imbalance syndrome.<br />
See chapter 6 (Functions).<br />
<br />
<br />
== Typedefs ==<br />
<br />
Please don't use things like &quot;vps_t&quot;.<br />
<br />
It's a _mistake_ to use typedef for structures and pointers. When you see a<br />
<br />
vps_t a;<br />
<br />
in the source, what does it mean?<br />
<br />
In contrast, if it says<br />
<br />
struct virtual_container *a;<br />
<br />
you can actually tell what &quot;a&quot; is.<br />
<br />
Lots of people think that typedefs &quot;help readability&quot;. Not so. They are<br />
useful only for:<br />
<br />
(a) totally opaque objects (where the typedef is actively used to _hide_<br />
what the object is).<br />
<br />
Example: &quot;pte_t&quot; etc. opaque objects that you can only access using<br />
the proper accessor functions.<br />
<br />
NOTE! Opaqueness and &quot;accessor functions&quot; are not good in themselves.<br />
The reason we have them for things like pte_t etc. is that there<br />
really is absolutely _zero_ portably accessible information there.<br />
<br />
(b) Clear integer types, where the abstraction _helps_ avoid confusion<br />
whether it is &quot;int&quot; or &quot;long&quot;.<br />
<br />
u8/u16/u32 are perfectly fine typedefs, although they fit into<br />
category (d) better than here.<br />
<br />
NOTE! Again - there needs to be a _reason_ for this. If something is<br />
&quot;unsigned long&quot;, then there's no reason to do<br />
<br />
typedef unsigned long myflags_t;<br />
<br />
but if there is a clear reason for why it under certain circumstances<br />
might be an &quot;unsigned int&quot; and under other configurations might be<br />
&quot;unsigned long&quot;, then by all means go ahead and use a typedef.<br />
<br />
(c) when you use sparse to literally create a _new_ type for<br />
type-checking.<br />
<br />
(d) New types which are identical to standard C99 types, in certain<br />
exceptional circumstances.<br />
<br />
Although it would only take a short amount of time for the eyes and<br />
brain to become accustomed to the standard types like 'uint32_t',<br />
some people object to their use anyway.<br />
<br />
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their<br />
signed equivalents which are identical to standard types are<br />
permitted -- although they are not mandatory in new code of your<br />
own.<br />
<br />
When editing existing code which already uses one or the other set<br />
of types, you should conform to the existing choices in that code.<br />
<br />
(e) Types safe for use in userspace.<br />
<br />
In certain structures which are visible to userspace, we cannot<br />
require C99 types and cannot use the 'u32' form above. Thus, we<br />
use __u32 and similar types in all structures which are shared<br />
with userspace.<br />
<br />
Maybe there are other cases too, but the rule should basically be to NEVER<br />
EVER use a typedef unless you can clearly match one of those rules.<br />
<br />
In general, a pointer, or a struct that has elements that can reasonably<br />
be directly accessed should _never_ be a typedef.<br />
<br />
<br />
== Functions ==<br />
<br />
Functions should be short and sweet, and do just one thing. They should<br />
fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,<br />
as we all know), and do one thing and do that well.<br />
<br />
The maximum length of a function is inversely proportional to the<br />
complexity and indentation level of that function. So, if you have a<br />
conceptually simple function that is just one long (but simple)<br />
case-statement, where you have to do lots of small things for a lot of<br />
different cases, it's OK to have a longer function.<br />
<br />
However, if you have a complex function, and you suspect that a<br />
less-than-gifted first-year high-school student might not even<br />
understand what the function is all about, you should adhere to the<br />
maximum limits all the more closely. Use helper functions with<br />
descriptive names (you can ask the compiler to in-line them if you think<br />
it's performance-critical, and it will probably do a better job of it<br />
than you would have done).<br />
<br />
Another measure of the function is the number of local variables. They<br />
shouldn't exceed 5-10, or you're doing something wrong. Re-think the<br />
function, and split it into smaller pieces. A human brain can<br />
generally easily keep track of about 7 different things, anything more<br />
and it gets confused. You know you're brilliant, but maybe you'd like<br />
to understand what you did 2 weeks from now.<br />
<br />
In source files, separate functions with one blank line. If the function is<br />
exported, the EXPORT* macro for it should follow immediately after the closing<br />
function brace line. E.g.:<br />
<br />
int system_is_up(void)<br />
{<br />
return system_state == SYSTEM_RUNNING;<br />
}<br />
EXPORT_SYMBOL(system_is_up);<br />
<br />
In function prototypes, include parameter names with their data types.<br />
Although this is not required by the C language, it is preferred in Linux<br />
because it is a simple way to add valuable information for the reader.<br />
<br />
<br />
== Centralized exiting of functions ==<br />
<br />
Albeit deprecated by some people, the equivalent of the goto statement is<br />
used frequently by compilers in form of the unconditional jump instruction.<br />
<br />
The goto statement comes in handy when a function exits from multiple<br />
locations and some common work such as cleanup has to be done. If there is no<br />
cleanup needed then just return directly.<br />
<br />
The rationale is:<br />
<br />
- unconditional statements are easier to understand and follow<br />
- nesting is reduced<br />
- errors by not updating individual exit points when making<br />
modifications are prevented<br />
- saves the compiler work to optimize redundant code away ;)<br />
<br />
int fun(int a)<br />
{<br />
int result = 0;<br />
char *buffer = kmalloc(SIZE);<br />
<br />
if (buffer == NULL)<br />
return -ENOMEM;<br />
<br />
if (condition1) {<br />
while (loop1) {<br />
...<br />
}<br />
result = 1;<br />
goto out;<br />
}<br />
...<br />
out:<br />
kfree(buffer);<br />
return result;<br />
}<br />
<br />
== Commenting ==<br />
<br />
Comments are good, but there is also a danger of over-commenting. NEVER<br />
try to explain HOW your code works in a comment: it's much better to<br />
write the code so that the _working_ is obvious, and it's a waste of<br />
time to explain badly written code.<br />
<br />
Generally, you want your comments to tell WHAT your code does, not HOW.<br />
Also, try to avoid putting comments inside a function body: if the<br />
function is so complex that you need to separately comment parts of it,<br />
you should probably go back to chapter 6 for a while. You can make<br />
small comments to note or warn about something particularly clever (or<br />
ugly), but try to avoid excess. Instead, put the comments at the head<br />
of the function, telling people what it does, and possibly WHY it does<br />
it.<br />
<br />
When commenting the kernel API functions, please use the kernel-doc format.<br />
See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc<br />
for details.<br />
<br />
coreboot style for comments is the C89 &quot;/* ... */&quot; style.<br />
You may use C99-style &quot;// ...&quot; comments.<br />
<br />
The preferred style for long (multi-line) comments is:<br />
<br />
/*<br />
* This is the preferred style for multi-line<br />
* comments in the Linux kernel source code.<br />
* Please use it consistently.<br />
*<br />
* Description: A column of asterisks on the left side,<br />
* with beginning and ending almost-blank lines.<br />
*/<br />
<br />
For files in net/ and drivers/net/ the preferred style for long (multi-line)<br />
comments is a little different.<br />
<br />
/* The preferred comment style for files in net/ and drivers/net<br />
* looks like this.<br />
*<br />
* It is nearly the same as the generally preferred comment style,<br />
* but there is no initial almost-blank line.<br />
*/<br />
<br />
It's also important to comment data, whether they are basic types or derived<br />
types. To this end, use just one data declaration per line (no commas for<br />
multiple data declarations). This leaves you room for a small comment on each<br />
item, explaining its use.<br />
<br />
<br />
== You've made a mess of it ==<br />
<br />
That's OK, we all do. You've probably been told by your long-time Unix<br />
user helper that &quot;GNU emacs&quot; automatically formats the C sources for<br />
you, and you've noticed that yes, it does do that, but the defaults it<br />
uses are less than desirable (in fact, they are worse than random<br />
typing - an infinite number of monkeys typing into GNU emacs would never<br />
make a good program).<br />
<br />
So, you can either get rid of GNU emacs, or change it to use saner<br />
values. To do the latter, you can stick the following in your .emacs file:<br />
<br />
(defun c-lineup-arglist-tabs-only (ignored)<br />
&quot;Line up argument lists by tabs, not spaces&quot;<br />
(let* ((anchor (c-langelem-pos c-syntactic-element))<br />
(column (c-langelem-2nd-pos c-syntactic-element))<br />
(offset (- (1+ column) anchor))<br />
(steps (floor offset c-basic-offset)))<br />
(* (max steps 1)<br />
c-basic-offset)))<br />
<br />
(add-hook 'c-mode-common-hook<br />
(lambda ()<br />
;; Add kernel style<br />
(c-add-style<br />
&quot;linux-tabs-only&quot;<br />
'(&quot;linux&quot; (c-offsets-alist<br />
(arglist-cont-nonempty<br />
c-lineup-gcc-asm-reg<br />
c-lineup-arglist-tabs-only))))))<br />
<br />
(add-hook 'c-mode-hook<br />
(lambda ()<br />
(let ((filename (buffer-file-name)))<br />
;; Enable kernel mode for the appropriate files<br />
(when (and filename<br />
(string-match (expand-file-name &quot;~/src/linux-trees&quot;)<br />
filename))<br />
(setq indent-tabs-mode t)<br />
(c-set-style &quot;linux-tabs-only&quot;)))))<br />
<br />
This will make emacs go better with the kernel coding style for C<br />
files below ~/src/linux-trees.<br />
<br />
But even if you fail in getting emacs to do sane formatting, not<br />
everything is lost: use &quot;indent&quot;.<br />
<br />
Now, again, GNU indent has the same brain-dead settings that GNU emacs<br />
has, which is why you need to give it a few command line options.<br />
However, that's not too bad, because even the makers of GNU indent<br />
recognize the authority of K&amp;R (the GNU people aren't evil, they are<br />
just severely misguided in this matter), so you just give indent the<br />
options &quot;-kr -i8&quot; (stands for &quot;K&amp;R, 8 character indents&quot;), or use<br />
&quot;scripts/Lindent&quot;, which indents in the latest style.<br />
<br />
&quot;indent&quot; has a lot of options, and especially when it comes to comment<br />
re-formatting you may want to take a look at the man page. But<br />
remember: &quot;indent&quot; is not a fix for bad programming.<br />
<br />
<br />
== Kconfig configuration files ==<br />
<br />
For all of the Kconfig* configuration files throughout the source tree,<br />
the indentation is somewhat different. Lines under a &quot;config&quot; definition<br />
are indented with one tab, while help text is indented an additional two<br />
spaces. Example:<br />
<br />
config AUDIT<br />
bool &quot;Auditing support&quot;<br />
depends on NET<br />
help<br />
Enable auditing infrastructure that can be used with another<br />
kernel subsystem, such as SELinux (which requires this for<br />
logging of avc messages output). Does not do system-call<br />
auditing without CONFIG_AUDITSYSCALL.<br />
<br />
Seriously dangerous features (such as write support for certain<br />
filesystems) should advertise this prominently in their prompt string:<br />
<br />
config ADFS_FS_RW<br />
bool &quot;ADFS write support (DANGEROUS)&quot;<br />
depends on ADFS_FS<br />
...<br />
<br />
For full documentation on the configuration files, see the file<br />
Documentation/kbuild/kconfig-language.txt.<br />
<br />
<br />
== Data structures ==<br />
<br />
Data structures that have visibility outside the single-threaded<br />
environment they are created and destroyed in should always have<br />
reference counts. In the kernel, garbage collection doesn't exist (and<br />
outside the kernel garbage collection is slow and inefficient), which<br />
means that you absolutely _have_ to reference count all your uses.<br />
<br />
Reference counting means that you can avoid locking, and allows multiple<br />
users to have access to the data structure in parallel - and not having<br />
to worry about the structure suddenly going away from under them just<br />
because they slept or did something else for a while.<br />
<br />
Note that locking is _not_ a replacement for reference counting.<br />
Locking is used to keep data structures coherent, while reference<br />
counting is a memory management technique. Usually both are needed, and<br />
they are not to be confused with each other.<br />
<br />
Many data structures can indeed have two levels of reference counting,<br />
when there are users of different &quot;classes&quot;. The subclass count counts<br />
the number of subclass users, and decrements the global count just once<br />
when the subclass count goes to zero.<br />
<br />
Examples of this kind of &quot;multi-level-reference-counting&quot; can be found in<br />
memory management (&quot;struct mm_struct&quot;: mm_users and mm_count), and in<br />
filesystem code (&quot;struct super_block&quot;: s_count and s_active).<br />
<br />
Remember: if another thread can find your data structure, and you don't<br />
have a reference count on it, you almost certainly have a bug.<br />
<br />
<br />
== Macros, Enums and RTL ==<br />
<br />
Names of macros defining constants and labels in enums are capitalized.<br />
<br />
#define CONSTANT 0x12345<br />
<br />
Enums are preferred when defining several related constants.<br />
<br />
CAPITALIZED macro names are appreciated but macros resembling functions<br />
may be named in lower case.<br />
<br />
Generally, inline functions are preferable to macros resembling functions.<br />
<br />
Macros with multiple statements should be enclosed in a do - while block:<br />
<br />
#define macrofun(a, b, c) \<br />
do { \<br />
if (a == 5) \<br />
do_this(b, c); \<br />
} while (0)<br />
<br />
Things to avoid when using macros:<br />
<br />
1) macros that affect control flow:<br />
<br />
#define FOO(x) \<br />
do { \<br />
if (blah(x) &lt; 0) \<br />
return -EBUGGERED; \<br />
} while(0)<br />
<br />
is a _very_ bad idea. It looks like a function call but exits the &quot;calling&quot;<br />
function; don't break the internal parsers of those who will read the code.<br />
<br />
2) macros that depend on having a local variable with a magic name:<br />
<br />
#define FOO(val) bar(index, val)<br />
<br />
might look like a good thing, but it's confusing as hell when one reads the<br />
code and it's prone to breakage from seemingly innocent changes.<br />
<br />
3) macros with arguments that are used as l-values: FOO(x) = y; will<br />
bite you if somebody e.g. turns FOO into an inline function.<br />
<br />
4) forgetting about precedence: macros defining constants using expressions<br />
must enclose the expression in parentheses. Beware of similar issues with<br />
macros using parameters.<br />
<br />
#define CONSTANT 0x4000<br />
#define CONSTEXP (CONSTANT | 3)<br />
<br />
The cpp manual deals with macros exhaustively. The gcc internals manual also<br />
covers RTL which is used frequently with assembly language in the kernel.<br />
<br />
<br />
== Printing kernel messages ==<br />
<br />
Kernel developers like to be seen as literate. Do mind the spelling<br />
of kernel messages to make a good impression. Do not use crippled<br />
words like &quot;dont&quot;; use &quot;do not&quot; or &quot;don't&quot; instead. Make the messages<br />
concise, clear, and unambiguous.<br />
<br />
Kernel messages do not have to be terminated with a period.<br />
<br />
Printing numbers in parentheses (%d) adds no value and should be avoided.<br />
<br />
There are a number of driver model diagnostic macros in &lt;linux/device.h&gt;<br />
which you should use to make sure messages are matched to the right device<br />
and driver, and are tagged with the right level: dev_err(), dev_warn(),<br />
dev_info(), and so forth. For messages that aren't associated with a<br />
particular device, &lt;linux/printk.h&gt; defines pr_debug() and pr_info().<br />
<br />
Coming up with good debugging messages can be quite a challenge; and once<br />
you have them, they can be a huge help for remote troubleshooting. Such<br />
messages should be compiled out when the DEBUG symbol is not defined (that<br />
is, by default they are not included). When you use dev_dbg() or pr_debug(),<br />
that's automatic. Many subsystems have Kconfig options to turn on -DDEBUG.<br />
A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to the<br />
ones already enabled by DEBUG.<br />
<br />
<br />
== Allocating memory ==<br />
<br />
The kernel provides the following general purpose memory allocators:<br />
kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and<br />
vzalloc(). Please refer to the API documentation for further information<br />
about them.<br />
<br />
The preferred form for passing a size of a struct is the following:<br />
<br />
p = kmalloc(sizeof(*p), ...);<br />
<br />
The alternative form where struct name is spelled out hurts readability and<br />
introduces an opportunity for a bug when the pointer variable type is changed<br />
but the corresponding sizeof that is passed to a memory allocator is not.<br />
<br />
Casting the return value which is a void pointer is redundant. The conversion<br />
from void pointer to any other pointer type is guaranteed by the C programming<br />
language.<br />
<br />
The preferred form for allocating an array is the following:<br />
<br />
p = kmalloc_array(n, sizeof(...), ...);<br />
<br />
The preferred form for allocating a zeroed array is the following:<br />
<br />
p = kcalloc(n, sizeof(...), ...);<br />
<br />
Both forms check for overflow on the allocation size n * sizeof(...),<br />
and return NULL if that occurred.<br />
<br />
<br />
== The inline disease ==<br />
<br />
There appears to be a common misperception that gcc has a magic &quot;make me<br />
faster&quot; speedup option called &quot;inline&quot;. While the use of inlines can be<br />
appropriate (for example as a means of replacing macros, see Chapter 12), it<br />
very often is not. Abundant use of the inline keyword leads to a much bigger<br />
kernel, which in turn slows the system as a whole down, due to a bigger<br />
icache footprint for the CPU and simply because there is less memory<br />
available for the pagecache. Just think about it; a pagecache miss causes a<br />
disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles<br />
that can go into these 5 milliseconds.<br />
<br />
A reasonable rule of thumb is to not put inline at functions that have more<br />
than 3 lines of code in them. An exception to this rule are the cases where<br />
a parameter is known to be a compiletime constant, and as a result of this<br />
constantness you *know* the compiler will be able to optimize most of your<br />
function away at compile time. For a good example of this later case, see<br />
the kmalloc() inline function.<br />
<br />
Often people argue that adding inline to functions that are static and used<br />
only once is always a win since there is no space tradeoff. While this is<br />
technically correct, gcc is capable of inlining these automatically without<br />
help, and the maintenance issue of removing the inline when a second user<br />
appears outweighs the potential value of the hint that tells gcc to do<br />
something it would have done anyway.<br />
<br />
<br />
== Function return values and names ==<br />
<br />
Functions can return values of many different kinds, and one of the<br />
most common is a value indicating whether the function succeeded or<br />
failed. Such a value can be represented as an error-code integer<br />
(-Exxx = failure, 0 = success) or a &quot;succeeded&quot; boolean (0 = failure,<br />
non-zero = success).<br />
<br />
Mixing up these two sorts of representations is a fertile source of<br />
difficult-to-find bugs. If the C language included a strong distinction<br />
between integers and booleans then the compiler would find these mistakes<br />
for us... but it doesn't. To help prevent such bugs, always follow this<br />
convention:<br />
<br />
If the name of a function is an action or an imperative command,<br />
the function should return an error-code integer. If the name<br />
is a predicate, the function should return a &quot;succeeded&quot; boolean.<br />
<br />
For example, &quot;add work&quot; is a command, and the add_work() function returns 0<br />
for success or -EBUSY for failure. In the same way, &quot;PCI device present&quot; is<br />
a predicate, and the pci_dev_present() function returns 1 if it succeeds in<br />
finding a matching device or 0 if it doesn't.<br />
<br />
All EXPORTed functions must respect this convention, and so should all<br />
public functions. Private (static) functions need not, but it is<br />
recommended that they do.<br />
<br />
Functions whose return value is the actual result of a computation, rather<br />
than an indication of whether the computation succeeded, are not subject to<br />
this rule. Generally they indicate failure by returning some out-of-range<br />
result. Typical examples would be functions that return pointers; they use<br />
NULL or the ERR_PTR mechanism to report failure.<br />
<br />
<br />
== Don't re-invent the kernel macros ==<br />
<br />
The header file include/linux/kernel.h contains a number of macros that<br />
you should use, rather than explicitly coding some variant of them yourself.<br />
For example, if you need to calculate the length of an array, take advantage<br />
of the macro<br />
<br />
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))<br />
<br />
Similarly, if you need to calculate the size of some structure member, use<br />
<br />
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)-&gt;f))<br />
<br />
There are also min() and max() macros that do strict type checking if you<br />
need them. Feel free to peruse that header file to see what else is already<br />
defined that you shouldn't reproduce in your code.<br />
<br />
<br />
== Editor modelines and other cruft ==<br />
<br />
Some editors can interpret configuration information embedded in source files,<br />
indicated with special markers. For example, emacs interprets lines marked<br />
like this:<br />
<br />
-*- mode: c -*-<br />
<br />
Or like this:<br />
<br />
/*<br />
Local Variables:<br />
compile-command: &quot;gcc -DMAGIC_DEBUG_FLAG foo.c&quot;<br />
End:<br />
*/<br />
<br />
Vim interprets markers that look like this:<br />
<br />
/* vim:set sw=8 noet */<br />
<br />
Do not include any of these in source files. People have their own personal<br />
editor configurations, and your source files should not override them. This<br />
includes markers for indentation and mode configuration. People may use their<br />
own custom mode, or may have some other magic method for making indentation<br />
work correctly.<br />
<br />
<br />
== Inline assembly ==<br />
<br />
In architecture-specific code, you may need to use inline assembly to interface<br />
with CPU or platform functionality. Don't hesitate to do so when necessary.<br />
However, don't use inline assembly gratuitously when C can do the job. You can<br />
and should poke hardware from C when possible.<br />
<br />
Consider writing simple helper functions that wrap common bits of inline<br />
assembly, rather than repeatedly writing them with slight variations. Remember<br />
that inline assembly can use C parameters.<br />
<br />
Large, non-trivial assembly functions should go in .S files, with corresponding<br />
C prototypes defined in C header files. The C prototypes for assembly<br />
functions should use &quot;asmlinkage&quot;.<br />
<br />
You may need to mark your asm statement as volatile, to prevent GCC from<br />
removing it if GCC doesn't notice any side effects. You don't always need to<br />
do so, though, and doing so unnecessarily can limit optimization.<br />
<br />
When writing a single inline assembly statement containing multiple<br />
instructions, put each instruction on a separate line in a separate quoted<br />
string, and end each string except the last with \n\t to properly indent the<br />
next instruction in the assembly output:<br />
<br />
asm (&quot;magic %reg1, #42\n\t&quot;<br />
&quot;more_magic %reg2, %reg3&quot;<br />
: /* outputs */ : /* inputs */ : /* clobbers */);<br />
<br />
<br />
<br />
== References ==<br />
<br />
The C Programming Language, Second Edition<br />
by Brian W. Kernighan and Dennis M. Ritchie.<br />
Prentice Hall, Inc., 1988.<br />
ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).<br />
URL: http://cm.bell-labs.com/cm/cs/cbook/<br />
<br />
The Practice of Programming<br />
by Brian W. Kernighan and Rob Pike.<br />
Addison-Wesley, Inc., 1999.<br />
ISBN 0-201-61586-X.<br />
URL: http://cm.bell-labs.com/cm/cs/tpop/<br />
<br />
GNU manuals - where in compliance with K&amp;R and this text - for cpp, gcc,<br />
gcc internals and indent, all available from http://www.gnu.org/manual/<br />
<br />
WG14 is the international standardization working group for the programming<br />
language C, URL: http://www.open-std.org/JTC1/SC22/WG14/<br />
<br />
Kernel CodingStyle, by greg@kroah.com at OLS 2002:<br />
http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/</div>Stepanhttp://www.coreboot.org/index.php?title=Easy_projects&diff=11799Easy projects2013-04-15T21:25:03Z<p>Stepan: /* Use CBFS wherever possible */</p>
<hr />
<div>You probably came here trying to find a small (minutes to hours) and easy task where you can get your hands dirty and get results immediately.<br />
<br />
If you're a coreboot or flashrom newbie, this page is for you.<br />
<br />
== coreboot ==<br />
<br />
<br />
=== AMD 740G information gathering ===<br />
<br />
(This project description is not finished yet)<br />
<br />
If you have a board with AMD 740G chipset, please run (as root)<br />
<br />
$ '''flashrom -V'''<br />
$ '''lspci -nnvvvxxxx'''<br />
$ '''superiotool -deV'''<br />
$ '''dmidecode'''<br />
<br />
and mail the output to the [[Mailinglist|coreboot mailing list]] together with the exact model number/name of your board.<br />
<br />
This helps us evaluate which boards are good targets for coreboot.<br />
<br />
Here are some boards:<br />
<br />
* http://www.czechcomputer.cz/cat_tree.jsp?bpath=Z%C3%A1kladn%C3%AD+desky\Socket+AM2%2B\AMD+740G<br />
<br />
=== Formatting and whitespace cleanup ===<br />
<br />
We try to maintain the code in the [[Development_Guidelines#Coding_Style Linux style]], but occasionally white-space and other formatting issues find their way into the project. Formatting and white-space changes should be done in small groups as a separate patch from code changes. Be careful running indent/lindent. The results are not always the right thing to do and require review.<br />
<br />
Ideally a check/test should be integrated into the build system pointing out these issues already when committing or testing the commit. Such tests probably already exist in other projects and just need to be copied.<br />
<br />
== Payloads ==<br />
<br />
coreboot can use a number of different [[Payloads|payloads]].<br />
<br />
=== Add/test new supported payloads ===<br />
<br />
* Test syslinux (probably requires [[SeaBIOS]] in addition, needs to be checked).<br />
* Port [[GPXE]] to &quot;native&quot; coreboot (it works fine together with [[SeaBIOS]] though).<br />
<br />
== flashrom ==<br />
<br />
The [http://www.flashrom.org flashrom] tool can read/write coreboot/BIOS images from/to flash chips.<br />
<br />
* See [http://flashrom.org/Easy_projects flashrom's Easy Projects] list for details.<br />
<br />
== Other ==<br />
<br />
* Add [http://tracker.coreboot.org/trac/coreboot/ticket/95 support for using coreboot in VirtualBox].</div>Stepanhttp://www.coreboot.org/index.php?title=Project_Ideas&diff=11651Project Ideas2013-03-27T00:36:17Z<p>Stepan: </p>
<hr />
<div>The following are some ideas that have come up in the community. Some are more or less suitable for [[GSoC]] and prospective students' application should expand on some ideas and pair back others.<br />
<br />
== Linux Firmware Kit, BITS ==<br />
<br />
There are various test suites for firmware aspects, esp. those that interacts with the operating systems. Unfortunately, some of these projects are dead, some seem to be forked and developed semi-publically, and having all that stuff in lots of different places is a big hassle.<br />
<br />
The goal of this project is to pick up the pieces, and create a single tool (most likely a bootable CD/USB drive image) that can be booted on vendor BIOS (for the Red Hat and Canonical developers that work on these) as well as coreboot (preferably seabios and FILO to improve testability - is an issue created/fixed by coreboot or seabios?). This can then be improved in various ways.<br />
<br />
There's also intel-gpu-tools that might have some useful tests (at least for intel-boards): http://article.gmane.org/gmane.comp.video.dri.devel/63948<br />
<br />
When applying for this task, please state in your proposal what you think might be worthy extensions to the existing tests.<br />
<br />
Required knowledge for this task: Minimal coreboot and firmware experience, but you should have some idea of the boot process of a Linux system (as these test suites are mostly Linux based). GSoC probably won't provide enough time to learn all that (Linux boot process, firmware interfaces such as ACPI) and still develop the tools in some useful way.<br />
<br />
'''Links'''<br />
* https://wiki.ubuntu.com/Kernel/Reference/fwts<br />
* http://biosbits.org/ <br />
* http://linuxfirmwarekit.org/<br />
* [[Supported Motherboards]]<br />
<br />
'''Mentors'''<br />
* [[User:MJones|Marc Jones]]<br />
<br />
== Infrastructure for automatic code checking ==<br />
We already have a build bot that builds various configurations of coreboot. It would be nice to extend it with various code validation routines, for example:<br />
* Validate that there's no regression in doxygen documentation (eg. are all arguments to functions still explained in @param tags, eg. after new arguments were added?)<br />
* Make code lint clean (and maybe extend lint to not fall into our traps), and run lint over the tree. Report regressions<br />
* Use LLVM's static code checking facilities, report regressions.<br />
<br />
'''Links'''<br />
* LLVM tools: [http://clang.llvm.org/StaticAnalysis.html Clang static analyser], [http://llvm.org/ProjectsWithLLVM/#Calysto SSA assertion checker], http://klee.llvm.org/<br />
* Lint tools: [http://lclint.cs.virginia.edu/ Splint]<br />
* Semantic Tester: https://code.google.com/p/c-semantics/<br />
* [http://frama-c.com/ Frama-C]<br />
<br />
'''Mentors'''<br />
* [[User:Stepan|Stefan Reinauer]], [[User:PatrickGeorgi|Patrick Georgi]]<br />
<br />
== Implement coreboot features for more boards ==<br />
A lot of cool coreboot features are only available for a subset of the supported mainboards:<br />
* global variables in romstage<br />
* relocatable ramstage<br />
* cbmem console<br />
* timestamps<br />
<br />
This project would analyze how to bring those features forward to more boards and work on doing so.<br />
<br />
'''Mentors'''<br />
* [[User:Stepan|Stefan Reinauer]]<br />
<br />
== coreboot test suite ==<br />
Create a test suite to gather and report coreboot mainboard and payload settings. This project may leverage libpayload, coreinfo, memtest86, BITS, and other tools like benchmarks for CPU and RAM performance. Konstantin Aladyshev reported according to the benchmark [http://www.cs.virginia.edu/stream/ STREAM], RAM access on his system with coreboot is four times slower than with the proprietary vendor BIOS. Such issues should be easily spotted with the test suite.<br />
<br />
The suite should gather result and report them at summary and detailed levels. The goal is to help coreboot developers identify problems and to test coreboot features. This project should work closely with the testing rig and test reporting projects. It is important the the student considers how testing and reporting can be extended as features and tests are added in the future.<br />
<br />
'''Links'''<br />
* [http://biosbits.org/ BITS]<br />
* [[Supported Motherboards]]<br />
<br />
'''Mentors'''<br />
* [[User:MJones|Marc Jones]], [[User:PatrickGeorgi|Patrick Georgi]]<br />
<br />
== coreboot cheap testing rig ==<br />
The goal of this project is to create a cheap testing rig which works with the existing board test infrastructure. We have a hardware test system since 2006:<br />
* [http://www.coresystems.de/PDFs/LinuxBIOS-testing/Slides-LinuxBIOS-QA.pdf Quality Assurance Talk (Slides)]<br />
* [http://www.coresystems.de/PDFs/LinuxBIOS-testing/TestIntegrationManual.pdf Test Integration Manual]<br />
* [http://www.coresystems.de/PDFs/LinuxBIOS-testing/DevelopersManual.pdf Test Developers Manual]<br />
* [http://www.coresystems.de/PDFs/LinuxBIOS-testing/TestSpecification.pdf Test Specification]<br />
<br />
The initial version of our testing rig used a remote power switch and was rather expensive. With cheaper technologies such as X10, it's possible to drop the testing costs per board significantly.<br />
<br />
'''Links'''<br />
* [[InSystemFlasher]] is a cheap DIY hardware prototype for building an automated testing rig for modern SPI-based boards. This could be used as a starting point.<br />
<br />
'''Mentors'''<br />
* [[User:Stepan|Stefan Reinauer]]<br />
<br />
== coreboot mainboard test result reporting ==<br />
One of the biggest challenges in coreboot is support many systems in the same codebase. As systems age and coreboot continues to develop, the condition of mainboards becomes unknown. This project would define a coreboot test results reporting mechanism, gather data, and report passing and failing systems on a webpage. This project would work closely with the coreboot test suite project and/or the hardware test rig project. A good example of test results gathering and reporting is done by the Phoronix/Openbenchmark. The student should investigate other test and reporting solutions to leverage the best options for coreboot. It is important the the student considers how testing and reporting can be extended as features and tests are added in the future.<br />
<br />
'''Links'''<br />
* http://openbenchmarking.org/<br />
* http://www.coreboot.org/Supported_Motherboards<br />
<br />
'''Mentors'''<br />
* [[User:Stepan|Stefan Reinauer]]<br />
* [[User:MJones|Marc Jones]]<br />
<br />
<br />
== coreboot ports for mainboards == <br />
Identify potential mainboards to port based on the recently release cpu and chipset support. The goal would be to support publicly available platforms with a number of payloads and operating systems.<br />
<br />
'''Mentors'''<br />
<br />
* [[User:ruik|Rudolf Marek]]<br />
<br />
== Tianocore as payload ==<br />
<br />
What SeaBIOS is for PC-BIOS interfaces, Tianocore is for UEFI - in fact, it's the reference implementation that most commercial UEFIs are built on. While coreboot favors other design goals than UEFI, it's really useful to support this standard that's being pushed on the market, just like SeaBIOS really helped coreboot by providing a BIOS &quot;frontend&quot;.<br />
<br />
There's already some code, but there's still much room for improvement: A graphics driver that uses a preinitialized (by coreboot) framebuffer. A CBFS driver so Tiano can access coreboot flash storage. Based on that, a flash driver (maybe adapted from flashrom) to implement non-volatile variable storage by writing to flash.<br />
<br />
Possible tasks depend a lot on existing knowledge of the candidate. Few of the tasks are large enough to fill the entire GSoC time frame with one of them. Feel free to discuss with us on IRC what a suitable target could be for you.<br />
<br />
'''Links'''<br />
* http://www.tianocore.org/<br />
* https://github.com/pgeorgi/edk2/tree/coreboot-pkg<br />
<br />
<br />
'''Mentors'''<br />
* [[User:Stepan|Stefan Reinauer]]<br />
* [[User:PatrickGeorgi|Patrick Georgi]]<br />
<br />
<br />
== coreboot ACPI 4.0 and S3 power management support ==<br />
coreboot has support for ACPI tables and S3 support for some platforms, but it is very mainboard specific and moslty based on ACPI 2.0. Create a generic solution for ACPI 4.0 table generation and S3 support.<br />
<br />
'''Mentors'''<br />
*<br />
<br />
<br />
==coreboot port to ARM SOC's with PCIe==<br />
<br />
[http://www.xilinx.com/products/silicon-devices/epp/zynq-7000/index.htm Xilinx Zynq-7030]<br />
<br />
[http://www.altera.com/devices/fpga/cyclone-v-fpgas/hard-processor-system/cyv-soc-hps.html Altera Cyclone V ]<br />
<br />
[http://www.st.com/internet/mcu/product/251211.jsp ST spear1340]<br />
<br />
<br />
[[ARM]] SOC's with PCIe are available. These systems can take advantage of coreboot's strength in properly configuring PCI devices, fast boot time and payload support.<br />
<br />
Note that coreboot has in the past supported three different CPUs (x86, Alpha, PPC), so the structure is there for adding in a new processor family. <br />
We will need to find the right platform to do the work, but I (Ron) can provide a board and JTAG debugger if needed. <br />
<br />
There was an ARM project started in 2011. <br />
<br />
http://blogs.coreboot.org/blog/2011/05/11/gsoc2011-project-porting-coreboot-to-arm-architecture/<br />
<br />
'''Mentors'''<br />
* Bari Ari<br />
* [[User:Rminnich|Ron Minnich]]<br />
* [[User:Jason Wang|QingPei Wang]]<br />
<br />
== coreboot panic room ==<br />
<br />
Create a safe boot solution for coreboot to easily and cheaply recover the system. <br />
<br />
The basic idea is that the system flash image always contains executable for SerialICE. Instead of loading a coreboot romstage, firmware can boot to SerialICE based on some GPIO state, a keypress sequence or a logged failure on earlier boots. It is possible to integrate this into the coreboot build tree as a bootblock option, in the same spot as the fallback/normal switch and the simple loader.<br />
<br />
Having this capability opens up new possibilities:<br />
<br />
During the lifetime of a mainboard, new requirements for ACPI hacks and CPU microcodes introduce the need to update boot firmware at customer site. The firmware shall have recovery path against any failures during the firmware update process. The most straight-forward solution is to do intelligent allocation of files in the CBFS such that files critical to the recovery are located on write-protected pages. The recovery path shall require only an USB mass-storage with compatible filesystem (ext2, fat32).<br />
<br />
The ability to dual-boot reduces the amount of tools required to reverse-engineer proprietary BIOS on ports for new mainboards. It is increasingly common that the flash chips are a) not socketed or b) physically hard to access (laptops). Even if chipset support existed already for a board, there are a lot of configuration registers for PCI-e links and GPIO signals that are difficult to get right by code disassembly only. With panic room implementation there would be no need to use external programmers or flashchip hot-swap method to alternate between SerialICE (for proprietary BIOS) and coreboot romstage boots.<br />
<br />
SerialICE requires minimal hardware resources and does not require installed RAM or display hardware. It could be used as the first power-on environment after mainboard PCB verification and assembly to verify integrated components enumerate correctly. At the end of this first power-on, actual board firmware can be programmed without the need for external programmers and SOIC-8 clips, as the SPI controller embedded in the chipset can be used instead. As setting up EHCI debug port console is fairly simple across different chipsets, it can be used to print detailed diagnostics instead of POST codes on LPC bus.<br />
<br />
<br />
GSoC 2011 project [http://blogs.coreboot.org/blog/2011/05/09/gsoc-project-coreboot-panic-room-diagnostics-also-remote-flashing/] was able to:<br />
* Link flashrom with libpayload and flash from USB drive in a pre-OS environment.<br />
* Optimise flashrom memory usage to flash in pre-ram/cache-as-ram environment.<br />
* Build SerialICE boot ROM inside the coreboot tree and share some of the PnP/SuperIO source code.<br />
* Demonstrate booting alternative payload on keypress.<br />
<br />
<br />
There are remaining open tasks to:<br />
* Bring the GSoC 2011 patches up-to-date with current flashrom and libpayload trees.<br />
* Create generic solution to jump to recovery mode using input from GPIOs and/or use of power-button override.<br />
* Use SMBus/SMLink to send POST failure codes over ethernet using integrated network controllers.<br />
* After panic(), dump RAM contents before they are overwritten.<br />
<br />
<br />
'''Mentors'''<br />
* [[User:Rminnich|Ron Minnich]]<br />
<br />
== Board config infrastructure ==<br />
<br />
Design data structures that host information about the board layout so coreboot can better initialize components and generate all kinds of tables (mptable, pirq, acpi, ...) from that dynamically (at build or runtime, as appropriate). Adapt boards to use that instead of the current hardcodes.<br />
<br />
'''Links'''<br />
* ?<br />
<br />
'''Mentors'''<br />
* ?<br />
<br />
<br />
== Refactor AMD code ==<br />
<br />
AMD K8 and AMD Fam10 are different enough to have their own code. This is unfortunate, as you have to decide which CPU type you use in a given mainboard. Refactor AMD code so a single image can support both chip types on a given board. Also move tables from get_bus_conf and the like to the device tree or kconfig options (or runtime detection), as appropriate.<br />
<br />
Alternatively, figure out a way how to build them in parallel and have coreboot select the right one on runtime.<br />
<br />
'''Links'''<br />
* ?<br />
<br />
'''Mentors'''<br />
* [[User:Stepan|Stefan Reinauer]]<br />
<br />
<br />
== AMD VSA ==<br />
<br />
Get the source code of AMD's VSA compiled and working with an open source toolchain. Integrate the it into the current build system.<br />
<br />
'''Links'''<br />
* ?<br />
<br />
'''Mentors'''<br />
* ?</div>Stepanhttp://www.coreboot.org/index.php?title=Project_Ideas&diff=11650Project Ideas2013-03-27T00:30:21Z<p>Stepan: /* Infrastructure for automatic code checking */</p>
<hr />
<div>The following are some ideas that have come up in the community. Some are more or less suitable for [[GSoC]] and prospective students' application should expand on some ideas and pair back others.<br />
<br />
== Linux Firmware Kit, BITS ==<br />
<br />
There are various test suites for firmware aspects, esp. those that interacts with the operating systems. Unfortunately, some of these projects are dead, some seem to be forked and developed semi-publically, and having all that stuff in lots of different places is a big hassle.<br />
<br />
The goal of this project is to pick up the pieces, and create a single tool (most likely a bootable CD/USB drive image) that can be booted on vendor BIOS (for the Red Hat and Canonical developers that work on these) as well as coreboot (preferably seabios and FILO to improve testability - is an issue created/fixed by coreboot or seabios?). This can then be improved in various ways.<br />
<br />
There's also intel-gpu-tools that might have some useful tests (at least for intel-boards): http://article.gmane.org/gmane.comp.video.dri.devel/63948<br />
<br />
When applying for this task, please state in your proposal what you think might be worthy extensions to the existing tests.<br />
<br />
Required knowledge for this task: Minimal coreboot and firmware experience, but you should have some idea of the boot process of a Linux system (as these test suites are mostly Linux based). GSoC probably won't provide enough time to learn all that (Linux boot process, firmware interfaces such as ACPI) and still develop the tools in some useful way.<br />
<br />
'''Links'''<br />
* https://wiki.ubuntu.com/Kernel/Reference/fwts<br />
* http://biosbits.org/ <br />
* http://linuxfirmwarekit.org/<br />
* [[Supported Motherboards]]<br />
<br />
'''Mentors'''<br />
* [[User:MJones|Marc Jones]]<br />
<br />
== Infrastructure for automatic code checking ==<br />
We already have a build bot that builds various configurations of coreboot. It would be nice to extend it with various code validation routines, for example:<br />
* Validate that there's no regression in doxygen documentation (eg. are all arguments to functions still explained in @param tags, eg. after new arguments were added?)<br />
* Make code lint clean (and maybe extend lint to not fall into our traps), and run lint over the tree. Report regressions<br />
* Use LLVM's static code checking facilities, report regressions.<br />
<br />
'''Links'''<br />
* LLVM tools: [http://clang.llvm.org/StaticAnalysis.html Clang static analyser], [http://llvm.org/ProjectsWithLLVM/#Calysto SSA assertion checker], http://klee.llvm.org/<br />
* Lint tools: [http://lclint.cs.virginia.edu/ Splint]<br />
* Semantic Tester: https://code.google.com/p/c-semantics/<br />
* [http://frama-c.com/ Frama-C]<br />
<br />
'''Mentors'''<br />
* [[User:Stepan|Stefan Reinauer]], [[User:PatrickGeorgi|Patrick Georgi]]<br />
<br />
== coreboot test suite ==<br />
Create a test suite to gather and report coreboot mainboard and payload settings. This project may leverage libpayload, coreinfo, memtest86, BITS, and other tools like benchmarks for CPU and RAM performance. Konstantin Aladyshev reported according to the benchmark [http://www.cs.virginia.edu/stream/ STREAM], RAM access on his system with coreboot is four times slower than with the proprietary vendor BIOS. Such issues should be easily spotted with the test suite.<br />
<br />
The suite should gather result and report them at summary and detailed levels. The goal is to help coreboot developers identify problems and to test coreboot features. This project should work closely with the testing rig and test reporting projects. It is important the the student considers how testing and reporting can be extended as features and tests are added in the future.<br />
<br />
'''Links'''<br />
* [http://biosbits.org/ BITS]<br />
* [[Supported Motherboards]]<br />
<br />
'''Mentors'''<br />
* [[User:MJones|Marc Jones]], [[User:PatrickGeorgi|Patrick Georgi]]<br />
<br />
== coreboot cheap testing rig ==<br />
The goal of this project is to create a cheap testing rig which works with the existing board test infrastructure. We have a hardware test system since 2006:<br />
* [http://www.coresystems.de/PDFs/LinuxBIOS-testing/Slides-LinuxBIOS-QA.pdf Quality Assurance Talk (Slides)]<br />
* [http://www.coresystems.de/PDFs/LinuxBIOS-testing/TestIntegrationManual.pdf Test Integration Manual]<br />
* [http://www.coresystems.de/PDFs/LinuxBIOS-testing/DevelopersManual.pdf Test Developers Manual]<br />
* [http://www.coresystems.de/PDFs/LinuxBIOS-testing/TestSpecification.pdf Test Specification]<br />
<br />
The initial version of our testing rig used a remote power switch and was rather expensive. With cheaper technologies such as X10, it's possible to drop the testing costs per board significantly.<br />
<br />
'''Links'''<br />
* [[InSystemFlasher]] is a cheap DIY hardware prototype for building an automated testing rig for modern SPI-based boards. This could be used as a starting point.<br />
<br />
'''Mentors'''<br />
* [[User:Stepan|Stefan Reinauer]]<br />
<br />
== coreboot mainboard test result reporting ==<br />
One of the biggest challenges in coreboot is support many systems in the same codebase. As systems age and coreboot continues to develop, the condition of mainboards becomes unknown. This project would define a coreboot test results reporting mechanism, gather data, and report passing and failing systems on a webpage. This project would work closely with the coreboot test suite project and/or the hardware test rig project. A good example of test results gathering and reporting is done by the Phoronix/Openbenchmark. The student should investigate other test and reporting solutions to leverage the best options for coreboot. It is important the the student considers how testing and reporting can be extended as features and tests are added in the future.<br />
<br />
'''Links'''<br />
* http://openbenchmarking.org/<br />
* http://www.coreboot.org/Supported_Motherboards<br />
<br />
'''Mentors'''<br />
* [[User:Stepan|Stefan Reinauer]]<br />
* [[User:MJones|Marc Jones]]<br />
<br />
<br />
== coreboot ports for mainboards == <br />
Identify potential mainboards to port based on the recently release cpu and chipset support. The goal would be to support publicly available platforms with a number of payloads and operating systems.<br />
<br />
'''Mentors'''<br />
<br />
* [[User:ruik|Rudolf Marek]]<br />
<br />
== Tianocore as payload ==<br />
<br />
What SeaBIOS is for PC-BIOS interfaces, Tianocore is for UEFI - in fact, it's the reference implementation that most commercial UEFIs are built on. While coreboot favors other design goals than UEFI, it's really useful to support this standard that's being pushed on the market, just like SeaBIOS really helped coreboot by providing a BIOS &quot;frontend&quot;.<br />
<br />
There's already some code, but there's still much room for improvement: A graphics driver that uses a preinitialized (by coreboot) framebuffer. A CBFS driver so Tiano can access coreboot flash storage. Based on that, a flash driver (maybe adapted from flashrom) to implement non-volatile variable storage by writing to flash.<br />
<br />
Possible tasks depend a lot on existing knowledge of the candidate. Few of the tasks are large enough to fill the entire GSoC time frame with one of them. Feel free to discuss with us on IRC what a suitable target could be for you.<br />
<br />
'''Links'''<br />
* http://www.tianocore.org/<br />
* https://github.com/pgeorgi/edk2/tree/coreboot-pkg<br />
<br />
<br />
'''Mentors'''<br />
* [[User:Stepan|Stefan Reinauer]]<br />
* [[User:PatrickGeorgi|Patrick Georgi]]<br />
<br />
<br />
== coreboot ACPI 4.0 and S3 power management support ==<br />
coreboot has support for ACPI tables and S3 support for some platforms, but it is very mainboard specific and moslty based on ACPI 2.0. Create a generic solution for ACPI 4.0 table generation and S3 support.<br />
<br />
'''Mentors'''<br />
*<br />
<br />
<br />
==coreboot port to ARM SOC's with PCIe==<br />
<br />
[http://www.xilinx.com/products/silicon-devices/epp/zynq-7000/index.htm Xilinx Zynq-7030]<br />
<br />
[http://www.altera.com/devices/fpga/cyclone-v-fpgas/hard-processor-system/cyv-soc-hps.html Altera Cyclone V ]<br />
<br />
[http://www.st.com/internet/mcu/product/251211.jsp ST spear1340]<br />
<br />
<br />
[[ARM]] SOC's with PCIe are available. These systems can take advantage of coreboot's strength in properly configuring PCI devices, fast boot time and payload support.<br />
<br />
Note that coreboot has in the past supported three different CPUs (x86, Alpha, PPC), so the structure is there for adding in a new processor family. <br />
We will need to find the right platform to do the work, but I (Ron) can provide a board and JTAG debugger if needed. <br />
<br />
There was an ARM project started in 2011. <br />
<br />
http://blogs.coreboot.org/blog/2011/05/11/gsoc2011-project-porting-coreboot-to-arm-architecture/<br />
<br />
'''Mentors'''<br />
* Bari Ari<br />
* [[User:Rminnich|Ron Minnich]]<br />
* [[User:Jason Wang|QingPei Wang]]<br />
<br />
== coreboot panic room ==<br />
<br />
Create a safe boot solution for coreboot to easily and cheaply recover the system. <br />
<br />
The basic idea is that the system flash image always contains executable for SerialICE. Instead of loading a coreboot romstage, firmware can boot to SerialICE based on some GPIO state, a keypress sequence or a logged failure on earlier boots. It is possible to integrate this into the coreboot build tree as a bootblock option, in the same spot as the fallback/normal switch and the simple loader.<br />
<br />
Having this capability opens up new possibilities:<br />
<br />
During the lifetime of a mainboard, new requirements for ACPI hacks and CPU microcodes introduce the need to update boot firmware at customer site. The firmware shall have recovery path against any failures during the firmware update process. The most straight-forward solution is to do intelligent allocation of files in the CBFS such that files critical to the recovery are located on write-protected pages. The recovery path shall require only an USB mass-storage with compatible filesystem (ext2, fat32).<br />
<br />
The ability to dual-boot reduces the amount of tools required to reverse-engineer proprietary BIOS on ports for new mainboards. It is increasingly common that the flash chips are a) not socketed or b) physically hard to access (laptops). Even if chipset support existed already for a board, there are a lot of configuration registers for PCI-e links and GPIO signals that are difficult to get right by code disassembly only. With panic room implementation there would be no need to use external programmers or flashchip hot-swap method to alternate between SerialICE (for proprietary BIOS) and coreboot romstage boots.<br />
<br />
SerialICE requires minimal hardware resources and does not require installed RAM or display hardware. It could be used as the first power-on environment after mainboard PCB verification and assembly to verify integrated components enumerate correctly. At the end of this first power-on, actual board firmware can be programmed without the need for external programmers and SOIC-8 clips, as the SPI controller embedded in the chipset can be used instead. As setting up EHCI debug port console is fairly simple across different chipsets, it can be used to print detailed diagnostics instead of POST codes on LPC bus.<br />
<br />
<br />
GSoC 2011 project [http://blogs.coreboot.org/blog/2011/05/09/gsoc-project-coreboot-panic-room-diagnostics-also-remote-flashing/] was able to:<br />
* Link flashrom with libpayload and flash from USB drive in a pre-OS environment.<br />
* Optimise flashrom memory usage to flash in pre-ram/cache-as-ram environment.<br />
* Build SerialICE boot ROM inside the coreboot tree and share some of the PnP/SuperIO source code.<br />
* Demonstrate booting alternative payload on keypress.<br />
<br />
<br />
There are remaining open tasks to:<br />
* Bring the GSoC 2011 patches up-to-date with current flashrom and libpayload trees.<br />
* Create generic solution to jump to recovery mode using input from GPIOs and/or use of power-button override.<br />
* Use SMBus/SMLink to send POST failure codes over ethernet using integrated network controllers.<br />
* After panic(), dump RAM contents before they are overwritten.<br />
<br />
<br />
'''Mentors'''<br />
* [[User:Rminnich|Ron Minnich]]<br />
<br />
== Board config infrastructure ==<br />
<br />
Design data structures that host information about the board layout so coreboot can better initialize components and generate all kinds of tables (mptable, pirq, acpi, ...) from that dynamically (at build or runtime, as appropriate). Adapt boards to use that instead of the current hardcodes.<br />
<br />
'''Links'''<br />
* ?<br />
<br />
'''Mentors'''<br />
* ?<br />
<br />
<br />
== Refactor AMD code ==<br />
<br />
AMD K8 and AMD Fam10 are different enough to have their own code. This is unfortunate, as you have to decide which CPU type you use in a given mainboard. Refactor AMD code so a single image can support both chip types on a given board. Also move tables from get_bus_conf and the like to the device tree or kconfig options (or runtime detection), as appropriate.<br />
<br />
Alternatively, figure out a way how to build them in parallel and have coreboot select the right one on runtime.<br />
<br />
'''Links'''<br />
* ?<br />
<br />
'''Mentors'''<br />
* [[User:Stepan|Stefan Reinauer]]<br />
<br />
<br />
== AMD VSA ==<br />
<br />
Get the source code of AMD's VSA compiled and working with an open source toolchain. Integrate the it into the current build system.<br />
<br />
'''Links'''<br />
* ?<br />
<br />
'''Mentors'''<br />
* ?</div>Stepanhttp://www.coreboot.org/index.php?title=Code_Coverage&diff=11384Code Coverage2013-01-09T01:14:45Z<p>Stepan: </p>
<hr />
<div>= Prerequisites =<br />
<br />
You need<br />
* The code coverage patch for coreboot: http://review.coreboot.org/#/c/2052/<br />
* The latest version of lcov: http://ltp.cvs.sourceforge.net/viewvc/ltp/utils/analysis/lcov/?view=tar<br />
<br />
= Getting started =<br />
<br />
* Install lcov. You will need to patch geninfo to make it work with the coreboot toolchain:<br />
--- bin/geninfo 2012-11-13 01:58:53.000000000 -0800<br />
+++ bin/geninfo 2013-01-08 16:44:48.041362229 -0800<br />
@@ -1871,7 +1871,7 @@<br />
close(GCOV_PIPE);<br />
<br />
$result = 0;<br />
- if ($version_string =~ /(\d+)\.(\d+)(\.(\d+))?/)<br />
+ if ($version_string =~ /(\d+)\.(\d+)(\.(\d+))$/)<br />
{<br />
if (defined($4))<br />
{<br />
<br />
= Getting code coverage information =<br />
<br />
* Compile coreboot with CONFIG_COVERAGE enabled<br />
* Flash and run coreboot on the target system<br />
* Run cbmem on the target system to extract coverage data (see coreboot/util/cbmem/)<br />
$ sudo ./cbmem -CV<br />
* Transfer the files back to your host system<br />
* Run lcov and genhtml on the host system<br />
$ lcov --capture --directory $( pwd ) --output-file coreboot.info --gcov-tool i386-elf-gcov<br />
$ genhtml coreboot.info --output-directory coreboot-coverage<br />
* Find your html files visualizing code coverage in coreboot-coverage<br />
<br />
= Demo =<br />
<br />
http://www.coreboot.org/~stepan/coreboot-coverage/<br />
<br />
= See Also =<br />
* http://ltp.sourceforge.net/coverage/lcov.php<br />
* http://gcc.gnu.org/onlinedocs/gcc/Gcov.html</div>Stepanhttp://www.coreboot.org/index.php?title=Code_Coverage&diff=11383Code Coverage2013-01-09T00:52:14Z<p>Stepan: Created page with &quot;= Prerequisites = You need * The code coverage patch for coreboot: http://review.coreboot.org/#/c/2052/ * The latest version of lcov: http://ltp.cvs.sourceforge.net/viewvc/lt...&quot;</p>
<hr />
<div>= Prerequisites =<br />
<br />
You need<br />
* The code coverage patch for coreboot: http://review.coreboot.org/#/c/2052/<br />
* The latest version of lcov: http://ltp.cvs.sourceforge.net/viewvc/ltp/utils/analysis/lcov/?view=tar<br />
<br />
= Getting started =<br />
<br />
* Install lcov. You will need to patch geninfo to make it work with the coreboot toolchain:<br />
--- bin/geninfo 2012-11-13 01:58:53.000000000 -0800<br />
+++ bin/geninfo 2013-01-08 16:44:48.041362229 -0800<br />
@@ -1871,7 +1871,7 @@<br />
close(GCOV_PIPE);<br />
<br />
$result = 0;<br />
- if ($version_string =~ /(\d+)\.(\d+)(\.(\d+))?/)<br />
+ if ($version_string =~ /(\d+)\.(\d+)(\.(\d+))$/)<br />
{<br />
if (defined($4))<br />
{<br />
<br />
= Getting code coverage information =<br />
<br />
* Compile coreboot with CONFIG_COVERAGE enabled<br />
* Flash and run coreboot on the target system<br />
* Run cbmem on the target system to extract coverage data (see coreboot/util/cbmem/)<br />
$ sudo ./cbmem -CV<br />
* Transfer the files back to your host system<br />
* Run lcov and genhtml on the host system<br />
$ lcov --capture --directory $( pwd ) --output-file coreboot.info --gcov-tool i386-elf-gcov<br />
$ genhtml coreboot.info --output-directory coreboot-coverage<br />
* Find your html files visualizing code coverage in coreboot-coverage<br />
<br />
= Demo =<br />
<br />
http://www.coreboot.org/~stepan/coreboot-coverage/</div>Stepanhttp://www.coreboot.org/index.php?title=MediaWiki:Sidebar&diff=11339MediaWiki:Sidebar2012-11-29T23:10:14Z<p>Stepan: </p>
<hr />
<div>* Status<br />
** mainpage|Overview<br />
** Current events|currentevents<br />
** Supported Motherboards|Supported boards<br />
** Supported Chipsets and Devices|Supported chipsets<br />
** Download coreboot|Downloads<br />
** recentchanges-url|Recent changes<br />
** Fun Stuff|Fun Stuff<br />
<br />
* Support<br />
** Documentation|Documentation<br />
** Category:Tutorials|Board&amp;nbsp;status&amp;nbsp;pages<br />
** http://tracker.coreboot.org/trac/coreboot/|Issue tracker<br />
** Mailinglist|Mailinglist<br />
** IRC|IRC<br />
** FAQ|FAQ<br />
<br />
* Development / QA<br />
** Development Guidelines|Guidelines<br />
** Developer Manual|Developer manual<br />
** http://review.coreboot.org/gitweb?p=coreboot.git|Browse source<br />
** http://qa.coreboot.org/docs/doxygen/|Doxygen<br />
** http://qa.coreboot.org/|QA and snapshots</div>Stepanhttp://www.coreboot.org/index.php?title=Welcome_to_coreboot&diff=11294Welcome to coreboot2012-10-23T00:07:28Z<p>Stepan: </p>
<hr />
<div>&lt;table width=&quot;100%&quot; valign=&quot;top&quot;&gt;&lt;tr valign=&quot;top&quot;&gt;&lt;td width=&quot;80%&quot;&gt;<br />
<br />
&lt;div style=&quot;margin-top:0.5em; margin-bottom:0.5em; padding:0.5em 0.5em 0.5em 0.5em; background-color:#efefff; align:right; border:1px solid #aabbcc;&quot;&gt;<br />
'''coreboot''' is a Free Software project aimed at replacing the proprietary [http://wikipedia.org/wiki/BIOS BIOS] (firmware) found in most computers. coreboot performs a little bit of hardware initialization and then executes additional boot logic, called a [[Payloads|payload]].<br />
<br />
With the separation of hardware initialization and later boot logic, coreboot can scale from specialized applications that run directly from firmware, run operating systems in flash, load custom bootloaders, or implement firmware standards, like [[SeaBIOS | PC BIOS services]] or [[TianoCore | UEFI]]. This allows for systems to only include the features necessary in the target application, reducing the amount of code and flash space required.<br />
<br />
coreboot currently supports over '''[[Supported Motherboards|230]]''' different mainboards. Check the [[Support]] page to see if your system is supported.<br />
<br />
&lt;small&gt;<br />
coreboot was formerly known as [http://www.coreboot.org/pipermail/coreboot/2008-January/029133.html LinuxBIOS]. <br />
&lt;/small&gt;<br />
&lt;/div&gt;<br />
<br />
&lt;div style=&quot;margin-top:0.5em; margin-bottom:0.5em; padding:0.5em 0.5em 0.5em 0.5em; background-color:#efefff; align:right; border:1px solid #aabbcc;&quot;&gt;<br />
coreboot recently switched to [[git]] and [http://review.coreboot.org gerrit] is now used as patch review tool.<br />
&lt;/div&gt;<br />
<br />
{| cellspacing=0 cellpadding=8 border=0 margin=0 padding=0 align=&quot;top&quot; width=100%<br />
|-<br />
|style=&quot;vertical-align:top&quot;|<br />
<br />
{{Box|<br />
BORDER = #8898bf|<br />
BACKGROUND = yellow|<br />
WIDTH = 100%|<br />
ICON = &lt;small&gt;[[Benefits|More...]]&lt;/small&gt;|<br />
HEADING = &lt;span style=&quot;font-variant:small-caps; font-size:120%&quot;&gt;[[Benefits]]&lt;/span&gt;|<br />
CONTENT =<br />
&lt;small&gt;<br />
* 100% Free Software (GPL), no royalties, no license fees!<br />
* Fast boot times (500 milliseconds to verified Linux kernel)<br />
&lt;!-- * Avoids the need for a slow/buggy/proprietary BIOS --&gt;<br />
&lt;!-- * Runs in 32-Bit protected mode almost from the start --&gt;<br />
&lt;!-- * Written in C, contains virtually no assembly code --&gt;<br />
* Supports many [[Supported Motherboards|mainboards]], [[Supported Chipsets and Devices|chipsets]], and [[payloads]]<br />
&lt;!-- * Further features: netboot, serial console, remote flashing, ... --&gt;<br />
&lt;/small&gt;<br />
}}<br />
<br />
|style=&quot;vertical-align:top&quot;|<br />
<br />
{{Box|<br />
BORDER = #8898bf|<br />
BACKGROUND = #d1adf6|<br />
WIDTH = 100%|<br />
ICON = &lt;small&gt;[[Use Cases|More...]]&lt;/small&gt;|<br />
HEADING = &lt;span style=&quot;font-variant:small-caps; font-size:120%&quot;&gt;[[Use Cases]]&lt;/span&gt;|<br />
CONTENT =<br />
&lt;small&gt;<br />
* Desktop PCs, servers, [[Laptop|laptops]]<br />
* [[Clusters]]<br />
&lt;!-- * Set-Top-Boxes, thin clients --&gt;<br />
* Embedded solutions<br />
&lt;!-- * [http://en.wikipedia.org/wiki/Small_form_factor Small form factor computers], [http://en.wikipedia.org/wiki/Home_theater_PC Home-theater PCs] --&gt;<br />
&lt;!-- * No-moving-parts solutions (ROM chip as &quot;disk&quot;) --&gt;<br />
&lt;!-- * Non-standard scenarios (e.g. FPGA in Opteron socket) --&gt;<br />
&lt;/small&gt;<br />
}}<br />
<br />
|style=&quot;vertical-align:top&quot;|<br />
<br />
{{Box|<br />
BORDER = #8898bf|<br />
BACKGROUND = lime|<br />
WIDTH = 100%|<br />
ICON = &lt;small&gt;[[Payloads|More...]]&lt;/small&gt;|<br />
HEADING = &lt;span style=&quot;font-variant:small-caps; font-size:120%&quot;&gt;[[Payloads]]&lt;/span&gt;|<br />
CONTENT =<br />
&lt;small&gt;<br />
* [[SeaBIOS]] / [[FILO]] / [[GRUB2]] / [[Payloads|...]] &lt;!-- / [[OpenFirmware]] / [[OpenBIOS]] --&gt;<br />
* [[Linux]] / [[Windows]] / [[FreeBSD]] / [[NetBSD]] / [[Payloads|...]] &lt;!-- / [http://openbsd.org/ OpenBSD]--&gt;<br />
* [[Etherboot]] / [[GPXE]] / [[iPXE]] / [[Payloads|...]]<br />
&lt;!--* [[Memtest86]]<br />
* [[Bayou]] / [[Coreinfo]] / [[Tint]] / [[Libpayload]]--&gt;<br />
&lt;/small&gt;<br />
}}<br />
<br />
|}<br />
<br />
{| cellspacing=5 cellpadding=15 border=0 valign=&quot;top&quot; width=100%<br />
| width=50% style=&quot;vertical-align:top&quot;|<br />
<br />
{|<br />
|style=&quot;vertical-align:top&quot;|<br />
[[Image:chip_cb.png]]<br />
|style=&quot;vertical-align:top&quot;|<br />
'''&lt;span style=&quot;font-variant:small-caps; font-size:150%&quot;&gt;About&lt;/span&gt;'''&lt;br /&gt;&lt;small&gt;Find out more about coreboot.&lt;/small&gt;&lt;small&gt;&lt;hr /&gt;[[Press]] | [[Logo]] | [[History]] | [[Screenshots|Screenshots/Videos]] | [[Contributors]] | [[Sponsors]] | [[Products]] | [[Vendors]]&lt;/small&gt;<br />
|}<br />
<br />
|style=&quot;vertical-align:top&quot;|<br />
<br />
{|<br />
|style=&quot;vertical-align:top&quot;|<br />
[[Image:chip_devel.png]]<br />
|style=&quot;vertical-align:top&quot;|<br />
'''&lt;span style=&quot;font-variant:small-caps; font-size:150%&quot;&gt;Developers&lt;/span&gt;'''&lt;br /&gt;&lt;small&gt;Get involved! Help us make coreboot better.&lt;/small&gt;&lt;small&gt;&lt;hr /&gt;[[Development Guidelines]] | [[Developer Manual]] | [http://qa.coreboot.org/docs/doxygen.php Doxygen] | [http://review.coreboot.org/gitweb?p=coreboot.git;a=tree Browse Source] | [[GSoC]] | [[Flag Days]] | [[Distributed and Automated Testsystem|Testsystem]]&lt;/small&gt;<br />
|}<br />
<br />
|-<br />
| width=50% style=&quot;vertical-align:top&quot;|<br />
<br />
{|<br />
|style=&quot;vertical-align:top&quot;|<br />
[[Image:chip_status.png]]<br />
|style=&quot;vertical-align:top&quot;|<br />
'''&lt;span style=&quot;font-variant:small-caps; font-size:150%&quot;&gt;Status&lt;/span&gt;'''&lt;br /&gt;&lt;small&gt;Find out whether your hardware is already supported.&lt;/small&gt;&lt;small&gt;&lt;hr /&gt;[[Supported Motherboards|Supported Boards]] | [[Supported Chipsets and Devices|Supported Chipsets]] | [[:Category:Tutorials|Board Status Pages]] | [http://qa.coreboot.org Build Status]&lt;/small&gt;<br />
|}<br />
<br />
|style=&quot;vertical-align:top&quot;|<br />
<br />
{|<br />
|style=&quot;vertical-align:top&quot;|<br />
[[Image:chip_tools.png]]<br />
|style=&quot;vertical-align:top&quot;|<br />
'''&lt;span style=&quot;font-variant:small-caps; font-size:150%&quot;&gt;Related Tools&lt;/span&gt;'''&lt;br /&gt;&lt;small&gt;Tools and libraries related to coreboot.&lt;/small&gt;&lt;small&gt;&lt;hr /&gt;[[Flashrom]] | [[Superiotool]] | [[Nvramtool]] | [[Buildrom]] | [[Mkelfimage]] | [[Inteltool]] | [[Msrtool]] | [[Ectool]] | [[Developer_Manual/Tools|Hardware tools]] | [[Abuild]] | [[SerialICE]]&lt;/small&gt;<br />
|}<br />
<br />
|-<br />
| width=50% style=&quot;vertical-align:top&quot;|<br />
<br />
{|<br />
|style=&quot;vertical-align:top&quot;|<br />
[[Image:chip_101.png]]<br />
|style=&quot;vertical-align:top&quot;|<br />
'''&lt;span style=&quot;font-variant:small-caps; font-size:150%&quot;&gt;Getting Started&lt;/span&gt;'''&lt;br /&gt;&lt;small&gt;Download coreboot and get started.&lt;/small&gt;&lt;small&gt;&lt;hr /&gt;[[Build HOWTO]] | [[Download coreboot|Downloads]] | [[Documentation]] | [[QEMU]] | [[AMD SimNow]] | [[Build from Windows]]&lt;/small&gt;<br />
|}<br />
<br />
|style=&quot;vertical-align:top&quot;|<br />
<br />
{|<br />
|style=&quot;vertical-align:top&quot;|<br />
[[Image:chip_support.png]]<br />
|style=&quot;vertical-align:top&quot;|<br />
'''&lt;span style=&quot;font-variant:small-caps; font-size:150%&quot;&gt;Support&lt;/span&gt;'''&lt;br /&gt;&lt;small&gt;Learn how to contact us and find help and support.&lt;/small&gt;&lt;small&gt;&lt;hr /&gt;[[FAQ]] | [[Mailinglist]] | [[IRC]] | [http://tracker.coreboot.org/trac/coreboot/ Issue Tracker] | [[Glossary]] | [[coreboot Options|coreboot Options]]&lt;/small&gt;<br />
|}<br />
<br />
|}<br />
&lt;/td&gt;&lt;td width=&quot;20%&quot;&gt;<br />
<br />
[[File:Coreboot menuconfig.png|center|thumb|[[Build HOWTO|make menuconfig]] in coreboot]]<br />
<br />
&lt;br clear=all /&gt;<br />
<br />
'''&lt;span style=&quot;font-variant:small-caps; font-size:120%&quot;&gt;[http://blogs.coreboot.org News (blog)]&lt;/span&gt;'''&lt;hr /&gt;<br />
&lt;small&gt;<br />
&lt;rss max=5&gt;http://blogs.coreboot.org/feed/&lt;/rss&gt;<br />
&lt;/small&gt;<br />
<br />
<br />
'''&lt;span style=&quot;font-variant:small-caps; font-size:120%&quot;&gt;[[Current events|Upcoming Events]]&lt;/span&gt;'''&lt;hr /&gt;<br />
&lt;!-- List of upcoming events (remove events after they have taken place). --&gt;<br />
&lt;small&gt;<br />
&lt;!-- * '''2011/mon/day:''' coreboot event at [[Link]] in somecity --&gt;<br />
&lt;/small&gt;<br />
<br />
<br />
&lt;br clear=all /&gt;<br />
{{#widget:Ohloh Project|id=coreboot|type=partner_badge}}<br />
{{#widget:Ohloh Project|id=coreboot|type=cocomo}}<br />
<br />
<br />
&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;<br />
<br />
__NOTOC__<br />
__NOEDITSECTION__</div>Stepanhttp://www.coreboot.org/index.php?title=ARM&diff=11196ARM2012-09-19T21:06:42Z<p>Stepan: </p>
<hr />
<div>coreboot on ARM is a work-in-progress. coreboot currently does not support ARM.<br />
<br />
ARM SOCs with PCIe are now on the market for tablets, netbooks and servers. These systems can take advantage of coreboot's strength in properly configuring PCI, SAS, SATA and SCSI devices; fast boot times; and payload support.<br />
<br />
== ARM SOCs ==<br />
<br />
* [http://www.marvell.com/products/processors/armada.html Marvell Armada 300, 510, 1000 with PCIe]<br />
* [http://www.marvell.com/products/processors/embedded/armada_xp/ Marvell Armada XP]<br />
* [http://www.marvell.com/products/processors/embedded/discovery_innovation/ Marvell Discovery Innovation Series with PCIe]<br />
* [http://www.marvell.com/products/processors/embedded/kirkwood/ Marvell Kirkwood Series with PCIe]<br />
* [http://www.st.com/internet/mcu/product/250658.jsp STMicroelectronics SPEAr1310 with PCIe]<br />
* [http://www.st.com/internet/mcu/product/251211.jsp STMicroelectronics SPEAr1340 with PCIe]<br />
* [http://focus.ti.com/dsp/docs/dspplatformscontento.tsp?sectionId=2&amp;familyId=1875&amp;tabId=2643 TI Sitara with PCIe]<br />
* [http://www.caviumnetworks.com/ECONA_CNS3XXX.html Cavium Networks ECONA CNS3XXX]<br />
* [http://www.samsung.com/global/business/semiconductor/productInfo.do?fmly_id=844&amp;partnum=Exynos%204210&amp;xFmly_id=229 Samsung Exynos 4210 with PCIe]<br />
* [http://www.nvidia.com/object/tegra.html NVIDIA TEGRA]<br />
* [http://www.semicon.panasonic.co.jp/en/catalog/uniphier/index.html Panasonic UniPhier MN2WS0220]<br />
* [http://www.ziilabs.com/products/processors/zms20.aspx ZiiLabs ZMS-20]<br />
<br />
== Platforms ==<br />
<br />
* [http://www.globalscaletechnologies.com/t-openrdudetails.aspx OpenRD Ultimate with Marvell 88F6281]<br />
* [http://www.marvell.com/platforms/open_rd.html OpenRD Platforms with Marvell 88F6281]<br />
* [http://www.wyse.com/products/hardware/thinclients/T50/ WYSE T50 Marvell Thin Client]<br />
* [http://h10010.www1.hp.com/wwpc/us/en/sm/WF05a/12454-12454-321959-338927-3640405-4063703.html HP t5325 Marvell Thin Client]<br />
* [http://www.ztsystems.com/Portals/0/ZTSystems_R1801e.pdf ZTSystems R1801e rackmount server with STMicroelectronics SPEAr 1310 with dual ARM® CortexTM-A9 cores]<br />
* [http://pandaboard.org/ PandaBoard Dual-core ARM® Cortex™-A9 MPCore™ mobile dev board]<br />
* [http://www.origenboard.org origenBOARD Exynos 4210 dev board]<br />
* [http://www.toradex.com/Products/Colibri/Modules/Colibri-Tegra-2 Colibri T20 cpu module with NVIDIA Dual Core ARM Cortex A9 Processor]<br />
* [http://trimslice.com/ Trimslice NVIDIA Tegra 2 dual-core ARM Cortex A9 @ 1 GHz 0.6&quot; thin desktop]<br />
* [http://www.compulab.co.il/a510/html/a510-sb-datasheet.htm SBC-A510 Marvell Armada 510 micro-ATX, single board computer]</div>Stepanhttp://www.coreboot.org/index.php?title=Debugging&diff=11064Debugging2012-03-29T19:56:03Z<p>Stepan: </p>
<hr />
<div>= GDB Interface =<br />
<br />
coreboot has an easy to use interface to the GNU debugger gdb. To enable it, select the CONFIG_GDB_STUB option in the Debugging menu of coreboot's configuration:<br />
[*] GDB debugging support<br />
<br />
Then you will not get exceptions like this:<br />
<br />
Unexpected Exception: 0 @ 10:0012724b - Halting<br />
Code: 0 eflags: 00010046<br />
eax: 00000001 ebx: 00000061 ecx: 00000004 edx: 00000000<br />
edi: 00000000 esi: 00000061 ebp: 00163abc esp: 00163a98<br />
<br />
But instead you will be able to connect to the machine using gdb over a serial line in case of an exception:<br />
<br />
(gdb) file coreboot/build/coreboot_ram.debug<br />
Reading symbols from coreboot/build/coreboot_ram.debug...done.<br />
(gdb) set remotebaud 115200<br />
(gdb) target remote /dev/ttyUSB0<br />
Remote debugging using /dev/ttyUSB0<br />
0x0012824b in __udivdi3 (n=17082841390, d=0) at ...<br />
...<br />
(gdb) bt<br />
#0 0x0012824b in __udivdi3 (n=17082841390, d=0)<br />
at /usr/lib/gcc/gcc- 4.3.2/libgcc/../gcc/libgcc2.c:899 <br />
#1 0x0011efa2 in handle_port_61h ()<br />
#2 0x0011fbc3 in my_inb ()<br />
#3 0x001189f5 in x86emuOp_in_byte_AL_IMM ()<br />
#4 0x001092f1 in X86EMU_exec ()<br />
#5 0x0010a06f in biosemu ()<br />
#6 0x0011fcfb in run_bios ()<br />
#7 0x0010cbcb in pci_dev_init ()<br />
#8 0x00103d9b in dev_initialize ()<br />
#9 0x0010f8b5 in hardwaremain ()<br />
#10 0x00100099 in _text ()</div>Stepanhttp://www.coreboot.org/index.php?title=User_talk:Nru&diff=11040User talk:Nru2012-02-27T17:45:44Z<p>Stepan: Created page with &quot;Noe Rubinstein&quot;</p>
<hr />
<div>Noe Rubinstein</div>Stepanhttp://www.coreboot.org/index.php?title=Infrastructure_Projects&diff=10949Infrastructure Projects2011-12-15T01:40:15Z<p>Stepan: /* Clean out duplicates */</p>
<hr />
<div>This page collects a list of projects to improve the infrastructure of coreboot v4. Infrastructure means those parts of the code that aren't chipset or mainboard specific, but are used by all of them. The idea is to consolidate a list of things &quot;to do&quot; with their status and responsible developers.<br />
<br />
= In progress =<br />
<br />
== Low/High Tables ==<br />
<br />
SeaBIOS requires a copy of various BIOS tables outside the fseg as it overwrites that segment. Generally clean out the table generation code.<br />
<br />
'''Status:''' Upstream, implemented on some boards. There are problems on some chipsets/boards because of incorrect CONFIG_VIDEO_MB handling. The might be other issues, too (not clear, yet).<br />
<br />
{| border=&quot;0&quot; style=&quot;font-size: smaller&quot;<br />
|- bgcolor=&quot;#6699ff&quot;<br />
! align=&quot;left&quot; | Vendor/chipset<br />
! align=&quot;left&quot; | Tested<br />
! align=&quot;left&quot; | Comments<br />
<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/amdfam10<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/amdht<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/amdk8<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/amdmct<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/gx1<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/gx2<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/lx<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/e7501<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/e7520<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/e7525<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i3100<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i440bx<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82810<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82830<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i855<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i945<br />
| style=&quot;background:lime&quot; | Y<br />
| Tested on Kontron 986LCD-M and Roda RK886EX<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/cn400<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/cn700<br />
| style=&quot;background:lime&quot; | Y<br />
| Tested on VIA pc2500e.<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/cx700<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vt8601<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vt8623<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vx800<br />
| ?<br />
| &amp;mdash;<br />
<br />
|}<br />
<br />
'''Developers:''' Stefan<br />
<br />
== CBFS ==<br />
<br />
A filesystem-alike layout for the coreboot image, to enable systems like bayou and to clean up the system in general (eg. no more buildrom).<br />
<br />
'''Status:'''<br />
<br />
Upstream, pre-CBFS infrastructure removed.<br />
<br />
There are places where using CBFS might be a good idea: Everything that makes use of external files, for example the VSA code in the Geode chipset code. VSA is converted, and tested on a couple of configurations, but untested on others.<br />
<br />
Some boards have issues with CBFS because it requires the whole ROM to be accessible at a quite early point in time (compared to the old mechanism). The following table contains validated knowledge if the ROM mapping happens at the right time.<br />
<br />
All boards that manage to boot in a tinybootblock configuration are capable at least for the used ROM size (it might be that larger ROMs would fail because they require mapping the larger space)<br />
<br />
{| border=&quot;0&quot; style=&quot;font-size: smaller&quot;<br />
|- bgcolor=&quot;#6699ff&quot;<br />
! align=&quot;left&quot; | Vendor/chipset<br />
! align=&quot;left&quot; | ROM enabled<br />
! align=&quot;left&quot; | Tiny bootblock<br />
! align=&quot;left&quot; | Status / Comments<br />
<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/amd8111<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| Not tested on hardware, yet.<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/cs5530<br />
| style=&quot;background:lime&quot; | Y<br />
| style=&quot;background:red&quot; | N<br />
| Not tested on hardware, yet.<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/cs5535<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/cs5536<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/sb600<br />
| style=&quot;background:lime&quot; | Y<br />
| style=&quot;background:lime&quot; | Y<br />
| Build- and runtime-tested on siemens/sitemp_g1p1 by [[User:PatrickGeorgi|PatrickGeorgi]].<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/sb700<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| &amp;mdash;<br />
<br />
|- bgcolor=&quot;#dddddd&quot;<br />
| broadcom/bcm5785<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| Not tested on hardware, yet.<br />
<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/esb6300<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i3100<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82371eb<br />
| style=&quot;background:lime&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| Build- and runtime-tested on ASUS P2B by [[User:Uwe|Uwe Hermann]].<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82801ax<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82801bx<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82801cx<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82801dx<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82801ex<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82801gx<br />
| style=&quot;background:lime&quot; | Y<br />
| style=&quot;background:lime&quot; | Y<br />
| Build- and runtime-tested on Kontron 986LCD-m by PatrickGeorgi<br />
<br />
|- bgcolor=&quot;#dddddd&quot;<br />
| nvidia/ck804<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| Not tested on hardware, yet.<br />
|- bgcolor=&quot;#dddddd&quot;<br />
| nvidia/mcp55<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| Not tested on hardware, yet.<br />
<br />
|- bgcolor=&quot;#dddddd&quot;<br />
| sis/sis966<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| Not tested on hardware, yet.<br />
<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vt8231<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vt8235<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vt8237r<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vt82c686<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
<br />
|}<br />
<br />
'''Developers:''' Stefan, Ron, Patrick, Myles, Uwe<br />
<br />
== Tiny Bootblock ==<br />
<br />
Right now, the decision whether to use fallback or normal is in cache_as_ram_auto.c in many boards. Make that generic again (also helps with further CBFSification at some point).<br />
<br />
'''Status:''' Available in Kconfig, works on a couple of boards. Requires per southbridge changes (and northbridge in some cases) on many boards (related to ROM enable, see CBFS section).<br />
<br />
'''Developers:''' Patrick<br />
<br />
== Remove .c includes ==<br />
<br />
Currently we include lots of code in the romstage using the preprocessor. This makes it harder to support new boards (where chipset components are supported already) and maintenance in general. So we should get rid of it where possible, using the linker for CAR boards and the build system for the remaining non-CAR boards appropriately.<br />
<br />
'''Status:''' CAR boards only for now, to keep the project manageable. i945 is modified already, and boards based on it have only one or two remaining source files they include. Interacts with the next project &quot;Move configuration to Kconfig&quot;, which ensures that code still sees all configuration when it is compiled separately.<br />
<br />
'''Developers:''' Patrick, Uwe<br />
<br />
== Move configuration to Kconfig ==<br />
<br />
Many boards have lots of &lt;code&gt;#define VAR somevalue&lt;/code&gt; statements in their romstage.c which define how certain component drivers are compiled. With Kconfig, there's a better place to store them. This project is about moving all configuration values out of romstage.c (and other places if appropriate) and into Kconfig. &lt;code&gt;util/lint/lint-001-no-global-config-in-romstage&lt;/code&gt; helps figuring out what remains to be done.<br />
<br />
'''Status:''' Intel and VIA based boards should be mostly configuration free, AMD boards still have defines in their romstage. AMD/AGESA Boards have platform_cfg.h for which a solution should be found.<br />
<br />
'''Developers:''' Patrick, Uwe<br />
<br />
== Unify ACPI ==<br />
* Figure out generic ACPI code and deduplicate it.<br />
* Fix issues like http://www.coreboot.org/pipermail/coreboot/2011-May/065179.html<br />
<br />
Done:<br />
* Every ACPI board has its own routines to compile the ACPI sources. Unify that.<br />
<br />
= More ideas =<br />
<br />
== CMOS handling ==<br />
<br />
The subprojects are ordered in a way that minimizes lost work.<br />
<br />
=== Simplify get_option ===<br />
Replace &lt;code&gt;get_option(VALstart, VALlen, default)&lt;/code&gt; with a macro that hides start/len in something like &lt;code&gt;get_option(VAL, default)&lt;/code&gt;<br />
<br />
=== Use nvramtool for static option table creation ===<br />
Instead of maintaining two tools (build_opt_tbl, nvramtool), maintain only one. This mostly requires adding an binary output writer to nvramtool, a cmos.layout parser already exists<br />
<br />
=== Implement a new cmos.layout format ===<br />
The current layout is simple to parse, but not so simple to maintain or extend.<br />
Create a format that combines the various fields into a single representation, eg.<br />
<br />
&lt;code&gt;<br />
400/8 century enum { 0x19=&quot;1900&quot;, 0x20=&quot;2000&quot;, 0x21=&quot;2100&quot; }<br />
<br />
408/512 some_string string<br />
<br />
984/16 checksum checksum 392 983<br />
&lt;/code&gt;<br />
<br />
=== Implement an include statement ===<br />
That way, we can have global fields (RTC, century byte), per chipset component fields (defined by northbrigde/southbridge/superio), per mainboard fields at their appropriate places.<br />
<br />
=== CMOS defaults ===<br />
Allow (somehow) to define defaults for all CMOS fields, and create a static table from that. Use that at runtime if the CMOS checksum fails.<br />
In the above format, it could simply be a suffix &lt;code&gt;default=VALUE&lt;/code&gt;<br />
Also drop the &quot;default&quot; argument in get_options. As components have their own cmos.layout snippets, we can always take those definitions' defaults, even if mainboards don't make use of CMOS themselves.<br />
<br />
=== Value overrides ===<br />
A chipset might provide options (eg. SATA/IDE) that a board might override (eg. because it doesn't provide IDE even if the chipset would support it). Allow the mainboard to override config options. This wouldn't just set a new default, but drop the option from CMOS entirely, hardcoding the value in the build. Some autogenerated #ifdef/#define magic might help there.<br />
<br />
=== Provide update paths and avoid conflicts in addressing ===<br />
Research topic: How could updates to nvram configuration (eg. new fields) be handled safely, and how could we get away from carving out the CMOS memory space manually? (one proposal: http://article.gmane.org/gmane.linux.bios/64572)<br />
<br />
=== Checksums ===<br />
<br />
The Linux kernel driver expects a non-inverted CMOS checksum for the &quot;PC&quot; area. coreboot inverts this checksum, which makes nvram unusable for the driver. This should be fixed.<br />
<br />
== Unify UMA / onboard video code and config ==<br />
<br />
Unify CONFIG_VIDEO_MB, CONFIG_GFXUMA, and similar options and make all code honor them.<br />
<br />
== Add / Unify / Test kconfig compile-time options and runtime CMOS options in coreboot ==<br />
<br />
Some coreboot options are compile-time configurable only at the moment (via kconfig), but should also be runtime-configurable via CMOS/NVRAM options. We should fix this.<br />
<br />
* Make all options (where it makes sense) run-time configurable via CMOS options, in addition to having sane compile-time defaults configured via kconfig.<br />
* This includes many options which are northbridge-specific, many southbridge-specific, and some board-specific ones.<br />
* Example options: Enable/disable IDE channel(s) / SATA / USB / SCSI / etc., enable/disable UDMA on older boards, amount of memory used for IGP/UMA, choice between IDE or NAND flash (on CS5536 boards), IDE 40/80 pin cable selection (VT8237R boards for example), and many more.<br />
* Some of these options are already handled in the code via CMOS options, some are compile-time only so far, so do not yet exist at all.<br />
<br />
== Kconfig TODO ==<br />
<br />
Notes / Style guide:<br />
<br />
* Any bool variables that are (re-)defined to 'y' in Kconfig files can be simplified by using '''select FOO''' instead of the usual paragraph, as long as they're defined globally as '''default n''' boolean elsewhere.<br />
* Use '''bool''' instead of '''boolean'''.<br />
* Use '''default n''' instead of '''default false'''.<br />
<br />
Various post-conversion things to consider:<br />
<br />
* Consider ways to move crt0-y and ldscript-y out of $(src)/arch/i386/Makefile.inc where appropriate (ie. component specific)<br />
* Make various CONFIG_* variable which were in each board's Kconfig file global or per-chipset options (instead of per-board). Examples:<br />
** UDELAY_TSC, TSC_X86RDTSC_CALIBRATE_WITH_TIMER2 (also check UDELAY_IO, APIC, etc.)<br />
** ...<br />
<br />
Stuff to port from v3 to v4:<br />
<br />
* All boards that are in v3 but not in v4 (especially Geode LX stuff. Also check amd/model_gx*).<br />
* Some remaining useful Kconfig options.<br />
<br />
== USB Debug Console ==<br />
<br />
Fix USB debug console and make the Kconfig choice actually work. Right now it's possible to transmit single characters but it's not really hooked up.<br />
<br />
== Clean up Assembler / Linker mess ==<br />
<br />
* Drop / combine / normalize .ld/.lb/.lds linker scripts.<br />
* Move them to a common place.<br />
* Drop / combine / normalize .inc / .S files.<br />
<br />
== Geode issues ==<br />
<br />
* Fix / Unify vsmsetup.c.<br />
* Fix CS5535/CS5536/GX2/LX &quot;chipsetinit&quot; issue.<br />
<br />
== Stack and Suspend/Resume ==<br />
<br />
* Use CONFIG_RAMBASE + HIGH_MEMORY_SAFE instead of 0x40000 for stack.<br />
<br />
== Fix Suspend/Resume on AMD64 ==<br />
<br />
* Use cbmem in romstage on the AMD64 board(s) that have suspend/resume.<br />
<br />
== printk into buffer ==<br />
<br />
Port the v3 feature that printk can write into a buffer (that might be usable from the client OS, or dumped to output, as soon as output exists).<br />
<br />
Consider use cases first (no need to provide buffer support, if all it would be useful for is buffering pre-CAR messages - which can't be buffered).<br />
<br />
== Global variables ==<br />
<br />
* Port the global variables framework from v3.<br />
* Make use of it where appropriate.<br />
<br />
== Clear phases in romstage ==<br />
<br />
* Split up the code (esp. in romstage) into more sensibly separated phases.<br />
* Maybe use v3 for inspiration where the lines can be drawn.<br />
<br />
== Refactor SMBUS code ==<br />
<br />
We have tons of duplication in the smbus/spd related functions and #defines. Every chipset (and sometimes board) does the same with the exception of the 2 or 3 boards that multiplex spd roms.<br />
* Deduplicate SMBUS related defines, they're virtually everywhere (and all the same)<br />
* Deduplicate the lowlevel functions - they should really be the same (except for some style differences)<br />
* Deduplicate the non-multiplexing highlevel functions. Mark them weak, so multiplexing boards can simply provide their own variant, which override the weak functions automatically<br />
<br />
== Move all registers/chip definitions in XML format for all tools ==<br />
<br />
For easy creating definitions of new chips, or editing old register definitions, improve readability support, and add support for humanless parsing the logs we decide move all data for msrtool, inteltool, superiotool, etc in XML-based format. See here: [[XML]]<br />
<br />
== Device dependency engine ==<br />
<br />
We have a couple of places where we want to disable (or otherwise reconfigure) a device if another one is active: SATA and IDE covering the same ports, integrated graphics / plugin video cards, ...<br />
Right now, such things are done &quot;somewhere&quot;, usually far away from any meaningful context. This idea isn't as actionable as the others as it's still missing even a sketch of a design.<br />
<br />
* Find a good place (or multiple places) where such device decisions can be made<br />
* Refactor the code to make use of it<br />
<br />
== Clean out duplicates ==<br />
<br />
Tools like http://duplo.giants.ch/ or http://pmd.sourceforge.net/cpd.html might be able to help finding duplicates that can be factored out.<br />
<br />
== Local APIC addresses ==<br />
<br />
There are several defines in several places that describe the local APIC address:<br />
<br />
* LAPIC_ADDR<br />
* LOCAL_APIC_ADDR (even twice)<br />
* LAPIC_DEFAULT_BASE<br />
<br />
This should be unified.<br />
<br />
== CONFIG_MAX_PHYSICAL_CPUS ==<br />
<br />
CONFIG_MAX_PHYSICAL_CPUS should be dropped. It's set for all boards, but it's only really used by AMD K8 and newer systems (and not on Intel based systems at all).<br />
In the AMD code it is used wrongly:<br />
<br />
* for determining which SPD offsets to include<br />
* to determine APIC IDs<br />
* possibly some more things<br />
<br />
= Finished =<br />
<br />
== Port v3 Resource Allocator ==<br />
<br />
The v3 resource allocator should be ported to v4.<br />
<br />
'''Status:''' Upstream. It's limited to one area for resources, that doesn't overlap with fixed resources.<br />
<br />
'''Developers:''' Myles<br />
<br />
== Config &amp; Build System ==<br />
<br />
The current system of generated Makefiles is non-ideal (for too many reasons for this little margin). Fix it, somehow. Use kconfig to improve the configuration management.<br />
<br />
'''Status:''' Upstream, boards are converted. Old system is gone. All boards build. HOWEVER, not all boards have been boot-tested yet, please report any issues you encounter!<br />
<br />
'''Developers:''' Stefan, Ron, Patrick, Uwe, Cristi<br />
<br />
== Unify text printing functions ==<br />
<br />
There are several copies of print_* and printk_* in the code. Unify them so everything is happier than before (because the disjoint features are merged).<br />
<br />
'''Status:''' Finished.<br />
<br />
'''Developers:''' Patrick, Stefan<br />
<br />
== Common payload location ==<br />
<br />
Many boards have different names for the payload in targets/.../Config.lb (payload.elf, filo.elf, etherboot.elf, etc) and locations (../payload.elf, or various absolute paths which only work for one developer). The problem will be fixed with kconfig, where the user specifies a payload manually in &quot;make menuconfig&quot;.<br />
<br />
'''Status:''' Finished.<br />
<br />
== Fix ALL build warnings ==<br />
<br />
* Someone has to do the deed.<br />
<br />
'''Status:''' Finished, the build usually issues no warnings. If you see warnings/errors, please report a bug.<br />
<br />
== Post codes ==<br />
<br />
Find all outb(x, 0x80) and replace them with post_code(). Use common numbers / defines across the boards.<br />
<br />
'''Status:''' Finished, except for some local delay routines in early smbus code.<br />
<br />
== Use central oprom init ==<br />
<br />
* Get rid of all vgabios.c, make all chipsets with own vgabios.c use devices/oprom/x86.c.<br />
* Use the realmode code for vsmsetup too.</div>Stepanhttp://www.coreboot.org/index.php?title=Fun_Stuff&diff=10942Fun Stuff2011-12-05T04:08:04Z<p>Stepan: </p>
<hr />
<div><br />
== Failure at scale ==<br />
<br />
A BIOS gets confused in a very visible way: <br />
<br />
[[File:Billboard_bios_fail.jpeg|640px]]<br />
<br />
Photo courtesy Greg Kurtzer of LBL.<br />
<br />
<br />
== What floor am I on? ==<br />
<br />
An elevator in Spain: <br />
<br />
[[File:Elevator_spain.jpeg|640px]]<br />
<br />
Photo courtesy Gorka Guardiola</div>Stepanhttp://www.coreboot.org/index.php?title=MediaWiki:Sidebar&diff=10937MediaWiki:Sidebar2011-12-04T22:07:16Z<p>Stepan: </p>
<hr />
<div>* Status<br />
** mainpage|Overview<br />
** Current events|currentevents<br />
** Supported Motherboards|Supported boards<br />
** Supported Chipsets and Devices|Supported chipsets<br />
** Download coreboot|Downloads<br />
** recentchanges-url|Recent changes<br />
** Fun Stuff|Fun Stuff<br />
<br />
* Support<br />
** Documentation|Documentation<br />
** Category:Tutorials|Board&amp;nbsp;status&amp;nbsp;pages<br />
** http://tracker.coreboot.org/trac/coreboot/|Issue tracker<br />
** Mailinglist|Mailinglist<br />
** IRC|IRC<br />
** FAQ|FAQ<br />
<br />
* Development / QA<br />
** Development Guidelines|Guidelines<br />
** Developer Manual|Developer manual<br />
** http://tracker.coreboot.org/trac/coreboot/browser/trunk|Browse source<br />
** http://qa.coreboot.org/docs/doxygen/|Doxygen<br />
** http://qa.coreboot.org/|QA and snapshots</div>Stepanhttp://www.coreboot.org/index.php?title=Infrastructure_Projects&diff=10905Infrastructure Projects2011-10-13T23:33:27Z<p>Stepan: </p>
<hr />
<div>This page collects a list of projects to improve the infrastructure of coreboot v4. Infrastructure means those parts of the code that aren't chipset or mainboard specific, but are used by all of them. The idea is to consolidate a list of things &quot;to do&quot; with their status and responsible developers.<br />
<br />
= In progress =<br />
<br />
== Low/High Tables ==<br />
<br />
SeaBIOS requires a copy of various BIOS tables outside the fseg as it overwrites that segment. Generally clean out the table generation code.<br />
<br />
'''Status:''' Upstream, implemented on some boards. There are problems on some chipsets/boards because of incorrect CONFIG_VIDEO_MB handling. The might be other issues, too (not clear, yet).<br />
<br />
{| border=&quot;0&quot; style=&quot;font-size: smaller&quot;<br />
|- bgcolor=&quot;#6699ff&quot;<br />
! align=&quot;left&quot; | Vendor/chipset<br />
! align=&quot;left&quot; | Tested<br />
! align=&quot;left&quot; | Comments<br />
<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/amdfam10<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/amdht<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/amdk8<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/amdmct<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/gx1<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/gx2<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/lx<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/e7501<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/e7520<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/e7525<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i3100<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i440bx<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82810<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82830<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i855<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i945<br />
| style=&quot;background:lime&quot; | Y<br />
| Tested on Kontron 986LCD-M and Roda RK886EX<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/cn400<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/cn700<br />
| style=&quot;background:lime&quot; | Y<br />
| Tested on VIA pc2500e.<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/cx700<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vt8601<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vt8623<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vx800<br />
| ?<br />
| &amp;mdash;<br />
<br />
|}<br />
<br />
'''Developers:''' Stefan<br />
<br />
== CBFS ==<br />
<br />
A filesystem-alike layout for the coreboot image, to enable systems like bayou and to clean up the system in general (eg. no more buildrom).<br />
<br />
'''Status:'''<br />
<br />
Upstream, pre-CBFS infrastructure removed.<br />
<br />
There are places where using CBFS might be a good idea: Everything that makes use of external files, for example the VSA code in the Geode chipset code. VSA is converted, and tested on a couple of configurations, but untested on others.<br />
<br />
Some boards have issues with CBFS because it requires the whole ROM to be accessible at a quite early point in time (compared to the old mechanism). The following table contains validated knowledge if the ROM mapping happens at the right time.<br />
<br />
All boards that manage to boot in a tinybootblock configuration are capable at least for the used ROM size (it might be that larger ROMs would fail because they require mapping the larger space)<br />
<br />
{| border=&quot;0&quot; style=&quot;font-size: smaller&quot;<br />
|- bgcolor=&quot;#6699ff&quot;<br />
! align=&quot;left&quot; | Vendor/chipset<br />
! align=&quot;left&quot; | ROM enabled<br />
! align=&quot;left&quot; | Tiny bootblock<br />
! align=&quot;left&quot; | Status / Comments<br />
<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/amd8111<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| Not tested on hardware, yet.<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/cs5530<br />
| style=&quot;background:lime&quot; | Y<br />
| style=&quot;background:red&quot; | N<br />
| Not tested on hardware, yet.<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/cs5535<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/cs5536<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/sb600<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/sb700<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| &amp;mdash;<br />
<br />
|- bgcolor=&quot;#dddddd&quot;<br />
| broadcom/bcm5785<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| Not tested on hardware, yet.<br />
<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/esb6300<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i3100<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82371eb<br />
| style=&quot;background:lime&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| Build- and runtime-tested on ASUS P2B by [[User:Uwe|Uwe Hermann]].<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82801ax<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82801bx<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82801cx<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82801dx<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82801ex<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82801gx<br />
| style=&quot;background:lime&quot; | Y<br />
| style=&quot;background:lime&quot; | Y<br />
| Build- and runtime-tested on Kontron 986LCD-m by PatrickGeorgi<br />
<br />
|- bgcolor=&quot;#dddddd&quot;<br />
| nvidia/ck804<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| Not tested on hardware, yet.<br />
|- bgcolor=&quot;#dddddd&quot;<br />
| nvidia/mcp55<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| Not tested on hardware, yet.<br />
<br />
|- bgcolor=&quot;#dddddd&quot;<br />
| sis/sis966<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| Not tested on hardware, yet.<br />
<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vt8231<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vt8235<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vt8237r<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vt82c686<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
<br />
|}<br />
<br />
'''Developers:''' Stefan, Ron, Patrick, Myles, Uwe<br />
<br />
== Tiny Bootblock ==<br />
<br />
Right now, the decision whether to use fallback or normal is in cache_as_ram_auto.c in many boards. Make that generic again (also helps with further CBFSification at some point).<br />
<br />
'''Status:''' Available in Kconfig, works on a couple of boards. Requires per southbridge changes (and northbridge in some cases) on many boards (related to ROM enable, see CBFS section).<br />
<br />
'''Developers:''' Patrick<br />
<br />
== Remove .c includes ==<br />
<br />
Currently we include lots of code in the romstage using the preprocessor. This makes it harder to support new boards (where chipset components are supported already) and maintenance in general. So we should get rid of it where possible, using the linker for CAR boards and the build system for the remaining non-CAR boards appropriately.<br />
<br />
'''Status:''' CAR boards only for now, to keep the project manageable. i945 is modified already, and boards based on it have only one or two remaining source files they include. Interacts with the next project &quot;Move configuration to Kconfig&quot;, which ensures that code still sees all configuration when it is compiled separately.<br />
<br />
'''Developers:''' Patrick, Uwe<br />
<br />
== Move configuration to Kconfig ==<br />
<br />
Many boards have lots of &lt;code&gt;#define VAR somevalue&lt;/code&gt; statements in their romstage.c which define how certain component drivers are compiled. With Kconfig, there's a better place to store them. This project is about moving all configuration values out of romstage.c (and other places if appropriate) and into Kconfig. &lt;code&gt;util/lint/lint-001-no-global-config-in-romstage&lt;/code&gt; helps figuring out what remains to be done.<br />
<br />
'''Status:''' Intel and VIA based boards should be mostly configuration free, AMD boards still have defines in their romstage.<br />
<br />
'''Developers:''' Patrick, Uwe<br />
<br />
== Unify ACPI ==<br />
* Figure out generic ACPI code and deduplicate it.<br />
* Fix issues like http://www.coreboot.org/pipermail/coreboot/2011-May/065179.html<br />
<br />
Done:<br />
* Every ACPI board has its own routines to compile the ACPI sources. Unify that.<br />
<br />
= More ideas =<br />
<br />
== CMOS handling ==<br />
<br />
The subprojects are ordered in a way that minimizes lost work.<br />
<br />
=== Simplify get_option ===<br />
Replace &lt;code&gt;get_option(VALstart, VALlen, default)&lt;/code&gt; with a macro that hides start/len in something like &lt;code&gt;get_option(VAL, default)&lt;/code&gt;<br />
<br />
=== Use nvramtool for static option table creation ===<br />
Instead of maintaining two tools (build_opt_tbl, nvramtool), maintain only one. This mostly requires adding an binary output writer to nvramtool, a cmos.layout parser already exists<br />
<br />
=== Implement a new cmos.layout format ===<br />
The current layout is simple to parse, but not so simple to maintain or extend.<br />
Create a format that combines the various fields into a single representation, eg.<br />
<br />
&lt;code&gt;<br />
400/8 century enum { 0x19=&quot;1900&quot;, 0x20=&quot;2000&quot;, 0x21=&quot;2100&quot; }<br />
<br />
408/512 some_string string<br />
<br />
984/16 checksum checksum 392 983<br />
&lt;/code&gt;<br />
<br />
=== Implement an include statement ===<br />
That way, we can have global fields (RTC, century byte), per chipset component fields (defined by northbrigde/southbridge/superio), per mainboard fields at their appropriate places.<br />
<br />
=== CMOS defaults ===<br />
Allow (somehow) to define defaults for all CMOS fields, and create a static table from that. Use that at runtime if the CMOS checksum fails.<br />
In the above format, it could simply be a suffix &lt;code&gt;default=VALUE&lt;/code&gt;<br />
Also drop the &quot;default&quot; argument in get_options. As components have their own cmos.layout snippets, we can always take those definitions' defaults, even if mainboards don't make use of CMOS themselves.<br />
<br />
=== Value overrides ===<br />
A chipset might provide options (eg. SATA/IDE) that a board might override (eg. because it doesn't provide IDE even if the chipset would support it). Allow the mainboard to override config options. This wouldn't just set a new default, but drop the option from CMOS entirely, hardcoding the value in the build. Some autogenerated #ifdef/#define magic might help there.<br />
<br />
=== Provide update paths and avoid conflicts in addressing ===<br />
Research topic: How could updates to nvram configuration (eg. new fields) be handled safely, and how could we get away from carving out the CMOS memory space manually? (one proposal: http://article.gmane.org/gmane.linux.bios/64572)<br />
<br />
=== Checksums ===<br />
<br />
The Linux kernel driver expects a non-inverted CMOS checksum for the &quot;PC&quot; area. coreboot inverts this checksum, which makes nvram unusable for the driver. This should be fixed.<br />
<br />
== Unify UMA / onboard video code and config ==<br />
<br />
Unify CONFIG_VIDEO_MB, CONFIG_GFXUMA, and similar options and make all code honor them.<br />
<br />
== Add / Unify / Test kconfig compile-time options and runtime CMOS options in coreboot ==<br />
<br />
Some coreboot options are compile-time configurable only at the moment (via kconfig), but should also be runtime-configurable via CMOS/NVRAM options. We should fix this.<br />
<br />
* Make all options (where it makes sense) run-time configurable via CMOS options, in addition to having sane compile-time defaults configured via kconfig.<br />
* This includes many options which are northbridge-specific, many southbridge-specific, and some board-specific ones.<br />
* Example options: Enable/disable IDE channel(s) / SATA / USB / SCSI / etc., enable/disable UDMA on older boards, amount of memory used for IGP/UMA, choice between IDE or NAND flash (on CS5536 boards), IDE 40/80 pin cable selection (VT8237R boards for example), and many more.<br />
* Some of these options are already handled in the code via CMOS options, some are compile-time only so far, so do not yet exist at all.<br />
<br />
== Kconfig TODO ==<br />
<br />
Notes / Style guide:<br />
<br />
* Any bool variables that are (re-)defined to 'y' in Kconfig files can be simplified by using '''select FOO''' instead of the usual paragraph, as long as they're defined globally as '''default n''' boolean elsewhere.<br />
* Use '''bool''' instead of '''boolean'''.<br />
* Use '''default n''' instead of '''default false'''.<br />
<br />
Various post-conversion things to consider:<br />
<br />
* Consider ways to move crt0-y and ldscript-y out of $(src)/arch/i386/Makefile.inc where appropriate (ie. component specific)<br />
* Make various CONFIG_* variable which were in each board's Kconfig file global or per-chipset options (instead of per-board). Examples:<br />
** UDELAY_TSC, TSC_X86RDTSC_CALIBRATE_WITH_TIMER2 (also check UDELAY_IO, APIC, etc.)<br />
** ...<br />
<br />
Stuff to port from v3 to v4:<br />
<br />
* All boards that are in v3 but not in v4 (especially Geode LX stuff. Also check amd/model_gx*).<br />
* Some remaining useful Kconfig options.<br />
<br />
== USB Debug Console ==<br />
<br />
Fix USB debug console and make the Kconfig choice actually work. Right now it's possible to transmit single characters but it's not really hooked up.<br />
<br />
== Clean up Assembler / Linker mess ==<br />
<br />
* Drop / combine / normalize .ld/.lb/.lds linker scripts.<br />
* Move them to a common place.<br />
* Drop / combine / normalize .inc / .S files.<br />
<br />
== Geode issues ==<br />
<br />
* Fix / Unify vsmsetup.c.<br />
* Fix CS5535/CS5536/GX2/LX &quot;chipsetinit&quot; issue.<br />
<br />
== Stack and Suspend/Resume ==<br />
<br />
* Use CONFIG_RAMBASE + HIGH_MEMORY_SAFE instead of 0x40000 for stack.<br />
<br />
== Fix Suspend/Resume on AMD64 ==<br />
<br />
* Use cbmem in romstage on the AMD64 board(s) that have suspend/resume.<br />
<br />
== printk into buffer ==<br />
<br />
Port the v3 feature that printk can write into a buffer (that might be usable from the client OS, or dumped to output, as soon as output exists).<br />
<br />
Consider use cases first (no need to provide buffer support, if all it would be useful for is buffering pre-CAR messages - which can't be buffered).<br />
<br />
== Global variables ==<br />
<br />
* Port the global variables framework from v3.<br />
* Make use of it where appropriate.<br />
<br />
== Clear phases in romstage ==<br />
<br />
* Split up the code (esp. in romstage) into more sensibly separated phases.<br />
* Maybe use v3 for inspiration where the lines can be drawn.<br />
<br />
== Refactor SMBUS code ==<br />
<br />
We have tons of duplication in the smbus/spd related functions and #defines. Every chipset (and sometimes board) does the same with the exception of the 2 or 3 boards that multiplex spd roms.<br />
* Deduplicate SMBUS related defines, they're virtually everywhere (and all the same)<br />
* Deduplicate the lowlevel functions - they should really be the same (except for some style differences)<br />
* Deduplicate the non-multiplexing highlevel functions. Mark them weak, so multiplexing boards can simply provide their own variant, which override the weak functions automatically<br />
<br />
== Move all registers/chip definitions in XML format for all tools ==<br />
<br />
For easy creating definitions of new chips, or editing old register definitions, improve readability support, and add support for humanless parsing the logs we decide move all data for msrtool, inteltool, superiotool, etc in XML-based format. See here: [[XML]]<br />
<br />
== Device dependency engine ==<br />
<br />
We have a couple of places where we want to disable (or otherwise reconfigure) a device if another one is active: SATA and IDE covering the same ports, integrated graphics / plugin video cards, ...<br />
Right now, such things are done &quot;somewhere&quot;, usually far away from any meaningful context. This idea isn't as actionable as the others as it's still missing even a sketch of a design.<br />
<br />
* Find a good place (or multiple places) where such device decisions can be made<br />
* Refactor the code to make use of it<br />
<br />
== Clean out duplicates ==<br />
<br />
Toold like http://duplo.giants.ch/ or http://pmd.sourceforge.net/cpd.html might be able to help finding duplicates that can be factored out.<br />
<br />
= Finished =<br />
<br />
== Port v3 Resource Allocator ==<br />
<br />
The v3 resource allocator should be ported to v4.<br />
<br />
'''Status:''' Upstream. It's limited to one area for resources, that doesn't overlap with fixed resources.<br />
<br />
'''Developers:''' Myles<br />
<br />
== Config &amp; Build System ==<br />
<br />
The current system of generated Makefiles is non-ideal (for too many reasons for this little margin). Fix it, somehow. Use kconfig to improve the configuration management.<br />
<br />
'''Status:''' Upstream, boards are converted. Old system is gone. All boards build. HOWEVER, not all boards have been boot-tested yet, please report any issues you encounter!<br />
<br />
'''Developers:''' Stefan, Ron, Patrick, Uwe, Cristi<br />
<br />
== Unify text printing functions ==<br />
<br />
There are several copies of print_* and printk_* in the code. Unify them so everything is happier than before (because the disjoint features are merged).<br />
<br />
'''Status:''' Finished.<br />
<br />
'''Developers:''' Patrick, Stefan<br />
<br />
== Common payload location ==<br />
<br />
Many boards have different names for the payload in targets/.../Config.lb (payload.elf, filo.elf, etherboot.elf, etc) and locations (../payload.elf, or various absolute paths which only work for one developer). The problem will be fixed with kconfig, where the user specifies a payload manually in &quot;make menuconfig&quot;.<br />
<br />
'''Status:''' Finished.<br />
<br />
== Fix ALL build warnings ==<br />
<br />
* Someone has to do the deed.<br />
<br />
'''Status:''' Finished, the build usually issues no warnings. If you see warnings/errors, please report a bug.<br />
<br />
== Post codes ==<br />
<br />
Find all outb(x, 0x80) and replace them with post_code(). Use common numbers / defines across the boards.<br />
<br />
'''Status:''' Finished, except for some local delay routines in early smbus code.<br />
<br />
== Use central oprom init ==<br />
<br />
* Get rid of all vgabios.c, make all chipsets with own vgabios.c use devices/oprom/x86.c.<br />
* Use the realmode code for vsmsetup too.</div>Stepanhttp://www.coreboot.org/index.php?title=Infrastructure_Projects&diff=10904Infrastructure Projects2011-10-13T23:27:37Z<p>Stepan: /* Unify ACPI */</p>
<hr />
<div>This page collects a list of projects to improve the infrastructure of coreboot v4. Infrastructure means those parts of the code that aren't chipset or mainboard specific, but are used by all of them. The idea is to consolidate a list of things &quot;to do&quot; with their status and responsible developers.<br />
<br />
= In progress =<br />
<br />
== Low/High Tables ==<br />
<br />
SeaBIOS requires a copy of various BIOS tables outside the fseg as it overwrites that segment. Generally clean out the table generation code.<br />
<br />
'''Status:''' Upstream, implemented on some boards. There are problems on some chipsets/boards because of incorrect CONFIG_VIDEO_MB handling. The might be other issues, too (not clear, yet).<br />
<br />
{| border=&quot;0&quot; style=&quot;font-size: smaller&quot;<br />
|- bgcolor=&quot;#6699ff&quot;<br />
! align=&quot;left&quot; | Vendor/chipset<br />
! align=&quot;left&quot; | Tested<br />
! align=&quot;left&quot; | Comments<br />
<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/amdfam10<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/amdht<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/amdk8<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/amdmct<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/gx1<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/gx2<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/lx<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/e7501<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/e7520<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/e7525<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i3100<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i440bx<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82810<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82830<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i855<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i945<br />
| style=&quot;background:lime&quot; | Y<br />
| Tested on Kontron 986LCD-M and Roda RK886EX<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/cn400<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/cn700<br />
| style=&quot;background:lime&quot; | Y<br />
| Tested on VIA pc2500e.<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/cx700<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vt8601<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vt8623<br />
| ?<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vx800<br />
| ?<br />
| &amp;mdash;<br />
<br />
|}<br />
<br />
'''Developers:''' Stefan<br />
<br />
== CBFS ==<br />
<br />
A filesystem-alike layout for the coreboot image, to enable systems like bayou and to clean up the system in general (eg. no more buildrom).<br />
<br />
'''Status:'''<br />
<br />
Upstream, pre-CBFS infrastructure removed.<br />
<br />
There are places where using CBFS might be a good idea: Everything that makes use of external files, for example the VSA code in the Geode chipset code. VSA is converted, and tested on a couple of configurations, but untested on others.<br />
<br />
Some boards have issues with CBFS because it requires the whole ROM to be accessible at a quite early point in time (compared to the old mechanism). The following table contains validated knowledge if the ROM mapping happens at the right time.<br />
<br />
All boards that manage to boot in a tinybootblock configuration are capable at least for the used ROM size (it might be that larger ROMs would fail because they require mapping the larger space)<br />
<br />
{| border=&quot;0&quot; style=&quot;font-size: smaller&quot;<br />
|- bgcolor=&quot;#6699ff&quot;<br />
! align=&quot;left&quot; | Vendor/chipset<br />
! align=&quot;left&quot; | ROM enabled<br />
! align=&quot;left&quot; | Tiny bootblock<br />
! align=&quot;left&quot; | Status / Comments<br />
<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/amd8111<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| Not tested on hardware, yet.<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/cs5530<br />
| style=&quot;background:lime&quot; | Y<br />
| style=&quot;background:red&quot; | N<br />
| Not tested on hardware, yet.<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/cs5535<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/cs5536<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/sb600<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| amd/sb700<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| &amp;mdash;<br />
<br />
|- bgcolor=&quot;#dddddd&quot;<br />
| broadcom/bcm5785<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| Not tested on hardware, yet.<br />
<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/esb6300<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i3100<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82371eb<br />
| style=&quot;background:lime&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| Build- and runtime-tested on ASUS P2B by [[User:Uwe|Uwe Hermann]].<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82801ax<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82801bx<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82801cx<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82801dx<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82801ex<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| intel/i82801gx<br />
| style=&quot;background:lime&quot; | Y<br />
| style=&quot;background:lime&quot; | Y<br />
| Build- and runtime-tested on Kontron 986LCD-m by PatrickGeorgi<br />
<br />
|- bgcolor=&quot;#dddddd&quot;<br />
| nvidia/ck804<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| Not tested on hardware, yet.<br />
|- bgcolor=&quot;#dddddd&quot;<br />
| nvidia/mcp55<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| Not tested on hardware, yet.<br />
<br />
|- bgcolor=&quot;#dddddd&quot;<br />
| sis/sis966<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| Not tested on hardware, yet.<br />
<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vt8231<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vt8235<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vt8237r<br />
| style=&quot;background:yellow&quot; | Y<br />
| style=&quot;background:yellow&quot; | Y<br />
| &amp;mdash;<br />
|- bgcolor=&quot;#eeeeee&quot;<br />
| via/vt82c686<br />
| style=&quot;background:red&quot; | N<br />
| style=&quot;background:red&quot; | N<br />
| &amp;mdash;<br />
<br />
|}<br />
<br />
'''Developers:''' Stefan, Ron, Patrick, Myles, Uwe<br />
<br />
== Tiny Bootblock ==<br />
<br />
Right now, the decision whether to use fallback or normal is in cache_as_ram_auto.c in many boards. Make that generic again (also helps with further CBFSification at some point).<br />
<br />
'''Status:''' Available in Kconfig, works on a couple of boards. Requires per southbridge changes (and northbridge in some cases) on many boards (related to ROM enable, see CBFS section).<br />
<br />
'''Developers:''' Patrick<br />
<br />
== Remove .c includes ==<br />
<br />
Currently we include lots of code in the romstage using the preprocessor. This makes it harder to support new boards (where chipset components are supported already) and maintenance in general. So we should get rid of it where possible, using the linker for CAR boards and the build system for the remaining non-CAR boards appropriately.<br />
<br />
'''Status:''' CAR boards only for now, to keep the project manageable. i945 is modified already, and boards based on it have only one or two remaining source files they include. Interacts with the next project &quot;Move configuration to Kconfig&quot;, which ensures that code still sees all configuration when it is compiled separately.<br />
<br />
'''Developers:''' Patrick, Uwe<br />
<br />
== Move configuration to Kconfig ==<br />
<br />
Many boards have lots of &lt;code&gt;#define VAR somevalue&lt;/code&gt; statements in their romstage.c which define how certain component drivers are compiled. With Kconfig, there's a better place to store them. This project is about moving all configuration values out of romstage.c (and other places if appropriate) and into Kconfig. &lt;code&gt;util/lint/lint-001-no-global-config-in-romstage&lt;/code&gt; helps figuring out what remains to be done.<br />
<br />
'''Status:''' Intel and VIA based boards should be mostly configuration free, AMD boards still have defines in their romstage.<br />
<br />
'''Developers:''' Patrick, Uwe<br />
<br />
== Unify ACPI ==<br />
* Figure out generic ACPI code and deduplicate it.<br />
* Fix issues like http://www.coreboot.org/pipermail/coreboot/2011-May/065179.html<br />
<br />
Done:<br />
* Every ACPI board has its own routines to compile the ACPI sources. Unify that.<br />
<br />
= More ideas =<br />
<br />
== CMOS handling ==<br />
<br />
The subprojects are ordered in a way that minimizes lost work.<br />
<br />
=== Simplify get_option ===<br />
Replace &lt;code&gt;get_option(VALstart, VALlen, default)&lt;/code&gt; with a macro that hides start/len in something like &lt;code&gt;get_option(VAL, default)&lt;/code&gt;<br />
<br />
=== Use nvramtool for static option table creation ===<br />
Instead of maintaining two tools (build_opt_tbl, nvramtool), maintain only one. This mostly requires adding an binary output writer to nvramtool, a cmos.layout parser already exists<br />
<br />
=== Implement a new cmos.layout format ===<br />
The current layout is simple to parse, but not so simple to maintain or extend.<br />
Create a format that combines the various fields into a single representation, eg.<br />
<br />
&lt;code&gt;<br />
400/8 century enum { 0x19=&quot;1900&quot;, 0x20=&quot;2000&quot;, 0x21=&quot;2100&quot; }<br />
<br />
408/512 some_string string<br />
<br />
984/16 checksum checksum 392 983<br />
&lt;/code&gt;<br />
<br />
=== Implement an include statement ===<br />
That way, we can have global fields (RTC, century byte), per chipset component fields (defined by northbrigde/southbridge/superio), per mainboard fields at their appropriate places.<br />
<br />
=== CMOS defaults ===<br />
Allow (somehow) to define defaults for all CMOS fields, and create a static table from that. Use that at runtime if the CMOS checksum fails.<br />
In the above format, it could simply be a suffix &lt;code&gt;default=VALUE&lt;/code&gt;<br />
Also drop the &quot;default&quot; argument in get_options. As components have their own cmos.layout snippets, we can always take those definitions' defaults, even if mainboards don't make use of CMOS themselves.<br />
<br />
=== Value overrides ===<br />
A chipset might provide options (eg. SATA/IDE) that a board might override (eg. because it doesn't provide IDE even if the chipset would support it). Allow the mainboard to override config options. This wouldn't just set a new default, but drop the option from CMOS entirely, hardcoding the value in the build. Some autogenerated #ifdef/#define magic might help there.<br />
<br />
=== Provide update paths and avoid conflicts in addressing ===<br />
Research topic: How could updates to nvram configuration (eg. new fields) be handled safely, and how could we get away from carving out the CMOS memory space manually? (one proposal: http://article.gmane.org/gmane.linux.bios/64572)<br />
<br />
=== Checksums ===<br />
<br />
The Linux kernel driver expects a non-inverted CMOS checksum for the &quot;PC&quot; area. coreboot inverts this checksum, which makes nvram unusable for the driver. This should be fixed.<br />
<br />
== Unify UMA / onboard video code and config ==<br />
<br />
Unify CONFIG_VIDEO_MB, CONFIG_GFXUMA, and similar options and make all code honor them.<br />
<br />
== Add / Unify / Test kconfig compile-time options and runtime CMOS options in coreboot ==<br />
<br />
Some coreboot options are compile-time configurable only at the moment (via kconfig), but should also be runtime-configurable via CMOS/NVRAM options. We should fix this.<br />
<br />
* Make all options (where it makes sense) run-time configurable via CMOS options, in addition to having sane compile-time defaults configured via kconfig.<br />
* This includes many options which are northbridge-specific, many southbridge-specific, and some board-specific ones.<br />
* Example options: Enable/disable IDE channel(s) / SATA / USB / SCSI / etc., enable/disable UDMA on older boards, amount of memory used for IGP/UMA, choice between IDE or NAND flash (on CS5536 boards), IDE 40/80 pin cable selection (VT8237R boards for example), and many more.<br />
* Some of these options are already handled in the code via CMOS options, some are compile-time only so far, so do not yet exist at all.<br />
<br />
== Kconfig TODO ==<br />
<br />
Notes / Style guide:<br />
<br />
* Any bool variables that are (re-)defined to 'y' in Kconfig files can be simplified by using '''select FOO''' instead of the usual paragraph, as long as they're defined globally as '''default n''' boolean elsewhere.<br />
* Use '''bool''' instead of '''boolean'''.<br />
* Use '''default n''' instead of '''default false'''.<br />
<br />
Various post-conversion things to consider:<br />
<br />
* Consider ways to move crt0-y and ldscript-y out of $(src)/arch/i386/Makefile.inc where appropriate (ie. component specific)<br />
* Make various CONFIG_* variable which were in each board's Kconfig file global or per-chipset options (instead of per-board). Examples:<br />
** UDELAY_TSC, TSC_X86RDTSC_CALIBRATE_WITH_TIMER2 (also check UDELAY_IO, APIC, etc.)<br />
** ...<br />
<br />
Stuff to port from v3 to v4:<br />
<br />
* All boards that are in v3 but not in v4 (especially Geode LX stuff. Also check amd/model_gx*).<br />
* Some remaining useful Kconfig options.<br />
<br />
== USB Debug Console ==<br />
<br />
Fix USB debug console and make the Kconfig choice actually work. Right now it's possible to transmit single characters but it's not really hooked up.<br />
<br />
== Clean up Assembler / Linker mess ==<br />
<br />
* Drop / combine / normalize .ld/.lb/.lds linker scripts.<br />
* Move them to a common place.<br />
* Drop / combine / normalize .inc / .S files.<br />
<br />
== Geode issues ==<br />
<br />
* Fix / Unify vsmsetup.c.<br />
* Fix CS5535/CS5536/GX2/LX &quot;chipsetinit&quot; issue.<br />
<br />
== Use central oprom init ==<br />
<br />
* Get rid of all vgabios.c, make all chipsets with own vgabios.c use devices/oprom/x86.c.<br />
* Use the realmode code for vsmsetup too.<br />
<br />
== Stack and Suspend/Resume ==<br />
<br />
* Use CONFIG_RAMBASE + HIGH_MEMORY_SAFE instead of 0x40000 for stack.<br />
<br />
== Fix Suspend/Resume on AMD64 ==<br />
<br />
* Use cbmem in romstage on the AMD64 board(s) that have suspend/resume.<br />
<br />
== printk into buffer ==<br />
<br />
Port the v3 feature that printk can write into a buffer (that might be usable from the client OS, or dumped to output, as soon as output exists).<br />
<br />
Consider use cases first (no need to provide buffer support, if all it would be useful for is buffering pre-CAR messages - which can't be buffered).<br />
<br />
== Global variables ==<br />
<br />
* Port the global variables framework from v3.<br />
* Make use of it where appropriate.<br />
<br />
== Clear phases in romstage ==<br />
<br />
* Split up the code (esp. in romstage) into more sensibly separated phases.<br />
* Maybe use v3 for inspiration where the lines can be drawn.<br />
<br />
== Refactor SMBUS code ==<br />
<br />
We have tons of duplication in the smbus/spd related functions and #defines. Every chipset (and sometimes board) does the same with the exception of the 2 or 3 boards that multiplex spd roms.<br />
* Deduplicate SMBUS related defines, they're virtually everywhere (and all the same)<br />
* Deduplicate the lowlevel functions - they should really be the same (except for some style differences)<br />
* Deduplicate the non-multiplexing highlevel functions. Mark them weak, so multiplexing boards can simply provide their own variant, which override the weak functions automatically<br />
<br />
== Move all registers/chip definitions in XML format for all tools ==<br />
<br />
For easy creating definitions of new chips, or editing old register definitions, improve readability support, and add support for humanless parsing the logs we decide move all data for msrtool, inteltool, superiotool, etc in XML-based format. See here: [[XML]]<br />
<br />
== Device dependency engine ==<br />
<br />
We have a couple of places where we want to disable (or otherwise reconfigure) a device if another one is active: SATA and IDE covering the same ports, integrated graphics / plugin video cards, ...<br />
Right now, such things are done &quot;somewhere&quot;, usually far away from any meaningful context. This idea isn't as actionable as the others as it's still missing even a sketch of a design.<br />
<br />
* Find a good place (or multiple places) where such device decisions can be made<br />
* Refactor the code to make use of it<br />
<br />
== Clean out duplicates ==<br />
<br />
Toold like http://duplo.giants.ch/ or http://pmd.sourceforge.net/cpd.html might be able to help finding duplicates that can be factored out.<br />
<br />
= Finished =<br />
<br />
== Port v3 Resource Allocator ==<br />
<br />
The v3 resource allocator should be ported to v4.<br />
<br />
'''Status:''' Upstream. It's limited to one area for resources, that doesn't overlap with fixed resources.<br />
<br />
'''Developers:''' Myles<br />
<br />
== Config &amp; Build System ==<br />
<br />
The current system of generated Makefiles is non-ideal (for too many reasons for this little margin). Fix it, somehow. Use kconfig to improve the configuration management.<br />
<br />
'''Status:''' Upstream, boards are converted. Old system is gone. All boards build. HOWEVER, not all boards have been boot-tested yet, please report any issues you encounter!<br />
<br />
'''Developers:''' Stefan, Ron, Patrick, Uwe, Cristi<br />
<br />
== Unify text printing functions ==<br />
<br />
There are several copies of print_* and printk_* in the code. Unify them so everything is happier than before (because the disjoint features are merged).<br />
<br />
'''Status:''' Finished.<br />
<br />
'''Developers:''' Patrick, Stefan<br />
<br />
== Common payload location ==<br />
<br />
Many boards have different names for the payload in targets/.../Config.lb (payload.elf, filo.elf, etherboot.elf, etc) and locations (../payload.elf, or various absolute paths which only work for one developer). The problem will be fixed with kconfig, where the user specifies a payload manually in &quot;make menuconfig&quot;.<br />
<br />
'''Status:''' Finished.<br />
<br />
== Fix ALL build warnings ==<br />
<br />
* Someone has to do the deed.<br />
<br />
'''Status:''' Finished, the build usually issues no warnings. If you see warnings/errors, please report a bug.<br />
<br />
== Post codes ==<br />
<br />
Find all outb(x, 0x80) and replace them with post_code(). Use common numbers / defines across the boards.<br />
<br />
'''Status:''' Finished, except for some local delay routines in early smbus code.</div>Stepan