• 页面

  • 功能

  • 标签

  • kernelnewbies

    DoWhile(0)

    星期四, 09月 25th, 2008

    更详细参考Kernelnewbies
    为啥内核里有这么多 do{ }while(0) 的宏啊?一开始我也好不明白。感觉不出用了会有什么效果。不过明白之后就知道它的好处了。好处就在于多语句的宏。

    #define FOO(x) print(”arg is %sn”,x);do_something(x);

    在代码中使用:

    if(2==blah)
     
    FOO(blah);

    预编译展开后:

    if(2==blah)
     
    print(”arg is %sn”,blah);
     
    do_something(blah);

    看到了吧,do_something函数已经脱离了if语句的控制了。这可不是我们想要的。使用do{}while(0);就万无一失了。

    if (2== blah)
     
    do {
    printf(”arg is %sn”, blah);
     
    do_something(blah);
    } while (0);

    当然你也可以使用下面这种形式:

    #define exch(x,y) { int tmp; tmp=x; x=y; y=tmp; }

    但是它在if-else语句中会出现问题。如:

    if (x > y)
     
    exch(x,y); // Branch 1
     
    else
    do_something(); // Branch 2

    展开后:

    if (x > y) { [...]

    likely() and unlikely() (转)

    星期四, 09月 25th, 2008

    (前言:之前我译过这版likelyUnlikely,但由于旧的博客坏了,再也找不回那篇文章了。但发现另有网友翻译了,由此转自http://blog.chinaunix.net/u/27708/showart_680626.html)
    内核FAQ之LikelyUnlikely
    作者: Haitao
    likely() and unlikely()
    它们是指什么?
    在linux内核代码中,经常看到likely()和unlikely()会在条件语句中调用到,如:
    bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx);
    if (unlikely(!bvl)) {
    mempool_free(bio, bio_pool);
    bio = NULL;
    goto out;
    }
    事实上,根据这两个函数可以得知条件语句中最可能发生的情形,从而告知编译器以允许它正确地优化条件分支。
    在include/linux/complier.h头文件中可以找到它们的宏定义:
    #define likely(x) __builtin_expect(!!(x), 1)
    #define unlikely(x) __builtin_expect(!!(x), 0)
    在gcc文档中是这样来解释__builtin_expect()的作用:

    — Built-in Function: long __builtin_expect (long EXP, long C)
    You may use `__builtin_expect’ to provide the compiler with branch
    prediction information. In general, you should prefer [...]

    什么是asmlinkage

    星期四, 09月 25th, 2008

    下面首先在kernelnewibes上的解释。

    What is asmlinkage?
    The asmlinkage tag is one other thing that we should observe aboutthis simple function.
    This is a #define for some gcc magic that tellsthe compiler that the function should not
    expect to find any of itsarguments in registers (a common optimization), but only on
    theCPU’s stack. Recall our earlier assertion that system_call consumesits [...]

    啥是__init __exit宏

    星期四, 09月 25th, 2008

    更详细内容请点击kernelnewbies
    原始定义在include/linux/init.h
    #define __init __attribute__ ((__section__ (”.init.text”)))
    #define __initdata __attribute__ ((__section__ (”.init.data”)))

    #define __exitdata __attribute__ ((__section__(”.exit.data”)))

    #define __exit_call __attribute_used__ __attribute__ ((__section__ (”.exitcall.exit”)))

    #ifdef MODULE

    #define __exit __attribute__ ((__section__(”.exit.text”)))

    #else

    #define __exit [...]