Kernel function in linux

The Linux Kernel API

This documentation is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

For more details see the file COPYING in the source distribution of Linux.

Table of Contents

1. Data Types Doubly Linked Lists 2. Basic C Library Functions String Conversions String Manipulation Bit Operations 3. Basic Kernel Library Functions Bitmap Operations Command-line Parsing CRC Functions idr/ida Functions 4. Memory Management in Linux The Slab Cache User Space Memory Access More Memory Management Functions 5. Kernel IPC facilities IPC utilities 6. FIFO Buffer kfifo interface 7. relay interface support relay interface 8. Module Support Module Loading Inter Module support 9. Hardware Interfaces Interrupt Handling DMA Channels Resources Management MTRR Handling PCI Support Library PCI Hotplug Support Library 10. Firmware Interfaces DMI Interfaces EDD Interfaces 11. Security Framework security_init — initializes the security framework security_module_enable — Load given security module on boot ? security_add_hooks — Add a modules hooks to the hook lists. securityfs_create_file — create a file in the securityfs filesystem securityfs_create_dir — create a directory in the securityfs filesystem securityfs_remove — removes a file or directory from the securityfs filesystem 12. Audit Interfaces audit_log_start — obtain an audit buffer audit_log_format — format a message into the audit buffer. audit_log_end — end one audit record audit_log — Log an audit record audit_log_secctx — Converts and logs SELinux context audit_alloc — allocate an audit context block for a task __audit_free — free a per-task audit context __audit_syscall_entry — fill in an audit record at syscall entry __audit_syscall_exit — deallocate audit context after a system call __audit_reusename — fill out filename with info from existing entry __audit_getname — add a name to the list __audit_inode — store the inode and device from a lookup auditsc_get_stamp — get local copies of audit_context values audit_set_loginuid — set current task’s audit_context loginuid __audit_mq_open — record audit data for a POSIX MQ open __audit_mq_sendrecv — record audit data for a POSIX MQ timed send/receive __audit_mq_notify — record audit data for a POSIX MQ notify __audit_mq_getsetattr — record audit data for a POSIX MQ get/set attribute __audit_ipc_obj — record audit data for ipc object __audit_ipc_set_perm — record audit data for new ipc permissions __audit_socketcall — record audit data for sys_socketcall __audit_fd_pair — record audit data for pipe and socketpair __audit_sockaddr — record audit data for sys_bind, sys_connect, sys_sendto audit_signal_info — record signal info for shutting down audit subsystem __audit_log_bprm_fcaps — store information about a loading bprm and relevant fcaps __audit_log_capset — store information about the arguments to the capset syscall audit_core_dumps — record information about processes that end abnormally audit_rule_change — apply all rules to the specified message type audit_list_rules_send — list the audit rules parent_len — find the length of the parent portion of a pathname audit_compare_dname_path — compare given dentry name with last component in given path. Return of 0 indicates a match. 13. Accounting Framework sys_acct — enable/disable process accounting acct_collect — collect accounting information into pacct_struct acct_process — 14. Block Devices blk_delay_queue — restart queueing after defined interval blk_start_queue_async — asynchronously restart a previously stopped queue blk_start_queue — restart a previously stopped queue blk_stop_queue — stop a queue blk_sync_queue — cancel any pending callbacks on a queue __blk_run_queue_uncond — run a queue whether or not it has been stopped __blk_run_queue — run a single device queue blk_run_queue_async — run a single device queue in workqueue context blk_run_queue — run a single device queue blk_queue_bypass_start — enter queue bypass mode blk_queue_bypass_end — leave queue bypass mode blk_cleanup_queue — shutdown a request queue blk_init_queue — prepare a request queue for use with a block device blk_requeue_request — put a request back on queue part_round_stats — Round off the performance stats on a struct disk_stats. generic_make_request — hand a buffer to its device driver for I/O submit_bio — submit a bio to the block device layer for I/O blk_insert_cloned_request — Helper for stacking drivers to submit a request blk_rq_err_bytes — determine number of bytes till the next failure boundary blk_peek_request — peek at the top of a request queue blk_start_request — start request processing on the driver blk_fetch_request — fetch a request from a request queue blk_update_request — Special helper function for request stacking drivers blk_unprep_request — unprepare a request blk_end_request — Helper function for drivers to complete the request. blk_end_request_all — Helper function for drives to finish the request. blk_end_request_cur — Helper function to finish the current request chunk. blk_end_request_err — Finish a request till the next failure boundary. __blk_end_request — Helper function for drivers to complete the request. __blk_end_request_all — Helper function for drives to finish the request. __blk_end_request_cur — Helper function to finish the current request chunk. __blk_end_request_err — Finish a request till the next failure boundary. rq_flush_dcache_pages — Helper function to flush all pages in a request blk_lld_busy — Check if underlying low-level drivers of a device are busy blk_rq_unprep_clone — Helper function to free all bios in a cloned request blk_rq_prep_clone — Helper function to setup clone request blk_start_plug — initialize blk_plug and track it inside the task_struct blk_pm_runtime_init — Block layer runtime PM initialization routine blk_pre_runtime_suspend — Pre runtime suspend check blk_post_runtime_suspend — Post runtime suspend processing blk_pre_runtime_resume — Pre runtime resume processing blk_post_runtime_resume — Post runtime resume processing blk_set_runtime_active — Force runtime status of the queue to be active __blk_drain_queue — drain requests from request_queue __get_request — get a free request get_request — get a free request blk_attempt_plug_merge — try to merge with current ‘s plugged list blk_cloned_rq_check_limits — Helper function to check a cloned request for new the queue limits blk_end_bidi_request — Complete a bidi request __blk_end_bidi_request — Complete a bidi request with queue lock held blk_rq_map_user_iov — map user data to a request, for passthrough requests blk_rq_unmap_user — unmap a request with user data blk_rq_map_kern — map kernel data to a request, for passthrough requests blk_release_queue — release a struct request_queue when it is no longer needed blk_queue_prep_rq — set a prepare_request function for queue blk_queue_unprep_rq — set an unprepare_request function for queue blk_set_default_limits — reset limits to default values blk_set_stacking_limits — set default limits for stacking devices blk_queue_make_request — define an alternate make_request function for a device blk_queue_bounce_limit — set bounce buffer limit for queue blk_queue_max_hw_sectors — set max sectors for a request for this queue blk_queue_chunk_sectors — set size of the chunk for this queue blk_queue_max_discard_sectors — set max sectors for a single discard blk_queue_max_write_same_sectors — set max sectors for a single write same blk_queue_max_write_zeroes_sectors — set max sectors for a single write zeroes blk_queue_max_segments — set max hw segments for a request for this queue blk_queue_max_discard_segments — set max segments for discard requests blk_queue_max_segment_size — set max segment size for blk_rq_map_sg blk_queue_logical_block_size — set logical block size for the queue blk_queue_physical_block_size — set physical block size for the queue blk_queue_alignment_offset — set physical block alignment offset blk_limits_io_min — set minimum request size for a device blk_queue_io_min — set minimum request size for the queue blk_limits_io_opt — set optimal request size for a device blk_queue_io_opt — set optimal request size for the queue blk_queue_stack_limits — inherit underlying queue limits for stacked drivers blk_stack_limits — adjust queue_limits for stacked devices bdev_stack_limits — adjust queue limits for stacked drivers disk_stack_limits — adjust queue limits for stacked drivers blk_queue_dma_pad — set pad mask blk_queue_update_dma_pad — update pad mask blk_queue_dma_drain — Set up a drain buffer for excess dma. blk_queue_segment_boundary — set boundary rules for segment merging blk_queue_virt_boundary — set boundary rules for bio merging blk_queue_dma_alignment — set dma length and memory alignment blk_queue_update_dma_alignment — update dma length and memory alignment blk_set_queue_depth — tell the block layer about the device queue depth blk_queue_write_cache — configure queue’s write cache blk_execute_rq_nowait — insert a request into queue for execution blk_execute_rq — insert a request into queue for execution blkdev_issue_flush — queue a flush blkdev_issue_discard — queue a discard blkdev_issue_write_same — queue a write same operation __blkdev_issue_zeroout — generate number of zero filed write bios blkdev_issue_zeroout — zero-fill a block range blk_queue_find_tag — find a request by its tag and queue blk_free_tags — release a given set of tag maintenance info blk_queue_free_tags — release tag maintenance info blk_init_tags — initialize the tag info for an external tag map blk_queue_init_tags — initialize the queue tag info blk_queue_resize_tags — change the queueing depth blk_queue_end_tag — end tag operations for a request blk_queue_start_tag — find a free tag and assign it blk_queue_invalidate_tags — invalidate all pending tags __blk_queue_free_tags — release tag maintenance info blk_rq_count_integrity_sg — Count number of integrity scatterlist elements blk_rq_map_integrity_sg — Map integrity metadata into a scatterlist blk_integrity_compare — Compare integrity profile of two disks blk_integrity_register — Register a gendisk as being integrity-capable blk_integrity_unregister — Unregister block integrity profile blk_trace_ioctl — handle the ioctls associated with tracing blk_trace_shutdown — stop and cleanup trace structures blk_add_trace_rq — Add a trace for a request oriented action blk_add_trace_bio — Add a trace for a bio oriented action blk_add_trace_bio_remap — Add a trace for a bio-remap operation blk_add_trace_rq_remap — Add a trace for a request-remap operation blk_mangle_minor — scatter minor numbers apart blk_alloc_devt — allocate a dev_t for a partition blk_free_devt — free a dev_t disk_replace_part_tbl — replace disk->part_tbl in RCU-safe way disk_expand_part_tbl — expand disk->part_tbl disk_block_events — block and flush disk event checking disk_unblock_events — unblock disk event checking disk_flush_events — schedule immediate event checking and flushing disk_clear_events — synchronously check, clear and return pending events disk_get_part — get partition disk_part_iter_init — initialize partition iterator disk_part_iter_next — proceed iterator to the next partition and return it disk_part_iter_exit — finish up partition iteration disk_map_sector_rcu — map sector to partition register_blkdev — register a new block device device_add_disk — add partitioning information to kernel list get_gendisk — get partitioning information for a given device bdget_disk — do bdget by gendisk and partition number 15. Char devices register_chrdev_region — register a range of device numbers alloc_chrdev_region — register a range of char device numbers __register_chrdev — create and register a cdev occupying a range of minors unregister_chrdev_region — unregister a range of device numbers __unregister_chrdev — unregister and destroy a cdev cdev_add — add a char device to the system cdev_del — remove a cdev from the system cdev_alloc — allocate a cdev structure cdev_init — initialize a cdev structure 16. Miscellaneous Devices misc_register — register a miscellaneous device misc_deregister — unregister a miscellaneous device 17. Clock Framework struct clk_notifier — associate a clk with a notifier struct clk_notifier_data — rate data to pass to the notifier callback clk_notifier_register — change notifier callback clk_notifier_unregister — change notifier callback clk_get_accuracy — obtain the clock accuracy in ppb (parts per billion) for a clock source. clk_set_phase — adjust the phase shift of a clock signal clk_get_phase — return the phase shift of a clock signal clk_is_match — check if two clk’s point to the same hardware clock clk_prepare — prepare a clock source clk_unprepare — undo preparation of a clock source clk_get — lookup and obtain a reference to a clock producer. devm_clk_get — lookup and obtain a managed reference to a clock producer. devm_get_clk_from_child — lookup and obtain a managed reference to a clock producer from child node. clk_enable — inform the system when the clock source should be running. clk_disable — inform the system when the clock source is no longer required. clk_get_rate — obtain the current clock rate (in Hz) for a clock source. This is only valid once the clock source has been enabled. clk_put — «free» the clock source devm_clk_put — «free» a managed clock source clk_round_rate — adjust a rate to the exact rate a clock can provide clk_set_rate — set the clock rate for a clock source clk_has_parent — check if a clock is a possible parent for another clk_set_rate_range — set a rate range for a clock source clk_set_min_rate — set a minimum clock rate for a clock source clk_set_max_rate — set a maximum clock rate for a clock source clk_set_parent — set the parent clock source for this clock clk_get_parent — get the parent clock source for this clock clk_get_sys — get a clock based upon the device name

