顯示具有 Linux C 標籤的文章。 顯示所有文章
顯示具有 Linux C 標籤的文章。 顯示所有文章

2017年12月12日 星期二

File I/O

1. scatter/gather I/O (vectored)
相較於linear I/O,分散/聚集 I/O有幾項優點:
(1)較自然的撰碼模式 (2)效率 (3)效能 (4)不可分割
Linux核心內部所有I/O均採用向量的方式
readv, writev, preadv, pwritev - read or write data into multiple buffers
ssize_t readv(int fd, const struct iovec *iov, int iovcnt);
ssize_t writev(int fd, const struct iovec *iov, int iovcnt);

每個iovec結構可用來描述一個獨立的緩衝區,稱為區段segmen(向量vector)
           struct iovec {
               void  *iov_base;   /* Starting address */
               size_t iov_len;      /* Number of bytes to transfer */
           };

iovcnt必須≥ 0以及≤ IOV_MAX(1024),
如果iovcnt個iov_len值的總和大於SSIZE_MAX,資料將不會被傳送
grep SSIZE_MAX -r /usr/include -n
SSIZE_MAX = 9223372036854775807

2. event poll (Epoll)
poll()與select()的每次調用,需提供一份所要檢視之檔案描述器的完整清單。然後核心必須處理清單中每個檔案描述器。當這份清單變大時-它可能包含成百上千的檔案描述氣-每次調用所要處理的清單會變成擴充性的瓶頸。
epoll避開這個問題的方法,就是讓「事件檢視器的登記」與「實際的事件檢視工作」脫勾。
(1) epoll_create1系統呼叫用於初始設定epoll的作業環境
epoll_create1 - open an epoll file descriptor
int epoll_create1(int flags);

傳回一個與實例相對應的檔案描述器,與真實的檔案沒有關係;它只是一個可供隨後呼叫使用epoll措施的操作代號,flag目前只有一個有效旗標: EPOLL_CLOEXEC。它可用於啟用close-on-exec行為。

(2) epoll_ctl系統呼叫用於把所要檢視的檔案描述器加入作業環境,或是從作業環境中移除檔案描述器
epoll_ctl - control interface for an epoll descriptor
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);

          typedef union epoll_data {
               void       *ptr;
               int           fd;
               uint32_t   u32;
               uint64_t   u64;
           } epoll_data_t;

           struct epoll_event {
               uint32_t      events;      /* Epoll events */
               epoll_data_t data;        /* User data variable */
           };

參數op用於指定如何操作與fd相對應的檔案
EPOLL_CTL_ADD: 把特定檔案(fd)上的一個檢視器加入epoll實例(epfd)
EPOLL_CTL_DEL: 從epoll實例(epfd)移除特定檔案(fd)上的一個事件檢視器

epoll ET/LT
event參數用於進一步描述操作的行為
EPOLLIN: 檔案可供讀取而且不會遭到阻擋
EPOLLET: 為檔案的檢視器啟用邊緣觸發行為(預設是準位觸發)
poll() / select(): Level-triggered
epoll(): Level-triggered (default) and Edge-triggered
邊緣觸發通常需要運用非阻擋I/O並且仔細檢查EAGAIN

(3) epoll_wait系統呼叫則實際進行事件的等待。
epoll_wait, epoll_pwait - wait for an I/O event on an epoll file descriptor
int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout);

3. memory-mapped I/O (mmap)
mmap, munmap - map or unmap files or devices into memory
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
prot:
PROT_READ  Pages may be read.
PROT_WRITE Pages may be written.
PROT_EXEC  Pages may be executed.

flags: 
MAP_SHARED
Share this mapping. Updates to the mapping are visible to other processes that map this file, and are carried through to the underlying file. The file may not actually be updated until msync(2) or munmap() is called.

MAP_PRIVATE
Create a private copy-on-write mapping. Updates to the mapping are not visible to  other processes mapping the same file, and are not carried through to the underlying file. It is unspecified whether changes made to the file after the mmap() call are visible in the mapped region.

調整一個映射的大小
mremap - remap a virtual memory address
void *mremap(void *old_address, size_t old_size,
                    size_t new_size, int flags, ... /* void *new_address */);
mremap() uses the Linux page table scheme. mremap() changes the mapping between virtual addresses and memory pages. This can be used to implement a very efficient realloc(3).

