Skip to contentSkip to conversation

kernel guide to space

DISCUSSION Michael S. Tsirkin 16 participants 23 messages Jul 11, 2005 – Jul 22, 2005

lore
Share & tools
lore
#0 lore raw

Hi!
I've been tasked with edicating some new hires on linux kernel coding style. While we have Documentation/CodingStyle, it skips detail that is supposed to be learned by example.

Since I've been burned by this a couple of times myself till I learned, I've put together a short list of rules complementing Documentation/CodingStyle. This list is attached, below.

Please cc me directly with comments, if any.

Thanks,
MST

---

kernel guide to space AKA a boring list of rules
http://www.mellanox.com/mst/boring.txt

This text deals mostly with whitespace issues, hence the name.

Whitespace -- In computer science, a whitespace (or a whitespace character) is any character which does not display itself but does take up space.
From Wikipedia, the free encyclopedia.

1. Read Documentation/CodingStyle. Yes, it applies to you. When working on a specific driver/subsystem, try to follow the style of the surrounding codebase.

2. The last character on a line is never a whitespace
Get a decent editor and don't leave whitespace at the end of lines.
Documentation/CodingStyle

Whitespace issues:

3. Space rules for C

3a. Binary operators

	+ - / * %
	== !=  > < >= <= && || 
	& | ^ << >> 
	= *= /= %= += -= <<= >>= &= ^= |=

	spaces around the operator
	a + b

3b. Unary operators

	! ~
	+ - *
	&

	no space between operator and operand
	*a

3c. * in types
Leave space between name and * in types. Multiple * dont need additional space between them.

struct foo **bar;

3d. Conditional
?:
spaces around both ? and :
a ? b : c

3e. sizeof
space after the operator
sizeof a

3f. Braces etc

	() [] -> .

	no space around any of these (but see 3h)
	foo(bar)

3g. Comma

	,
	space after comma, no space before comma
	foo, bar

3h. Semicolon

	;
	no space before semicolon
	foo;

3i. if/else/do/while/for/switch

	space between if/else/do/while and following/preceeding
	statements/expressions, if any:

	if (a) {
	} else {
	}

	do {
	} while (b);

3j. Labels
goto and case labels should have a line of their own (possibly with a comment).
No space before colon in labels.

int foobar()

{
	...
foolabel: /* short comment */
	foo();
}

4. Indentation rules for C
Use tabs, not spaces, for indentation. Tabs should be 8 characters wide.

4a. Labels

	case labels should be indented same as the switch statement.
	statements occurring after a case label are indented by one level.

	switch (foo) {
	case foo:
		bar();
	default:
		break;
	}

4b. Global scope
Functions, type definitions/declarations, defines, global variables etc are global scope. Start them at the first character in a line (indent level 0).

static struct foo *foo_bar(struct foo *first, struct bar *second,

			   struct foobar* thirsd);

4c. Breaking long lines
Descendants are always substantially shorter than the parent and are placed substantially to the right.
Documentation/CodingStyle

Descendant must be indented at least to the level of the innermost compound expression in the parent. All descendants at the same level are indented the same.
if (foobar(.................................) + barbar * foobar(bar +
foo * oof)) {
}

5. Blank lines
One blank line between functions.

void foo()
{
}

/* comment */
void bar()
{
}

No more than one blank line in a row. Last (or first) line in a file is never blank.

Non-whitespace issues:

6. One-line statement does not need a {} block, so dont put it into one

	if (foo)
		bar;

7. Comments
Dont use C99 // comments.

8. Return codes

	Functions that return success/failure status, should use 0 for success,
	a negative value for failure.
	Error codes are in linux/errno.h .

	if (do_something()) {
		handle_error();
		return -EINVAL;
	}

	Functions that test a condition return 1 if condition is satisfied,
	0 if its not.

	if (is_condition())
		condition_true();