Читайте также:  Math input panel windows 10 что это

Источник

Linux kernel coding style¶

This is a short document describing the preferred coding style for the linux kernel. Coding style is very personal, and I won’t force my views on anybody, but this is what goes for anything that I have to be able to maintain, and I’d prefer it for most other things too. Please at least consider the points made here.

First off, I’d suggest printing out a copy of the GNU coding standards, and NOT read it. Burn them, it’s a great symbolic gesture.

Anyway, here goes:

1) Indentation¶

Tabs are 8 characters, and thus indentations are also 8 characters. There are heretic movements that try to make indentations 4 (or even 2!) characters deep, and that is akin to trying to define the value of PI to be 3.

Rationale: The whole idea behind indentation is to clearly define where a block of control starts and ends. Especially when you’ve been looking at your screen for 20 straight hours, you’ll find it a lot easier to see how the indentation works if you have large indentations.

Now, some people will claim that having 8-character indentations makes the code move too far to the right, and makes it hard to read on a 80-character terminal screen. The answer to that is that if you need more than 3 levels of indentation, you’re screwed anyway, and should fix your program.

In short, 8-char indents make things easier to read, and have the added benefit of warning you when you’re nesting your functions too deep. Heed that warning.

The preferred way to ease multiple indentation levels in a switch statement is to align the switch and its subordinate case labels in the same column instead of double-indenting the case labels. E.g.:

Don’t put multiple statements on a single line unless you have something to hide:

Don’t put multiple assignments on a single line either. Kernel coding style is super simple. Avoid tricky expressions.

Outside of comments, documentation and except in Kconfig, spaces are never used for indentation, and the above example is deliberately broken.

Get a decent editor and don’t leave whitespace at the end of lines.

2) Breaking long lines and strings¶

Coding style is all about readability and maintainability using commonly available tools.

The limit on the length of lines is 80 columns and this is a strongly preferred limit.

Statements longer than 80 columns will be broken into sensible chunks, unless exceeding 80 columns significantly increases readability and does not hide information. Descendants are always substantially shorter than the parent and are placed substantially to the right. The same applies to function headers with a long argument list. However, never break user-visible strings such as printk messages, because that breaks the ability to grep for them.

3) Placing Braces and Spaces¶

The other issue that always comes up in C styling is the placement of braces. Unlike the indent size, there are few technical reasons to choose one placement strategy over the other, but the preferred way, as shown to us by the prophets Kernighan and Ritchie, is to put the opening brace last on the line, and put the closing brace first, thusly:

This applies to all non-function statement blocks (if, switch, for, while, do). E.g.:

However, there is one special case, namely functions: they have the opening brace at the beginning of the next line, thus:

Heretic people all over the world have claimed that this inconsistency is . well . inconsistent, but all right-thinking people know that (a) K&R are right and (b) K&R are right. Besides, functions are special anyway (you can’t nest them in C).