變更一個映射的保護旗標
mprotect - set protection on a region of memory
int mprotect(void *addr, size_t len, int prot);
prot:   
PROT_NONE  The memory cannot be accessed at all.
PROT_READ  The memory can be read.
PROT_WRITE The memory can be modified.
PROT_EXEC  The memory can be executed.

檔案與映射的同步
msync - synchronize a file with a memory map
int msync(void *addr, size_t length, int flags);
flag:
MS_SYNC
MS_ASYNC
MS_INVALIDATE

對映射的用法提供建議
madvise - give advice about use of memory
int madvise(void *addr, size_t length, int advice);


4. file advice

5. asynchronous I/O

kqueue

2017年10月19日 星期四

exclusive or :XOR


A ⊕ 1 = A'; //某些特定位元反轉
A ⊕ 0 = A;
A ⊕ A = 0; //快速比較兩個值;將變數reset
A ⊕ A' = 1;

➠ 將變數設為零  a^=a
➠ 快速比較兩個值  if ((a^b) == 0) {}

include/linux/etherdevice.h
/**
 * ether_addr_equal - Compare two Ethernet addresses
 * @addr1: Pointer to a six-byte array containing the Ethernet address
 * @addr2: Pointer other six-byte array containing the Ethernet address
 *
 * Compare two Ethernet addresses, returns true if equal
 *
 * Please note: addr1 & addr2 must both be aligned to u16.
 */
static inline bool ether_addr_equal(const u8 *addr1, const u8 *addr2)
{
#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
    u32 fold = ((*(const u32 *)addr1) ^ (*(const u32 *)addr2)) |
           ((*(const u16 *)(addr1 + 4)) ^ (*(const u16 *)(addr2 + 4)));

    return fold == 0;

#else
    const u16 *a = (const u16 *)addr1;
    const u16 *b = (const u16 *)addr2;

    return ((a[0] ^ b[0]) | (a[1] ^ b[1]) | (a[2] ^ b[2])) == 0;

#endif
}

➠ 某些特定位元反轉
status ^= 1 << x;                             //Toggling a bit
status |= 1 << x; //Setting a bit
status &= ~(1 << x);                         //Clearing a bit
bit = (status >> x) & 1;                     //Checking a bit
status ^= (-x ^ status) & (1 << n);     //Changing the nth bit to x
unsigned int a, b, mask = 1 << 6; 
a = 0xB1; // 10100001 
b = a ^ mask; /* flip the 6th bit */
https://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit

➠ 一個二進制數中1的數量是奇數還是偶數 (Parity Check)
例如:求10100001中1的數量是奇還是偶數; 
答案:1 ^ 0 ^ 1 ^ 0 ^ 0 ^ 0 ^ 0 ^ 1 = 1,
結果為1就是奇數個1,結果為0就是偶數個1;

➠ 校驗和恢復
if (a ^ b = c) then a ^ c = b
RAID5: 使用三塊磁盤(A、B、C)組成RAID5陣列,當寫資料時,將資料分成兩部分,分別寫到磁盤A和磁盤B,A^B的結果寫到磁盤C,
當讀取A的資料時,透過B ^ C可以對A的數據做校驗
當磁盤A出錯時,透過B ^ C也可以恢復磁盤A的資料

➠ [面試] XOR swap  #define swap(a,b) { a^=b, b^=a, a^=b; }
不用宣告新變數直接做swap
x = a ^ b
y = x ^ b
z = x ^ y

y = (a ^ b) ^ b = a ^ b ^ b = a ^ (b ^ b) = a ^ 0 = a
z = (a ^ b) ^ a = a ^ b ^ a = (a ^ a) ^ b = 0 ^ b = b
https://en.wikipedia.org/wiki/XOR_swap_algorithm

➠ [面試] 互換二進制數的奇偶位
#define N(n) ((n<<1) & 0xAAAAAAAA) | ((n>>1) & 0x55555555)
將一個int型態的數的奇偶位互換,
例如6的2進制為00000110,交換後得到00001001,輸出應該為9

➠ OddOccurrencesInArray
一個數組存放若干整數,一個數出現奇數次,其餘數均出現偶數次,找出這個出現奇數次的數?
交換律:A ^ B = B ^ A 
結合律:A ^ (B ^ C) = (A ^ B) ^ C

