Linux Kernel features

Source: Internet
Author: User

 

Type discovery

GCC allows you to identify types by referencing variables. This operation supports generic programming. Similar functions can be found in many modern programming languages, such as C ++, Ada, and Java & #8482. Linux uses typeof to build min, Max, and other types of operations. Listing 1 demonstrates how to use typeof to build a generic macro (see./Linux/include/Linux/kernel. h ).

Listing 1. Using typeof to build a generic macro

# Define min (x, y )({\
Typeof (x) _ min1 = (x );\
Typeof (y) _ min2 = (y );\
(Void) (& _ min1 ==& _ min2 );\
_ Min1 <_ min2? _ Min1: _ min2 ;})

//////////////////////////////////////// ///////////////////////////////

 

Extended Range

GCC support scope, which can be used in many aspects of C language. One of them is the case statement in the switch/case block. In complex condition structures, nested if statements are usually used to implement and list 2 (see. /Linux/Drivers/SCSI/SD. c) the same result, but Listing 2 is more concise. Using switch/case, you can use Jump tables for Compiler optimization.

List 2. Range Used in case statements

Static int sd_major (INT major_idx)
{
Switch (major_idx ){
Case 0:
Return scsi_disk0_major;
Case 1... 7:
Return scsi_disk1_major + major_idx-1;
Case 8... 15:
Return scsi_disk8_major + major_idx-8;
Default:
Bug ();
Return 0;/* shut up GCC */
}
}

You can also use a range for initialization, as shown below (see./Linux/ARCH/CRIS/arch-v32/kernel/SMP. C ). In this example, spinlock_t creates an array of lock_count sizes. Each element of the array is initialized to the value of spin_lock_unlocked.

/* Vector of locks used for various atomic operations */
Spinlock_t cris_atomic_locks [] = {[0... lock_count-1] = spin_lock_unlocked };

The range also supports more complex initialization. For example, the following code specifies the initial values of several sub-ranges in the array.

Int widths [] = {[0... 9] = 1, [10... 99] = 2, [100] = 3 };
//////////////////////////////////////// //////////////////////////////////////// /////////////////////

 

Zero-length Array

In the C standard, at least one array element must be defined. This requirement often complicate the code design. However, GCC supports the concept of a zero-length array, which is particularly useful for structure definition. This concept is similar to flexible array members in ISO c99, but uses different syntaxes.

The following example declares an array with no members at the end of the structure (see./Linux/Drivers/ieee1394/raw1394-private.h ). This allows elements in the structure to reference the memory that follows the structure instance. This feature is useful when you need a variable number of array members.

Struct iso_block_store {
Atomic_t refcount;
Size_t data_size;
Quadlet_t data [0];
};

 

//////////////////////////////////////// ///////////////////////////

 

Determine the call address

In many cases, you need to determine the caller of a given function. GCC provides the built-in function _ builtin_return_address for this purpose. This function is usually used for debugging, but it has many other purposes in the kernel.

As shown in the following code, __builtin_return_address receives a parameter called level. This parameter defines the call stack level for obtaining the return address. For example, if the specified level is 0, the return address of the current function is requested. If the value of level 1 is specified, it is the return address of the function requested to be called, and so on.

Void * _ builtin_return_address (unsigned int level );

In the following example (see. /Linux/kernel/softirq. c) The local_bh_disable function disables Soft Interrupt on the local processor, thus prohibiting softirqs, tasklets, and bottom halves from running on the current processor. Use _ builtin_return_address to capture the returned address for future tracking.

Void local_bh_disable (void)
{
_ Local_bh_disable (unsigned long) _ builtin_return_address (0 ));
}

 

//////////////////////////////////////// //////////////////////////////////////// ////

 

Constant Detection

During compilation, you can use a built-in function provided by GCC to determine whether a value is a constant. This information is very valuable because it can be used to construct expressions that can be optimized by constant folding. The _ builtin_constant_p function is used to detect constants.

The prototype of _ builtin_constant_p is as follows. Note: __builtin_constant_p cannot detect all constants, because GCC is not easy to prove whether some values are constants.

Int _ builtin_constant_p (exp)

Linux uses constant detection quite frequently. In the example shown in listing 3 (see./Linux/include/Linux/log2.h), use constant detection to optimize the roundup_pow_of_two macro. If the expression is a constant, use a constant expression that can be optimized. If the expression is not a constant, call another macro function to round up the value to the power of 2.

Listing 3. Using constant detection to optimize macro functions

# Define roundup_pow_of_two (n )\
(\
_ Builtin_constant_p (n )? (\
(N = 1 )? 1 :\
(1ul <(ilog2 (n)-1) + 1 ))\
):\
_ Roundup_pow_of_two (n )\
)

//////////////////////////////////////// ////////////////////////////////////

 

Function attribute

GCC provides many function-level attributes that can be used to provide more data to the compiler to help the compiler perform optimization. This section describes the attributes associated with functions. The next section describes the attributes that affect optimization.

As shown in Listing 4, attributes use other symbol definitions to specify aliases. For more information about how to use attributes, see./Linux/include/Linux/compiler-gcc3.h ).

Listing 4. Function attribute Definition

# DEFINE _ inline _ attribute _ (always_inline ))
# DEFINE _ deprecated _ attribute _ (Deprecated ))
# DEFINE _ attribute_used _ attribute _ (_ used __))
# DEFINE _ attribute_const _ attribute _ (_ const __))
# DEFINE _ must_check _ attribute _ (warn_unused_result ))

The definitions shown in Listing 4 are some function attributes available in GCC. They are also the most useful function attributes in the Linux kernel. The following explains how to use these attributes:

* Always_inline enables GCC to concurrently process specified functions, regardless of whether optimization is enabled.
* Deprecated indicates that the function has been discarded and should not be used again. If you try to use an obsolete function, you will receive a warning. You can also apply this attribute to types and variables to encourage developers to use them as little as possible.

* _ Used _ tells the compiler to use this function no matter whether or not the GCC detects the call instance of this function. This is helpful for Calling C functions from assembly code.
* _ Const _ tells the compiler that a function is stateless (that is, it uses the parameter passed to it to generate the result to be returned ).
* Warn_unused_result allows the compiler to check whether all callers check the function results. This ensures that the caller can properly check the function results and handle errors as appropriate.

The following is an example of using these attributes in the Linux kernel. Deprecated example comes from the kernel unrelated to the architecture (. /Linux/kernel/resource. c). The const example is from the IA64 kernel source code (. /Linux/ARCH/IA64/kernel/unwind. c ).

Int _ deprecated _ check_region (struct Resource
* Parent, unsigned long start, unsigned long N)

Static Enum unw_register_index _ attribute_const __
Decode_abreg (unsigned char abreg, int memory)

 

//////////////////////////////////////// ////////////////////////////////////////

Optimized Scaling

Now we will discuss some GCC features that help generate better machine codes.

Branch Prediction prompt

One of the most common optimization technologies in Linux kernel is _ builtin_expect. When developers use conditional code, they often know which branch is most likely to be executed, and which branch is rarely executed. If the compiler knows this prediction information, it can generate the best code around the branch that is most likely to be executed.

As shown in the following figure, __builtin_cmdct is used based on two macros: likely and unlikely (see./Linux/include/Linux/compiler. h ).

# Define likely (x) _ builtin_exact CT (!! (X), 1)
# Define unlikely (x) _ builtin_exact CT (!! (X), 0)

By using _ builtin_expect, the compiler can make command selection decisions that conform to the provided prediction information. This makes the executed code as close as possible to the actual situation. It can also improve the cache and command line.

For example, if a condition is labeled with "likely", the compiler can place the true part of the Code directly after the branch instruction (so that the branch instruction is not required ). Using branch commands to access the false part of the condition structure is not the optimal method, but it is unlikely to be accessed. In this way, the code is optimal for the most likely situation.

Listing 5 provides a function using the likely and unlikely macros (see./Linux/NET/CORE/datax. C ). This function predicts that the sum variable will be zero (the packet checksum is valid), and The ip_summed variable is not equal to checksum_hw.

Listing 5. Examples of likely and unlikely macros

Unsigned int _ skb_checksum_complete (struct sk_buff * SKB)
{
Unsigned int sum;

Sum = (2010) csum_fold (skb_checksum (SKB, 0, SKB-> Len, SKB-> csum ));
If (likely (! Sum )){
If (unlikely (SKB-> ip_summed = checksum_hw ))
Netdev_rx_csum_fault (SKB-> Dev );
SKB-> ip_summed = checksum_unnecessary;
}
Return sum;
}

Pre-capture

Another important way to improve performance is to cache necessary data close to the processor. Caching can significantly reduce the time required to access data. Most modern processors have three types of memory:

* Level-1 cache usually supports single-cycle access
* Second-level cache supports two-period Access
* The system memory supports longer access times.

To minimize access latency and improve performance, it is best to put the data in the nearest memory. Manual execution of this task is called pre-capturing. GCC supports manual pre-capturing of data through the built-in function _ builtin_prefetch. Use this function to cache data before data is needed. The __builtin_prefetch function receives three parameters as follows:

* Data address
* RW parameter, which indicates whether data is pre-captured for read or write operations
* Locality parameter, which specifies whether the data should be cached or cleared after the data is used.

Void _ builtin_prefetch (const void * ADDR, int RW, int locality );

Prefetch is often used in linux kernels. Usually pre-capturing is used through macro and package functions. Listing 6 is an example of a helper function that uses the built-in function package (see./Linux/include/Linux/prefetch. h ). This function provides a pre-capturing mechanism for stream operations. Using this function can usually reduce cache missing and pauses, thus improving performance.

Listing 6. Range prefetch wrapper Functions

# Ifndef arch_has_prefetch
# Define prefetch (x) _ builtin_prefetch (X)
# Endif

Static inline void prefetch_range (void * ADDR, size_t Len)
{
# Ifdef arch_has_prefetch
Char * CP;
Char * end = ADDR + Len;

For (Cp = ADDR; CP <end; CP + = prefetch_stride)
Prefetch (CP );
# Endif
}

Variable attributes

In addition to the Function Attributes discussed earlier in this article, GCC also provides attributes for variable and Type Definitions. One of the most important attributes is the aligned attribute, which is used to achieve object aligned in memory. In addition to being important to performance, some device or hardware configurations also require object alignment. The aligned attribute has a parameter that specifies the desired aligned type.

The following example is used to suspend the software (see./Linux/ARCH/i386/MM/init. C ). Define the page_size object when page alignment is required.

Char _ nosavedata swsusp_pg_dir [page_size]
_ Attribute _ (aligned (page_size )));

The example in listing 7 describes two optimizations:

* Packed attributes package elements of a structure to minimize the space they occupy. This means that if a char variable is defined, it will not occupy more than one byte (8 bits ). Bit fields are compressed into one bit without occupying more storage space.

* This source code is optimized using a _ attribute _ declaration, which defines multiple attributes using a comma-separated list.

Listing 7. Structure packaging and setting multiple attributes

Static struct swsusp_header {
Char reserved [page_size-20-sizeof (swp_entry_t)];
Swp_entry_t image;
Char orig_sig [10];
Char sig [10];
} _ Attribute _ (packed, aligned (page_size) swsusp_header;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.