Note that the closing brace is empty on a line of its own, except in the cases where it is followed by a continuation of the same statement, ie a while in a do-statement or an else in an if-statement, like this:

Also, note that this brace-placement also minimizes the number of empty (or almost empty) lines, without any loss of readability. Thus, as the supply of new-lines on your screen is not a renewable resource (think 25-line terminal screens here), you have more empty lines to put comments on.

Do not unnecessarily use braces where a single statement will do.

This does not apply if only one branch of a conditional statement is a single statement; in the latter case use braces in both branches:

3.1) Spaces¶

Linux kernel style for use of spaces depends (mostly) on function-versus-keyword usage. Use a space after (most) keywords. The notable exceptions are sizeof, typeof, alignof, and __attribute__, which look somewhat like functions (and are usually used with parentheses in Linux, although they are not required in the language, as in: sizeof info after struct fileinfo info; is declared).

So use a space after these keywords:

but not with sizeof, typeof, alignof, or __attribute__. E.g.,

Do not add spaces around (inside) parenthesized expressions. This example is bad:

When declaring pointer data or a function that returns a pointer type, the preferred use of * is adjacent to the data name or function name and not adjacent to the type name. Examples:

Use one space around (on each side of) most binary and ternary operators, such as any of these:

but no space after unary operators:

no space before the postfix increment & decrement unary operators:

no space after the prefix increment & decrement unary operators:

and no space around the . and -> structure member operators.

Do not leave trailing whitespace at the ends of lines. Some editors with smart indentation will insert whitespace at the beginning of new lines as appropriate, so you can start typing the next line of code right away. However, some such editors do not remove the whitespace if you end up not putting a line of code there, such as if you leave a blank line. As a result, you end up with lines containing trailing whitespace.

Git will warn you about patches that introduce trailing whitespace, and can optionally strip the trailing whitespace for you; however, if applying a series of patches, this may make later patches in the series fail by changing their context lines.

4) Naming¶

C is a Spartan language, and so should your naming be. Unlike Modula-2 and Pascal programmers, C programmers do not use cute names like ThisVariableIsATemporaryCounter. A C programmer would call that variable tmp , which is much easier to write, and not the least more difficult to understand.

HOWEVER, while mixed-case names are frowned upon, descriptive names for global variables are a must. To call a global function foo is a shooting offense.

GLOBAL variables (to be used only if you really need them) need to have descriptive names, as do global functions. If you have a function that counts the number of active users, you should call that count_active_users() or similar, you should not call it cntusr() .