A ^ B ^ C ^ B ^ C ^ D ^ A

= A ^ A ^ B ^ B ^ C ^ C ^ D
= 0 ^ 0 ^ 0 ^ D
= 0 ^ D
= D
int iterator;
int result;
for (result = A[0], iterator = 1; iterator < N; result ^= A[iterator], iterator++);
return (result);
https://github.com/avrahamcohen/CodilitySolutions/blob/master/OddOccurrencesInArray.c

題目: 一個整數類型組除了一個數字之外,其他的數字都出現了兩次,找出這一個數字
題目: 一個整數類型組除了二個數字之外,其他的數字都出現了兩次,找出這二個數字
題目: 一個整數類型組除了三個數字之外,其他的數字都出現了兩次,找出這三個數字
https://www.lijinma.com/blog/2014/05/29/amazing-xor/

➠ 1 ~ 1000放在含有1001個元素的數組中,只有唯一的一個元素值重複,其它均只出現一次
每個數組元素只能訪問一次,不用輔助儲存空間
http://www.atove.com/Article/Details/635F056EDD0150910AEC759527EFD539

2017年10月2日 星期一

gdb除錯工具

GDB (Global Project DeBug): 1. Debug 2.反組譯 3.Hack執行檔
編譯選項: -g

# gdb

(gdb) run  <沒有設定breakpoint的話,程式會一直執行到結束>
(gdb) start  <在main設置暫時中斷點,並開始執行程式>
(gdb) next  <執行下一行指令,func call會被當作一行指令,不會進去func執行(over)>
(gdb) step  <執行下一行指令,連function都會進去一行一行執行(into)>
(gdb) continue  <繼續執行,直到下一個中斷點或是程式停止>
(gdb) return  <視同該frame已執行完畢>
(gdb) quit  <離開gdb>
(gdb) attach [PID]  <載入正在執行的程式以進行除錯>
(gdb) detach  <釋放已 attach 的程式>

➠ Breakpoint

(gdb) breakpoint [file:]function  <在function函式下中斷點>
(gdb) info break  <列出目前所有的中斷點>
(gdb) delete [num]  <移除第num個中斷點>

➠ Frame

所有的程式,每一個 function 都會被分配到一個 frame ,每個 frame 都是一個 組語 stack ,存放所有組語指令,然後再一行一行的執行,例如當程式執行到 printf 這個 function 的時候,就會進入該 printf frame 。
正在執行的函式就是 frame 0,而呼叫該函式的函式就是 frame 1,以此類推
(gdb) backtrace  <顯示出所有的frame的資訊>
(gdb) frame  <顯示現在的行數、函式、及其所傳送的參數>
(gdb) frame [num]  <切換至指定的frame(以印出區域變數)>
(gdb) up  <回到上一層frame>
(gdb) down  <到下一層frame>
(gdb) finish  <執行完目前的frame>
(gdb) jump [location]  <直接跳到指定位置(行數、函式...)>
(gdb) info frame  <詳細的frame資訊>

➠ Thread

(gdb) info thread  <看thread號碼>
(gdb) thread  <查看目前在哪個thread>
(gdb) thread [num]  <切換至第num個thread>

➠ Print

(gdb) info locals  <顯示目前執行函式內所有區域變數的值>
(gdb) print/format [variable]  <看某變數的數值>
format: d-整數; u-無號整數; o-八進位; t-二進位; a-位址; c-字元; f-浮點數
(gdb) print "%d,%d\n",var1,var2  <一次印出兩個以上的變數>
(gdb) print arr[1]@5  <印出變數arr[1]和之後的變數,共印出5個(arr[1]~arr[5])> 
(gdb) print *arr@3  <印出陣列arr的前3個變數(arr[0]~arr[2])>
(gdb) whatis [variable]  <顯示指定變數的型態>
(gdb) ptype [variable]  <顯示class, struct的定義內容>
(gdb) display [variable]  <持續顯示指定變數>
(gdb) undisplay [num]  <停止顯示指定變數>
(gdb) x/[num]bx [variable]  <顯示變數的記憶體的HEX>

➠ Watch
(gdb) watch [variable]  <觀察變數被更改時,會中斷程式,並印出更改前後的值>
(gdb) rwatch [variable]  <觀察變數被讀取時,會中斷程式,並印出更改前後的值>
(gdb) awatch [variable]  <觀察變數被讀取/更改時,會中斷程式,並印出更改前後的值>
(gdb) watch [variable > num]  <觀察變數是否大於num>
(gdb) info watch  <顯示所有的watchpoint>