9. Data types
Standard linux types are in linux/types.h .
See also Linux Device Drivers, Third Edition,
Chapter 11: Data Types in the Kernel. http://lwn.net/images/pdf/LDD3/

9a. Integer types
int is the default integer type.
Use unsigned type if you perform bit operations (<<,>>,&,|,~). Use unsigned long if you have to fit a pointer into integer. long long is at least 64 bit wide on all platforms. char is for ASCII characters and strings.
Use u8,u16,u32,u64 if you need an integer of a specific size.

9b. typedef
Using typedefs to hide the data type is generally discouraged. typedefs to function types are ok, since these can get very long.

typedef struct foo *(foo_bar_handler)(struct foo *first, struct bar *second,

				      struct foobar* thirsd);

Editor configuration:

9. The following is helpful with VIM

	set cinoptions=(0:0

Michael S. Tsirkin

Signature · 1 line
MST
#1 lore raw

Michael S. Tsirkin wrote (ao):

Quoted 2 lines

Use tabs, not spaces, for indentation. Tabs should be 8 characters wide.

A tab is a tab. The editor/viewer can be configured to show 2, 3, 4, 8, any amount of characters, right?

Sander

Signature · 2 lines
Humilis IT Services and Solutions
http://www.humilis.net
#2 lore raw
Quoted 6 lines · Sander

Michael S. Tsirkin wrote (ao):

Quoted 2 lines

Use tabs, not spaces, for indentation. Tabs should be 8 characters wide.

A tab is a tab. The editor/viewer can be configured to show 2, 3, 4, 8, any amount of characters, right?

text with 8-char tabs:

struct s {
int n; /* comment */
unsigned int u; /* comment */
};

Same text viewed with tabs set to 4-char width:

struct s {
int n; /* comment */
unsigned int u; /* comment */
};

Comments are not aligned anymore
--
vda

#3 lore raw
Quoted 7 lines · Denis Vlasenko

text with 8-char tabs:

struct s {
int n; /* comment */
unsigned int u; /* comment */
};

Quoted 8 lines

Same text viewed with tabs set to 4-char width:

struct s {
int n; /* comment */
unsigned int u; /* comment */
};

Comments are not aligned anymore

Best rule IMO is to use tabs for indentation and spaces for alignment. This way tab size can be changed without breaking alignment.

#4 lore raw
Quoted 15 lines · Patrick McHardy
Quoted 14 lines · Denis Vlasenko

text with 8-char tabs:

struct s {
int n; /* comment */
unsigned int u; /* comment */
};

Same text viewed with tabs set to 4-char width:

struct s {
int n; /* comment */
unsigned int u; /* comment */
};

Quoted 4 lines
Quoted 1 line

Comments are not aligned anymore

Best rule IMO is to use tabs for indentation and spaces for alignment. This way tab size can be changed without breaking alignment.

Or just disallow tabs altogether. At Analogic we had several hundred thousand lines of imaging code from various engineers around the world. They would set their tabs so everything looked fine on their computers. On other computers, it looked like hell so engineers who had to merge code spent hundreds of wasted hours lining up the code. The "cleanup" work never stopped! That was until, we made a rule that all code would be run through a filter that would remove tabs and substitute spaces (of the width the writer intended). No code that is released contains even a single tab anymode.

The files are larger of course, but even lap-tops have gigabyte drives now-days and the duplicate spaces give compression utilities something to do.

Cheers,
Dick Johnson
Penguin : Linux version 2.6.12 on an i686 machine (5537.79 BogoMips).
Notice : All mail here is now cached for review by Dictator Bush.
98.36% of all statistics are fiction.

#5 lore raw
Quoted 1 line · Dick Johnson

Or just disallow tabs altogether. At Analogic we ...

This is the Linux kernel, not Analogic.

We use tabs for indentation. You can set the number of physical spaces per tab however you want in your editor, but it had better look good (and stay within 80 columns) when the rest of us use 8 spaces per tab.

Signature · 3 lines
                  I won't rest till it's the best ...
                  Programmer, Linux Scalability
                  Paul Jackson <[email protected]> 1.925.600.0401
#6 lore raw
Quoted 9 lines · Paul Jackson
Quoted 1 line · Dick Johnson

Or just disallow tabs altogether. At Analogic we ...

This is the Linux kernel, not Analogic.

We use tabs for indentation. You can set the number of physical spaces per tab however you want in your editor, but it had better look good (and stay within 80 columns)

I don't think there's a strict 80 column rule anymore. It's 2005...

Lee

#7 lore raw
Quoted 1 line · Lee

I don't think there's a strict 80 column rule anymore. It's 2005...

Look back through the lkml archives. One will find repeated requests to keep code within 80 columns. It maybe 2005, but this is the kernel.

Signature · 3 lines
                  I won't rest till it's the best ...
                  Programmer, Linux Scalability
                  Paul Jackson <[email protected]> 1.925.600.0401
#8 lore raw
In reply to Lee Revell
Quoted 4 lines · Lee Revell
Quoted 3 lines · Paul Jackson
Quoted 1 line · Dick Johnson

Or just disallow tabs altogether. At Analogic we ...

Quoted 8 lines
Quoted 6 lines

This is the Linux kernel, not Analogic.

We use tabs for indentation. You can set the number of physical spaces per tab however you want in your editor, but it had better look good (and stay within 80 columns)

I don't think there's a strict 80 column rule anymore. It's 2005...

Think again. There are a lot of people who use 80 column windows so that we can see two code windows side-by-side.

#9 lore raw
In reply to Michael S. Tsirkin

Hi,

Quoted 3 lines · Michael S. Tsirkin

3e. sizeof
space after the operator
sizeof a

If braces are used no spaces please : sizeof(struct foo)

Quoted 6 lines

4c. Breaking long lines
Descendants are always substantially shorter than the parent and are placed substantially to the right.
Documentation/CodingStyle

Quoted 7 lines

Descendant must be indented at least to the level of the innermost compound expression in the parent. All descendants at the same level are indented the same.
if (foobar(.................................) + barbar * foobar(bar +
foo * oof)) {
}

Ugh, that's as ugly as it can get... Something like below is much easier to read...

        if (foobar(.................................) +
            barbar * foobar(bar + foo * oof)) {
        }
Signature · 1 line
Dmitry
#10 lore raw
Quoted 8 lines · Dmitry Torokhov
Quoted 7 lines

Descendant must be indented at least to the level of the innermost compound expression in the parent. All descendants at the same level are indented the same.
if (foobar(.................................) + barbar * foobar(bar +
foo * oof)) {
}

Quoted 6 lines

Ugh, that's as ugly as it can get... Something like below is much easier to read...

        if (foobar(.................................) +
            barbar * foobar(bar + foo * oof)) {
        }

Even easier is

         if (foobar(.................................)
             + barbar * foobar(bar + foo * oof)) {
         }

since a statement cannot start with binary operators
and as such we are SURE that there must have been something before. And this matches with old shop owner calculations like:

1
+ 2
+ 3
----
6

which we all know since early math classes.

Regards

Ingo Oeser

#11 lore raw
In reply to Michael S. Tsirkin
Quoted 5 lines

3c. * in types
Leave space between name and * in types. Multiple * dont need additional space between them.

struct foo **bar;

unless you declare a fuction:

int*
function_style_for_easy_grep(...)

{
	...
}

I like this style because I can grep for ^function_style_for_easy_grep and quickly find function def.

int
*function_style_for_easy_grep(...) ..

would make it harder.

Quoted 3 lines

3e. sizeof
space after the operator
sizeof a

I use sizeof(a) always (both for sizeof(type) and sizeof(expr)).

Quoted 10 lines

3i. if/else/do/while/for/switch

	space between if/else/do/while and following/preceeding
	statements/expressions, if any:

	if (a) {
	} else {
	}

	do {
	} while (b);

What's wrong with if(expr) ? Rationale?

Quoted 5 lines

4c. Breaking long lines
Descendants are always substantially shorter than the parent and are placed substantially to the right.
Documentation/CodingStyle

Quoted 7 lines

Descendant must be indented at least to the level of the innermost compound expression in the parent. All descendants at the same level are indented the same.
if (foobar(.................................) + barbar * foobar(bar +
foo * oof)) {
}

Avoid this. If needed, use a temporary. Save a few brain cells of poor reader.

Quoted 3 lines

6. One-line statement does not need a {} block, so dont put it into one

	if (foo)
		bar;

Disagree. Common case of hard-to-notice bug:

	if(foo)
		bar()
...after some time code evolves into:
	if(foo)
		/*
		 * Wee need to barify it, or else pagecache gets foobar'ed
		 */
		bar();
...after some more time:
	if(foo)
		/*
		 * Wee need to barify it, or else pagecache gets foobar'ed.
		 * Also we need to bazify it.
		 */
		bar();
		baz();

Thus we may be better to slighty encourage use of {}s even if they are not needed:

	if(foo) {
		bar();
	}
Quoted 2 lines

9a. Integer types
Use unsigned long if you have to fit a pointer into integer.

This is a porting nightmare waiting to happen.
Why dont we have ptr_t instead?

Quoted 1 line

long long is at least 64 bit wide on all platforms.

hugeint or hugeint_t

And also irqflags_t for spinlock_irqsave(&lock, flags), jiffies_t for jiffies.

Quoted 6 lines

9b. typedef
Using typedefs to hide the data type is generally discouraged. typedefs to function types are ok, since these can get very long.

typedef struct foo *(foo_bar_handler)(struct foo *first, struct bar *second,

				      struct foobar* thirsd);

? did you mean struct foo (*foo_bar_handler)(... or struct foo* foo_bar_handler(... --
vda

#12 lore raw
Quoted 8 lines · Denis Vlasenko
Quoted 5 lines

3c. * in types
Leave space between name and * in types. Multiple * dont need additional space between them.

struct foo **bar;

unless you declare a fuction:

Quoted 9 lines

int*
function_style_for_easy_grep(...)

{
	...
}

I like this style because I can grep for ^function_style_for_easy_grep and quickly find function def.

That's a pretty bad argument, since most functions aren't declared that way, and there are much better source code navigational tools, like cscope and ctags.

#13 lore raw
In reply to Michael S. Tsirkin

Nice work - thanks.

A couple of possible additions:

* Keep lines within 80 columns.

* Be consistent in use of tabs versus spaces. If the rest of a file is indented using tabs, then any change you make should be indented the same way, not with spaces. It is easy to unknowingly introduce spaces in a patch by cutting and pasting something in one of the many desktop UI environments that dont preserve tabs across a cut and paste.

* See also Documentation/kernel-doc-nano-HOWTO.txt for formatting the documentation for external functions and data to work with the kernels DocBook automatically extractable documentation.

* Multiline comments are shown as:

/*
* This is a big comment. It is full of sound
* and fury, signifying nothing. Now is the time
* for all good men to come to the aid of their
* country.
*/

Signature · 3 lines
                  I won't rest till it's the best ...
                  Programmer, Linux Scalability
                  Paul Jackson <[email protected]> 1.925.600.0401
#14 lore raw
In reply to Michael S. Tsirkin
Quoted 1 line · Michael S. Tsirkin

[snip]

Quoted 3 lines

kernel guide to space AKA a boring list of rules
http://www.mellanox.com/mst/boring.txt

[snip]

Quoted 7 lines

3c. * in types
Leave space between name and * in types. Multiple * dont need additional space between them.

struct foo **bar;

Don't put spaces between `*' and the name when declaring variables,
even if it's not a double pointer. int * foo; is ugly. Common
convention is int *foo;

Quoted 4 lines

3e. sizeof
space after the operator
sizeof a

I don't think that's a hard rule, there's plenty of code that does "sizeof(type)" and not "sizeof (type)", and whitespace cleanup patches I've done that change "sizeof (type)" into "sizeof(type)" have generally been accepted.

[snip]

Quoted 4 lines

4. Indentation rules for C
Use tabs, not spaces, for indentation. Tabs should be 8 characters wide.

A tab is a tab is a tab, how it's displayed is up to the editor showing the file.

[snip]

Quoted 4 lines

static struct foo *foo_bar(struct foo *first, struct bar *second,

                           struct foobar* thirsd);

In this example you are not consistently placing your *'s, "struct foo *first" vs "struct foobar* thirsd". Common practice is "struct foo *first".

[snip]

Quoted 4 lines

No more than one blank line in a row. Last (or first) line in a file is never blank.

Files should end with a newline. gcc will even warn (with -pedantic) if this is not so.

"line<nl>
line"

is wrong,

"line<nl>
line<nl>
"

is right.

Quoted 6 lines

Non-whitespace issues:

6. One-line statement does not need a {} block, so dont put it into one

        if (foo)
                bar;

Not always so, if `bar' is a macro adding {} may be safer. Also sometimes adding {} improves readability, which is important.

Quoted 3 lines

7. Comments
Dont use C99 // comments.

s/Dont/Don't/

Quoted 7 lines

9a. Integer types
int is the default integer type.
Use unsigned type if you perform bit operations (<<,>>,&,|,~). Use unsigned long if you have to fit a pointer into integer. long long is at least 64 bit wide on all platforms. char is for ASCII characters and strings.
Use u8,u16,u32,u64 if you need an integer of a specific size.

u8,s8,u16,s16,u32,s32,u64,s64

Signature · 3 lines
Jesper Juhl <[email protected]>
Don't top-post  http://www.catb.org/~esr/jargon/html/T/top-post.html
Plain text mails only, please      http://www.expita.com/nomime.html
#15 lore raw

Quoting r. Jesper Juhl <[email protected]>:

Quoted 6 lines
Quoted 3 lines

static struct foo *foo_bar(struct foo *first, struct bar *second,

                           struct foobar* thirsd);

In this example you are not consistently placing your *'s, "struct foo *first" vs "struct foobar* thirsd". Common practice is "struct foo *first".

Doh. Right. Thanks!

Signature · 1 line
MST
#16 lore raw
In reply to Jesper Juhl
Quoted 9 lines
Quoted 6 lines

3c. * in types
Leave space between name and * in types. Multiple * dont need additional space between them.

struct foo **bar;

Don't put spaces between `*' and the name when declaring variables,
even if it's not a double pointer. int * foo; is ugly. Common
convention is int *foo;

The "Leave space between name and *" is confusing. Does 'name' refer to the type or variable. I hope Michael was not recommending:

	char * p;

How about saying:

Do not leave a space between a * and the following variable name, nor between multiple *, when used to declare pointers:

char *p;
struct foo **bar;

Signature · 3 lines
                  I won't rest till it's the best ...
                  Programmer, Linux Scalability
                  Paul Jackson <[email protected]> 1.925.600.0401
#17 lore raw
In reply to Jesper Juhl
Quoted 4 lines · Jesper Juhl

I don't think that's a hard rule, there's plenty of code that does "sizeof(type)" and not "sizeof (type)", and whitespace cleanup patches I've done that change "sizeof (type)" into "sizeof(type)" have generally been accepted.

Sure, the common rule is that function names and alike (including "sizeof") are not followed by a space. Statements such as "if", "while" etc. - are.

Signature · 1 line
Krzysztof Halasa
#18 lore raw

Why isn't a code formatting program used? People could write the code as they like to write it, then format it automatically in a standard way before it gets put into the kernel.

Patrick

#19 lore raw
Quoted 3 lines · Patrick Draper

Why isn't a code formatting program used? People could write the code as they like to write it, then format it automatically in a standard way before it gets put into the kernel.

There is.
scripts/Lindent

But sometimes it fails to do the job properly and some hand formatting is needed. Also much of the kernel is not new stuff but expanding or fixing old stuff.

Sam

#20 lore raw
Quoted 11 lines · Sam Ravnborg
Quoted 3 lines · Patrick Draper

Why isn't a code formatting program used? People could write the code as they like to write it, then format it automatically in a standard way before it gets put into the kernel.

There is.
scripts/Lindent

But sometimes it fails to do the job properly and some hand formatting is needed. Also much of the kernel is not new stuff but expanding or fixing old stuff.

Ehh, that's exactely why I wrote "You can do some cleanup that way, but not everything..."

Jesper

#21 lore raw
In reply to Patrick Draper
Quoted 1 line · Patrick Draper

Why isn't a code formatting program used?

There's scripts/Lindent (which is just a wrapper around indent with appropriate options.

Quoted 4 lines

People could write the code
as they like to write it, then format it automatically in a standard way before it gets put into the kernel.

You can do some cleanup that way, but not everything, and then if people continue to write in their own FunkyStyle locally but what's in the kernel has been beautified they are going to have a hell of a time
creating proper patches... It should just be cleaned up by whoever
submits it before it gets merged (and if you want to let a tool help you out some of the way, then noone's stopping you).

Signature · 3 lines
Jesper Juhl <[email protected]>
Don't top-post  http://www.catb.org/~esr/jargon/html/T/top-post.html
Plain text mails only, please      http://www.expita.com/nomime.html
#22 lore raw
In reply to Jesper Juhl
Quoted 4 lines · Jesper Juhl

On 7/11/05, Michael S. Tsirkin <[email protected]> wrote:

[snip]

Quoted 8 lines
Quoted 3 lines

3e. sizeof
space after the operator
sizeof a

I don't think that's a hard rule, there's plenty of code that does "sizeof(type)" and not "sizeof (type)", and whitespace cleanup patches I've done that change "sizeof (type)" into "sizeof(type)" have generally been accepted.

It is necessary /not/ to put space between "function name" and '(', because if it is a function-like macro, it does matter. For uniformity, do it for functions and operations like sizeof too.

Quoted 7 lines

[snip]

Quoted 3 lines

4. Indentation rules for C
Use tabs, not spaces, for indentation. Tabs should be 8 characters wide.

A tab is a tab is a tab, how it's displayed is up to the editor showing the file.

But editing a file with tab==4 and editing it later with tab==8 guarantees a mess.

[...]

Quoted 5 lines
Quoted 3 lines

6. One-line statement does not need a {} block, so dont put it into one

        if (foo)
                bar;

Not always so, if `bar' is a macro adding {} may be safer.

Such macros are /very/ dangerous. That's one reason why multi-line macros must be wrapped in "do { ... } while(0)"

Quoted 2 lines

Also
sometimes adding {} improves readability, which is important.

Or leaves an old C hand wondering what is going on...

Quoted 15 lines
Quoted 3 lines

7. Comments
Dont use C99 // comments.

s/Dont/Don't/

Quoted 7 lines

9a. Integer types
int is the default integer type.
Use unsigned type if you perform bit operations (<<,>>,&,|,~). Use unsigned long if you have to fit a pointer into integer. long long is at least 64 bit wide on all platforms. char is for ASCII characters and strings.
Use u8,u16,u32,u64 if you need an integer of a specific size.

Quoted 1 line

u8,s8,u16,s16,u32,s32,u64,s64

Plus annotations for bitwise and such. See Documentation/sparse.txt

Signature · 4 lines
Dr. Horst H. von Brand                   User #22616 counter.li.org
Departamento de Informatica                     Fono: +56 32 654431
Universidad Tecnica Federico Santa Maria              +56 32 654239
Casilla 110-V, Valparaiso, Chile                Fax:  +56 32 797513