Encoding the type of a function into the name (so-called Hungarian notation) is brain damaged — the compiler knows the types anyway and can check those, and it only confuses the programmer. No wonder MicroSoft makes buggy programs.

LOCAL variable names should be short, and to the point. If you have some random integer loop counter, it should probably be called i . Calling it loop_counter is non-productive, if there is no chance of it being mis-understood. Similarly, tmp can be just about any type of variable that is used to hold a temporary value.

If you are afraid to mix up your local variable names, you have another problem, which is called the function-growth-hormone-imbalance syndrome. See chapter 6 (Functions).

5) Typedefs¶

Please don’t use things like vps_t . It’s a mistake to use typedef for structures and pointers. When you see a

in the source, what does it mean? In contrast, if it says

you can actually tell what a is.

Lots of people think that typedefs help readability . Not so. They are useful only for:

totally opaque objects (where the typedef is actively used to hide what the object is).

Example: pte_t etc. opaque objects that you can only access using the proper accessor functions.

Opaqueness and accessor functions are not good in themselves. The reason we have them for things like pte_t etc. is that there really is absolutely zero portably accessible information there.

Читайте также:  Драйвера для asus n750j windows 10

Clear integer types, where the abstraction helps avoid confusion whether it is int or long .

u8/u16/u32 are perfectly fine typedefs, although they fit into category (d) better than here.

Again — there needs to be a reason for this. If something is unsigned long , then there’s no reason to do

typedef unsigned long myflags_t;

but if there is a clear reason for why it under certain circumstances might be an unsigned int and under other configurations might be unsigned long , then by all means go ahead and use a typedef.

when you use sparse to literally create a new type for type-checking.

New types which are identical to standard C99 types, in certain exceptional circumstances.

Although it would only take a short amount of time for the eyes and brain to become accustomed to the standard types like uint32_t , some people object to their use anyway.

Therefore, the Linux-specific u8/u16/u32/u64 types and their signed equivalents which are identical to standard types are permitted – although they are not mandatory in new code of your own.

When editing existing code which already uses one or the other set of types, you should conform to the existing choices in that code.

Types safe for use in userspace.

In certain structures which are visible to userspace, we cannot require C99 types and cannot use the u32 form above. Thus, we use __u32 and similar types in all structures which are shared with userspace.

Maybe there are other cases too, but the rule should basically be to NEVER EVER use a typedef unless you can clearly match one of those rules.

In general, a pointer, or a struct that has elements that can reasonably be directly accessed should never be a typedef.

6) Functions¶

Functions should be short and sweet, and do just one thing. They should fit on one or two screenfuls of text (the ISO/ANSI screen size is 80×24, as we all know), and do one thing and do that well.

The maximum length of a function is inversely proportional to the complexity and indentation level of that function. So, if you have a conceptually simple function that is just one long (but simple) case-statement, where you have to do lots of small things for a lot of different cases, it’s OK to have a longer function.

However, if you have a complex function, and you suspect that a less-than-gifted first-year high-school student might not even understand what the function is all about, you should adhere to the maximum limits all the more closely. Use helper functions with descriptive names (you can ask the compiler to in-line them if you think it’s performance-critical, and it will probably do a better job of it than you would have done).

Another measure of the function is the number of local variables. They shouldn’t exceed 5-10, or you’re doing something wrong. Re-think the function, and split it into smaller pieces. A human brain can generally easily keep track of about 7 different things, anything more and it gets confused. You know you’re brilliant, but maybe you’d like to understand what you did 2 weeks from now.

In source files, separate functions with one blank line. If the function is exported, the EXPORT macro for it should follow immediately after the closing function brace line. E.g.:

In function prototypes, include parameter names with their data types. Although this is not required by the C language, it is preferred in Linux because it is a simple way to add valuable information for the reader.

7) Centralized exiting of functions¶

Albeit deprecated by some people, the equivalent of the goto statement is used frequently by compilers in form of the unconditional jump instruction.

The goto statement comes in handy when a function exits from multiple locations and some common work such as cleanup has to be done. If there is no cleanup needed then just return directly.

Choose label names which say what the goto does or why the goto exists. An example of a good name could be out_free_buffer: if the goto frees buffer . Avoid using GW-BASIC names like err1: and err2: , as you would have to renumber them if you ever add or remove exit paths, and they make correctness difficult to verify anyway.