➠ List
(gdb) list  <列出現在執行的位置上下5行>
(gdb) list [function]  <列出某函式的程式碼>

➠ Info

(gdb) info line  <查看程式目前運行的行數>
(gdb) info args  <顯示傳給目前執行函式的參數值>
(gdb) info reg  <顯示register的值>
(gdb) info handle  <列出目前處理signal的設定>
(gdb) info share  <顯示共享函式庫資訊>
info proc -- Show /proc process information about any running process
info program -- Execution status of the program
info sharedlibrary -- Status of loaded shared object libraries
info types -- All type names
info source -- Information about the current source file
info set -- Show all GDB settings

➠ Assemble

(gdb) disass [function]  <印出某函式的組語>
(gdb) disass /m [function]  <印出某函式的組語與程式碼內容>
(gdb) disass /r [function]  <把組語的內容用HEX的方式印出來>

➠ GDB dashboard
https://github.com/cyrus-and/gdb-dashboard
$ wget -P ~ git.io/.gdbinit
# gdb ./examples/kni/build/app/kni
>>> dashboard -layout source assembly threads stack registers expressions memory history
>>> dashboard -output /dev/pts/3
>>> set args -c 0xFFFFF -n 4 -- -P -p 0x3 --config="(0,0,1),(1,2,3)"
>>> br kni_ingress
>>> run
>>> x/32bx pkts_burst[0]
>>> dashboard memory watch 0x7fffc924ea00 100

dashboard memory -output -- Set the output file/TTY for both the dashboard and modules
dashboard memory clear -- Clear all the watched regions
dashboard memory unwatch -- Stop watching a memory region by address
dashboard memory watch -- Watch a memory region by address and length


參考資料
http://gitqwerty777.github.io/gdb-introduction/
http://www.study-area.org/cyril/opentools/opentools/x1265.html

2017年9月22日 星期五

建立行程: system / fork / clone / execl

➠ system - execute a shell command (3)
int system(const char *command);

The system() library function uses fork(2) to create a child process that executes the shell command specified in command
using execl(3) as follows:
           execl("/bin/sh", "sh", "-c", command, (char *) 0);
system() returns after the command has been completed.
The main cost of system() is inefficiency: additional system calls are required to create the process that runs the shell and to execute the shell.

During execution of the command, SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored, in the process that calls system().

➠ fork - create a child process (2)
pid_t fork(void);
➠ clone, __clone2 - create a child process (2)
int clone(int (*fn)(void *), void *child_stack,
                 int flags, void *arg, ...
                 /* pid_t *ptid, void *newtls, pid_t *ctid */ );
C library/kernel differences
      Since version 2.3.3, rather than invoking the kernel's fork() system call, the glibc fork() wrapper that is provided as part of the NPTL threading implementation invokes clone(2) with flags that provide the same effect as the traditional system call.

➠ execl, execlp, execle, execv, execvp, execvpe - execute a file (3)
The exec() family of functions replaces the current process image with a new process image.
int execl(const char *path, const char *arg, ... /* (char  *) NULL */);
int execlp(const char *file, const char *arg, ... /* (char  *) NULL */);
int execle(const char *path, const char *arg, ... /*, (char *) NULL, char * const envp[] */);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[], char *const envp[]);

➠ execve - execute program (2)
int execve(const char *filename, char *const argv[], char *const envp[]);

# strace ./create_process
//system()
rt_sigaction(SIGINT, {SIG_IGN, [], SA_RESTORER, 0x7f5cc398d7f0}, {SIG_DFL, [], 0}, 8) = 0
rt_sigaction(SIGQUIT, {SIG_IGN, [], SA_RESTORER, 0x7f5cc398d7f0}, {SIG_DFL, [], 0}, 8) = 0
rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0
clone(child_stack=0, flags=CLONE_PARENT_SETTID|SIGCHLD, parent_tidptr=0x7ffc96f5c9ac) = 3576
wait4(3576,
...
[{WIFEXITED(s) && WEXITSTATUS(s) == 0}], 0, NULL) = 3576
rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7f5cc398d7f0}, NULL, 8) = 0
rt_sigaction(SIGQUIT, {SIG_DFL, [], SA_RESTORER, 0x7f5cc398d7f0}, NULL, 8) = 0
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=3576, si_uid=1001, si_status=0, si_utime=0, si_stime=0} ---