The rationale for using gotos is:

  • unconditional statements are easier to understand and follow
  • nesting is reduced
  • errors by not updating individual exit points when making modifications are prevented
  • saves the compiler work to optimize redundant code away 😉

A common type of bug to be aware of is one err bugs which look like this:

The bug in this code is that on some exit paths foo is NULL. Normally the fix for this is to split it up into two error labels err_free_bar: and err_free_foo: :

Ideally you should simulate errors to test all exit paths.

8) Commenting¶

Comments are good, but there is also a danger of over-commenting. NEVER try to explain HOW your code works in a comment: it’s much better to write the code so that the working is obvious, and it’s a waste of time to explain badly written code.

Generally, you want your comments to tell WHAT your code does, not HOW. Also, try to avoid putting comments inside a function body: if the function is so complex that you need to separately comment parts of it, you should probably go back to chapter 6 for a while. You can make small comments to note or warn about something particularly clever (or ugly), but try to avoid excess. Instead, put the comments at the head of the function, telling people what it does, and possibly WHY it does it.

When commenting the kernel API functions, please use the kernel-doc format. See the files at Documentation/doc-guide/ and scripts/kernel-doc for details.

The preferred style for long (multi-line) comments is:

For files in net/ and drivers/net/ the preferred style for long (multi-line) comments is a little different.

It’s also important to comment data, whether they are basic types or derived types. To this end, use just one data declaration per line (no commas for multiple data declarations). This leaves you room for a small comment on each item, explaining its use.

9) You’ve made a mess of itВ¶

That’s OK, we all do. You’ve probably been told by your long-time Unix user helper that GNU emacs automatically formats the C sources for you, and you’ve noticed that yes, it does do that, but the defaults it uses are less than desirable (in fact, they are worse than random typing — an infinite number of monkeys typing into GNU emacs would never make a good program).

So, you can either get rid of GNU emacs, or change it to use saner values. To do the latter, you can stick the following in your .emacs file:

This will make emacs go better with the kernel coding style for C files below

But even if you fail in getting emacs to do sane formatting, not everything is lost: use indent .

Now, again, GNU indent has the same brain-dead settings that GNU emacs has, which is why you need to give it a few command line options. However, that’s not too bad, because even the makers of GNU indent recognize the authority of K&R (the GNU people aren’t evil, they are just severely misguided in this matter), so you just give indent the options -kr -i8 (stands for K&R, 8 character indents ), or use scripts/Lindent , which indents in the latest style.

indent has a lot of options, and especially when it comes to comment re-formatting you may want to take a look at the man page. But remember: indent is not a fix for bad programming.

10) Kconfig configuration files¶

For all of the Kconfig* configuration files throughout the source tree, the indentation is somewhat different. Lines under a config definition are indented with one tab, while help text is indented an additional two spaces. Example:

Seriously dangerous features (such as write support for certain filesystems) should advertise this prominently in their prompt string:

For full documentation on the configuration files, see the file Documentation/kbuild/kconfig-language.txt.

11) Data structures¶

Data structures that have visibility outside the single-threaded environment they are created and destroyed in should always have reference counts. In the kernel, garbage collection doesn’t exist (and outside the kernel garbage collection is slow and inefficient), which means that you absolutely have to reference count all your uses.

Reference counting means that you can avoid locking, and allows multiple users to have access to the data structure in parallel — and not having to worry about the structure suddenly going away from under them just because they slept or did something else for a while.

Note that locking is not a replacement for reference counting. Locking is used to keep data structures coherent, while reference counting is a memory management technique. Usually both are needed, and they are not to be confused with each other.

Many data structures can indeed have two levels of reference counting, when there are users of different classes . The subclass count counts the number of subclass users, and decrements the global count just once when the subclass count goes to zero.

Examples of this kind of multi-level-reference-counting can be found in memory management ( struct mm_struct : mm_users and mm_count), and in filesystem code ( struct super_block : s_count and s_active).

Remember: if another thread can find your data structure, and you don’t have a reference count on it, you almost certainly have a bug.

12) Macros, Enums and RTL¶

Names of macros defining constants and labels in enums are capitalized.

Enums are preferred when defining several related constants.

CAPITALIZED macro names are appreciated but macros resembling functions may be named in lower case.

Generally, inline functions are preferable to macros resembling functions.

Macros with multiple statements should be enclosed in a do — while block:

Things to avoid when using macros:

  1. macros that affect control flow:

is a very bad idea. It looks like a function call but exits the calling function; don’t break the internal parsers of those who will read the code.

  1. macros that depend on having a local variable with a magic name:

might look like a good thing, but it’s confusing as hell when one reads the code and it’s prone to breakage from seemingly innocent changes.

Читайте также:  Принудительное обновление windows 10 до последней версии

3) macros with arguments that are used as l-values: FOO(x) = y; will bite you if somebody e.g. turns FOO into an inline function.

4) forgetting about precedence: macros defining constants using expressions must enclose the expression in parentheses. Beware of similar issues with macros using parameters.

5) namespace collisions when defining local variables in macros resembling functions:

ret is a common name for a local variable — __foo_ret is less likely to collide with an existing variable.

The cpp manual deals with macros exhaustively. The gcc internals manual also covers RTL which is used frequently with assembly language in the kernel.

13) Printing kernel messages¶

Kernel developers like to be seen as literate. Do mind the spelling of kernel messages to make a good impression. Do not use crippled words like dont ; use do not or don’t instead. Make the messages concise, clear, and unambiguous.

Kernel messages do not have to be terminated with a period.

Printing numbers in parentheses (%d) adds no value and should be avoided.

There are a number of driver model diagnostic macros in

  • which you should use to make sure messages are matched to the right device and driver, and are tagged with the right level: dev_err(), dev_warn(), dev_info(), and so forth. For messages that aren’t associated with a particular device,
  • defines pr_notice(), pr_info(), pr_warn(), pr_err(), etc.

    Coming up with good debugging messages can be quite a challenge; and once you have them, they can be a huge help for remote troubleshooting. However debug message printing is handled differently than printing other non-debug messages. While the other pr_XXX() functions print unconditionally, pr_debug() does not; it is compiled out by default, unless either DEBUG is defined or CONFIG_DYNAMIC_DEBUG is set. That is true for dev_dbg() also, and a related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to the ones already enabled by DEBUG.

    Many subsystems have Kconfig debug options to turn on -DDEBUG in the corresponding Makefile; in other cases specific files #define DEBUG. And when a debug message should be unconditionally printed, such as if it is already inside a debug-related #ifdef section, printk(KERN_DEBUG . ) can be used.

    14) Allocating memory¶

    The kernel provides the following general purpose memory allocators: kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and vzalloc(). Please refer to the API documentation for further information about them.

    The preferred form for passing a size of a struct is the following:

    The alternative form where struct name is spelled out hurts readability and introduces an opportunity for a bug when the pointer variable type is changed but the corresponding sizeof that is passed to a memory allocator is not.

    Casting the return value which is a void pointer is redundant. The conversion from void pointer to any other pointer type is guaranteed by the C programming language.

    The preferred form for allocating an array is the following:

    The preferred form for allocating a zeroed array is the following:

    Both forms check for overflow on the allocation size n * sizeof(. ), and return NULL if that occurred.

    15) The inline disease¶

    There appears to be a common misperception that gcc has a magic “make me faster” speedup option called inline . While the use of inlines can be appropriate (for example as a means of replacing macros, see Chapter 12), it very often is not. Abundant use of the inline keyword leads to a much bigger kernel, which in turn slows the system as a whole down, due to a bigger icache footprint for the CPU and simply because there is less memory available for the pagecache. Just think about it; a pagecache miss causes a disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles that can go into these 5 milliseconds.

    A reasonable rule of thumb is to not put inline at functions that have more than 3 lines of code in them. An exception to this rule are the cases where a parameter is known to be a compiletime constant, and as a result of this constantness you know the compiler will be able to optimize most of your function away at compile time. For a good example of this later case, see the kmalloc() inline function.

    Often people argue that adding inline to functions that are static and used only once is always a win since there is no space tradeoff. While this is technically correct, gcc is capable of inlining these automatically without help, and the maintenance issue of removing the inline when a second user appears outweighs the potential value of the hint that tells gcc to do something it would have done anyway.

    16) Function return values and names¶

    Functions can return values of many different kinds, and one of the most common is a value indicating whether the function succeeded or failed. Such a value can be represented as an error-code integer (-Exxx = failure, 0 = success) or a succeeded boolean (0 = failure, non-zero = success).

    Mixing up these two sorts of representations is a fertile source of difficult-to-find bugs. If the C language included a strong distinction between integers and booleans then the compiler would find these mistakes for us. but it doesn’t. To help prevent such bugs, always follow this convention:

    For example, add work is a command, and the add_work() function returns 0 for success or -EBUSY for failure. In the same way, PCI device present is a predicate, and the pci_dev_present() function returns 1 if it succeeds in finding a matching device or 0 if it doesn’t.

    All EXPORTed functions must respect this convention, and so should all public functions. Private (static) functions need not, but it is recommended that they do.

    Functions whose return value is the actual result of a computation, rather than an indication of whether the computation succeeded, are not subject to this rule. Generally they indicate failure by returning some out-of-range result. Typical examples would be functions that return pointers; they use NULL or the ERR_PTR mechanism to report failure.

    17) Don’t re-invent the kernel macrosВ¶

    The header file include/linux/kernel.h contains a number of macros that you should use, rather than explicitly coding some variant of them yourself. For example, if you need to calculate the length of an array, take advantage of the macro

    Similarly, if you need to calculate the size of some structure member, use

    There are also min() and max() macros that do strict type checking if you need them. Feel free to peruse that header file to see what else is already defined that you shouldn’t reproduce in your code.

    18) Editor modelines and other cruft¶

    Some editors can interpret configuration information embedded in source files, indicated with special markers. For example, emacs interprets lines marked like this:

    Vim interprets markers that look like this:

    Do not include any of these in source files. People have their own personal editor configurations, and your source files should not override them. This includes markers for indentation and mode configuration. People may use their own custom mode, or may have some other magic method for making indentation work correctly.

    19) Inline assembly¶

    In architecture-specific code, you may need to use inline assembly to interface with CPU or platform functionality. Don’t hesitate to do so when necessary. However, don’t use inline assembly gratuitously when C can do the job. You can and should poke hardware from C when possible.

    Consider writing simple helper functions that wrap common bits of inline assembly, rather than repeatedly writing them with slight variations. Remember that inline assembly can use C parameters.

    Large, non-trivial assembly functions should go in .S files, with corresponding C prototypes defined in C header files. The C prototypes for assembly functions should use asmlinkage .

    You may need to mark your asm statement as volatile, to prevent GCC from removing it if GCC doesn’t notice any side effects. You don’t always need to do so, though, and doing so unnecessarily can limit optimization.

    When writing a single inline assembly statement containing multiple instructions, put each instruction on a separate line in a separate quoted string, and end each string except the last with nt to properly indent the next instruction in the assembly output:

    20) Conditional Compilation¶

    Wherever possible, don’t use preprocessor conditionals (#if, #ifdef) in .c files; doing so makes code harder to read and logic harder to follow. Instead, use such conditionals in a header file defining functions for use in those .c files, providing no-op stub versions in the #else case, and then call those functions unconditionally from .c files. The compiler will avoid generating any code for the stub calls, producing identical results, but the logic will remain easy to follow.

    Prefer to compile out entire functions, rather than portions of functions or portions of expressions. Rather than putting an ifdef in an expression, factor out part or all of the expression into a separate helper function and apply the conditional to that function.

    If you have a function or variable which may potentially go unused in a particular configuration, and the compiler would warn about its definition going unused, mark the definition as __maybe_unused rather than wrapping it in a preprocessor conditional. (However, if a function or variable always goes unused, delete it.)

    Within code, where possible, use the IS_ENABLED macro to convert a Kconfig symbol into a C boolean expression, and use it in a normal C conditional:

    The compiler will constant-fold the conditional away, and include or exclude the block of code just as with an #ifdef, so this will not add any runtime overhead. However, this approach still allows the C compiler to see the code inside the block, and check it for correctness (syntax, types, symbol references, etc). Thus, you still have to use an #ifdef if the code inside the block references symbols that will not exist if the condition is not met.

    At the end of any non-trivial #if or #ifdef block (more than a few lines), place a comment after the #endif on the same line, noting the conditional expression used. For instance:

    Appendix I) References¶

    The C Programming Language, Second Edition by Brian W. Kernighan and Dennis M. Ritchie. Prentice Hall, Inc., 1988. ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).

    The Practice of Programming by Brian W. Kernighan and Rob Pike. Addison-Wesley, Inc., 1999. ISBN 0-201-61586-X.

    GNU manuals — where in compliance with K&R and this text — for cpp, gcc, gcc internals and indent, all available from http://www.gnu.org/manual/

    WG14 is the international standardization working group for the programming language C, URL: http://www.open-std.org/JTC1/SC22/WG14/

    © Copyright 2016, The kernel development community.

    Источник

  • Оцените статью