//fork()
clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f5cc3f379d0) = 3823
wait4(3823,
...
[{WIFEXITED(s) && WEXITSTATUS(s) == 0}], 0, NULL) = 3823
--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=3823, si_uid=1001, si_status=0, si_utime=0, si_stime=0} ---

//execl
execve("./cmd_process", ["cmd_process"], [/* 20 vars */]) = 0

➠ sigaction, rt_sigaction - examine and change a signal action
int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);
➠ sigprocmask, rt_sigprocmask - examine and change blocked signals
/* Prototype for the underlying system call */
int rt_sigprocmask(int how, const kernel_sigset_t *set, kernel_sigset_t *oldset, size_t sigsetsize);
    SIG_BLOCK
        The set of blocked signals is the union of the current set and the set argument.


➠ kernel/fork.c
/*
 *  Ok, this is the main fork-routine.
 *
 * It copies the process, and if successful kick-starts
 * it and waits for it to finish using the VM if required.
 */
long _do_fork(unsigned long clone_flags,
          unsigned long stack_start,
          unsigned long stack_size,
          int __user *parent_tidptr,
          int __user *child_tidptr,
          unsigned long tls)
{
    struct task_struct *p;
...
    p = copy_process(clone_flags, stack_start, stack_size,
             child_tidptr, NULL, trace, tls, NUMA_NO_NODE);
...
}

/*
 * This creates a new process as a copy of the old one,
 * but does not actually start it yet.
 *
 * It copies the registers, and all the appropriate
 * parts of the process environment (as per the clone
 * flags). The actual kick-off is left to the caller.
 */
static __latent_entropy struct task_struct *copy_process(
                    unsigned long clone_flags,
                    unsigned long stack_start,
                    unsigned long stack_size,
                    int __user *child_tidptr,
                    struct pid *pid,
                    int trace,
                    unsigned long tls,
                    int node)



參考資料:
➠ 範例程式
https://github.com/bruce690813/example/tree/master/test_create_process
➠ 補充資料 poepn


2017年9月19日 星期二

Zero-length arrays

Zero-length arrays are allowed in GNU C. 
They are very useful as the last element of a structure that is really a header for a variable-length object

在某些情況下,一個資料結構之定義的尾端會包含一個選用區塊。
#include <stdio.h>
#include <stdlib.h>

struct abc {
    int age;
    char *name[20];
    //...
    //char *placeholder;
    char placeholder[0];
};

int main()
{
    char buffer[30];
    struct abc *data = malloc(sizeof(struct abc) + 100);
    //placeholder會指向後面多的那100

    printf("sizeof(struct abc) = %zu\n", sizeof(struct abc));
    printf("data = %p, placeholder = %p\n", data, data->placeholder);

    return 0;
}

$ ./a.out
sizeof(struct abc) = 168

data = 0x555c65741010, placeholder = 0x555c657410b8

選用區塊從placeholder起算。
placeholder被定義成大小為0的向量。也就是說,abc被分配時若包含這個選用區塊,placeholder就會指向此區塊的開端處。不需要選用區塊時,placeholder就只是一個指向此結構尾端的指標;不會耗用任何空間。

include/net/inet_sock.h
/** struct ip_options - IP Options
 *
 * @faddr - Saved first hop address
 * @nexthop - Saved nexthop address in LSRR and SSRR
 * @is_strictroute - Strict source route
 * @srr_is_hit - Packet destination addr was our one
 * @is_changed - IP checksum more not valid
 * @rr_needaddr - Need to record addr of outgoing dev
 * @ts_needtime - Need to record timestamp
 * @ts_needaddr - Need to record addr of outgoing dev
 */
struct ip_options {
    __be32      faddr;
    __be32      nexthop;
    unsigned char   optlen;
    unsigned char   srr;
    unsigned char   rr;
    unsigned char   ts;
    unsigned char   is_strictroute:1,
            srr_is_hit:1,
            is_changed:1,
            rr_needaddr:1,
            ts_needtime:1,
            ts_needaddr:1;
    unsigned char   router_alert;
    unsigned char   cipso;
    unsigned char   __pad2;
    unsigned char   __data[0];
};

net/ipv4/ip_sockglue.c
static int do_ip_getsockopt(struct sock *sk, int level, int optname,
                char __user *optval, int __user *optlen, unsigned int flags)
{
...
    switch (optname) {
    case IP_OPTIONS:
    {
        unsigned char optbuf[sizeof(struct ip_options)+40];
        struct ip_options *opt = (struct ip_options *)optbuf;
        struct ip_options_rcu *inet_opt;

        inet_opt = rcu_dereference_protected(inet->inet_opt,
                             lockdep_sock_is_held(sk));
        opt->optlen = 0;
        if (inet_opt)
            memcpy(optbuf, &inet_opt->opt,
                   sizeof(struct ip_options) +
                   inet_opt->opt.optlen);
        release_sock(sk);

        if (opt->optlen == 0)
            return put_user(0, optlen);

        ip_options_undo(opt);

        len = min_t(unsigned int, len, opt->optlen);
        if (put_user(len, optlen))
            return -EFAULT;
        if (copy_to_user(optval, opt->__data, len))
            return -EFAULT;
        return 0;

    }
...
}

net/ipv4/ip_output.c
static int ip_setup_cork(struct sock *sk, struct inet_cork *cork,
             struct ipcm_cookie *ipc, struct rtable **rtp)
{
...
    opt = ipc->opt;
    if (opt) {
        if (!cork->opt) {
            cork->opt = kmalloc(sizeof(struct ip_options) + 40,
                        sk->sk_allocation);
            if (unlikely(!cork->opt))
                return -ENOBUFS;
        }
        memcpy(cork->opt, &opt->opt, sizeof(struct ip_options) + opt->opt.optlen);
        cork->flags |= IPCORK_OPT;
        cork->addr = ipc->addr;
    }
...
}

note:
➠ 用在不確定後面會不會有payload的而且是不一定長度的時候
➠ 要小心資料對齊問題
➠ 主要是減少一次記憶體分配,釋放時也少一次,比較方便

參考資料
https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html

2017年9月12日 星期二

likely / unlikely 編譯期間優化條件檢查

多數時刻,當核心以某個外來值比較一個變數,以檢視特定條件是否滿足時,結果很有可能是可預料的。這是很常見的事,例如,那些實施sanity check的程式碼。核心會分別使用likely和unlikely巨集,把那些可能傳回一個真(1)或假(0)值的比較結果包裹起來。這些巨集會用到gcc編譯器的一項功能;此項功能會根據該項資訊來優化程式碼的編譯。

實例: 假設你必須呼叫do_something函式,但是,如果失敗的話,你必須使用handle_error韓式予以處理。
err = do_something(x, y, z);
if (err)
    handle_error(err);

假如do_something很少失敗,則可以將程式改寫成下面這樣:
err = do_something(x, y, z);
if (unlikely(err))
    handle_error(err);

likely和unlikely巨集所能進行的優化動作之一就是處理IP header裡面的選項。
IP選項的使用只限於一些特定情況,核心可以安全地假設多數IP封包不會攜帶IP選項。
轉送IP封包的最後一個階段係由ip_forward_finish負責。此函式會使用unlikely巨集把
「用來檢查是否要處理IP選項的條件」包裹起來。

net/ipv4/ip_forward.c
static int ip_forward_finish(struct net *net, struct sock *sk, struct sk_buff *skb) { struct ip_options *opt = &(IPCB(skb)->opt); __IP_INC_STATS(net, IPSTATS_MIB_OUTFORWDATAGRAMS); __IP_ADD_STATS(net, IPSTATS_MIB_OUTOCTETS, skb->len); if (unlikely(opt->optlen)) ip_forward_options(skb); return dst_output(net, sk, skb); }

include/linux/compiler.h
/*
 * Using __builtin_constant_p(x) to ignore cases where the return
 * value is always the same.  This idea is taken from a similar patch
 * written by Daniel Walker.
 */
# ifndef likely
#  define likely(x) (__branch_check__(x, 1, __builtin_constant_p(x)))
# endif
# ifndef unlikely
#  define unlikely(x)   (__branch_check__(x, 0, __builtin_constant_p(x)))

#else
# define likely(x)  __builtin_expect(!!(x), 1)
# define unlikely(x)    __builtin_expect(!!(x), 0)
#endif

# endif