2016年1月2日 星期六

Linux Kernel(15)- Platform Devices


很多人心中都有過一個問題What is the difference between Platform driver and normal device driver?,簡單的來說Platform devices就non-discoverable,也就是device本身沒辦法跟系統說"我在這裡",典型的就是I2C device,它不會通知kernel"我在這裡",通常是預先知道有個I2C device在那裡,再由software設定好,這類non-discoverable device就適用Platform devices架構來寫。
platform device會被connect在platform bus上,而platform bus是一個虛擬的bus(pseudo-bus),這樣可以讓整個架構platform driver符合Linux的標準driver model。

這篇會根據The platform device API教導如何寫一個簡單的Platform devices,基本上最基本的platform device只需要name,因為platform bus會根據platform device與platform driver的name是否match執行driver的probe(),而最簡單的platform driver只需要name,跟probe()與remove()即可。
#include <linux/module.h>
#include <linux/platform_device.h>

MODULE_AUTHOR("Brook");
MODULE_DESCRIPTION("Kernel module for demo");
MODULE_LICENSE("GPL");

#define DEVNAME "brook"

#define DYN_ALLOC 1

static struct platform_device brook_device = {
    .name = DEVNAME,
};

static int brook_probe(struct platform_device *pdev)
{
    pr_info("%s(#%d)\n", __func__, __LINE__);
    return 0;
}

static int brook_remove(struct platform_device *pdev)
{
    pr_info("%s(#%d)\n", __func__, __LINE__);
    return 0;
}

static struct platform_driver brook_driver = {
    .driver = {
        .name  = DEVNAME,
        .owner = THIS_MODULE,
    },
    .probe  = brook_probe,
    .remove = brook_remove,
};

static int __init brook_init(void)
{
    int err;
    pr_info("%s(#%d)\n", __func__, __LINE__);

    err = platform_device_register(&brook_device);
    if (err) {
        pr_err("%s(#%d): platform_device_register failed(%d)\n",
                __func__, __LINE__, err);
        return err;
    }

    err = platform_driver_register(&brook_driver);
    if (err) {
        dev_err(&(brook_device.dev), "%s(#%d): platform_driver_register fail(%d)\n",
                __func__, __LINE__, err);
        goto dev_reg_failed;
    }
    return err;

dev_reg_failed:
    platform_device_unregister(&brook_device);

    return err;
}
module_init(brook_init);

static void __exit brook_exit(void)
{
    dev_info(&(brook_device.dev), "%s(#%d)\n", __func__, __LINE__);
    platform_device_unregister(&brook_device);
    platform_driver_unregister(&brook_driver);
}
module_exit(brook_exit);


使用platform_device_register()會導致"brook.0" does not have a release() function, it is broken and must be fixed.的OOPS,可以改用platform_device_alloc() + platform_device_add(),platform_device_alloc()裡面就會做pa->pdev.dev.release = platform_device_release。
#include <linux/module.h>
#include <linux/platform_device.h>

MODULE_AUTHOR("Brook");
MODULE_DESCRIPTION("Kernel module for demo");
MODULE_LICENSE("GPL");

#define DEVNAME "brook"

#define DYN_ALLOC 1

static struct platform_device *brook_device;

static int brook_probe(struct platform_device *pdev)
{
    pr_info("%s(#%d)\n", __func__, __LINE__);
    return 0;
}

static int brook_remove(struct platform_device *pdev)
{
    pr_info("%s(#%d)\n", __func__, __LINE__);
    return 0;
}

static struct platform_driver brook_driver = {
    .driver = {
        .name  = DEVNAME,
        .owner = THIS_MODULE,
    },
    .probe  = brook_probe,
    .remove = brook_remove,
};

static int __init brook_init(void)
{
    int err;
    pr_info("%s(#%d)\n", __func__, __LINE__);

    /* using platform_device_alloc() + platform_device_add() 
     * instead of platform_device_register() to avoid the OOPS, 
     *     "Device 'brook.0' does not have a release() function,
     *      it is broken and must be fixed."
     */
    brook_device = platform_device_alloc(DEVNAME, 0);
    if (!brook_device) {
        pr_err("%s(#%d): platform_device_alloc fail\n",
               __func__, __LINE__);
        return -ENOMEM;
    }

    err = platform_device_add(brook_device);
    if (err) {
        pr_err("%s(#%d): platform_device_add failed\n",
               __func__, __LINE__);
        goto dev_add_failed;
    }

    err = platform_driver_register(&brook_driver);
    if (err) {
        dev_err(&(brook_device->dev), "%s(#%d): platform_driver_register fail(%d)\n",
                __func__, __LINE__, err);
        goto dev_reg_failed;
    }
    return err;

dev_add_failed:
    platform_device_put(brook_device);
dev_reg_failed:
    platform_device_unregister(brook_device);

    return err;
}
module_init(brook_init);

static void __exit brook_exit(void)
{
    dev_info(&(brook_device->dev), "%s(#%d)\n", __func__, __LINE__);
    platform_device_unregister(brook_device);
    platform_driver_unregister(&brook_driver);
}
module_exit(brook_exit);



    參考資料:
  1. Documentation/driver-model
  2. What is the difference between Platform driver and normal device driver?
  3. The platform device API
  4. Linux Kernel architecture for device drivers
  5. platform_driver_register()--如何match之后调用probe
  6. Improved dynamically allocated platform_device interface




2015年12月26日 星期六

OpenEmbedded -- Creating and using an SDK


SDK包含了開發時所需的相關檔案,有些還包含了整個開發環境(tool/command),避免系統的tool/command跟SDK需要的不同造成的error,一個SDK應該包含以下內容:(YOCTO Slides)
  1. Compilers or cross-compilers
  2. Linkers
  3. Library headers
  4. Debuggers
  5. Custom utilities


這篇文章就是在介紹如何使用Openembedded建立一個generic SDK供他人開發application,使用指令bitbake -v meta-toolchain即可產生generic SDK,並產生一個install的script,放置於oe/oe-core/build/tmp-eglibc/deploy/sdk/底下,執行過程如下
brook@vista:/home/brook/oe/oe-core/build$ bitbake -v meta-toolchain

...

+ chmod +x /home/brook/oe/oe-core/build/tmp-eglibc/deploy/sdk/oecore-x86_64-armv7a-vfp-neon-toolchain-oe-core.0.sh

+ cat /home/brook/oe/oe-core/build/tmp-eglibc/deploy/sdk/oecore-x86_64-armv7a-vfp-neon-toolchain-oe-core.0.tar.bz2

+ rm /home/brook/oe/oe-core/build/tmp-eglibc/deploy/sdk/oecore-x86_64-armv7a-vfp-neon-toolchain-oe-core.0.tar.bz2


NOTE: Tasks Summary: Attempted 1685 tasks of which 1312 didn't need to be rerun and all succeeded.
brook@vista:/home/brook/oe/oe-core/build$ tree tmp-eglibc/deploy/sdk/
tmp-eglibc/deploy/sdk/
`-- oecore-x86_64-armv7a-vfp-neon-toolchain-oe-core.0.sh

0 directories, 1 file

接著直要將底下的script(oecore-x86_64-armv7a-vfp-neon-toolchain-oe-core.0.sh)給developer開發即可,-d後面帶安裝目錄,安裝過程需要SUDO權限,
brook@vista:/home/brook/oe/oe-core/build$ ./tmp-eglibc/deploy/sdk/oecore-x86_64-armv7a-vfp-neon-toolchain-oe-core.0.sh --help
Usage: oecore-x86_64-armv7a-vfp-neon-toolchain-oe-core.0.sh [-y] [-d <dir>]
  -y         Automatic yes to all prompts
  -d <dir>   Install the SDK to <dir>
======== Advanced DEBUGGING ONLY OPTIONS ========
  -S         Save relocation scripts
  -R         Do not relocate executables
  -D         use set -x to see what is going on
brook@vista:~$ /home/brook/oe/oe-core/build/tmp-eglibc/deploy/sdk/oecore-x86_64-armv7a-vfp-neon-toolchain-oe-core.0.sh -d /opt/oe -D
+ printf 'Enter target directory for SDK (default: /usr/local/oecore-x86_64): '
Enter target directory for SDK (default: /usr/local/oecore-x86_64): + '[' /opt/oe = '' ']'
+ echo /opt/oe
/opt/oe

...

+ '[' 0 = 0 ']'
+ /usr/bin/sudo rm /SSD/opt/oe/relocate_sdk.py /SSD/opt/oe/relocate_sdk.sh
+ echo 'SDK has been successfully set up and is ready to be used.'
SDK has been successfully set up and is ready to be used.
+ exit 0

要使用SDK之前,必須先source安裝目錄下開頭為environment-setup-的script,設置相關的環境變數,我的script內容如下
export PATH=/SSD/opt/oe/sysroots/x86_64-oesdk-linux/usr/bin:/SSD/opt/oe/sysroots/x86_64-oesdk-linux/usr/bin/armv
7a-vfp-neon-oe-linux-gnueabi:$PATH
export PKG_CONFIG_SYSROOT_DIR=/SSD/opt/oe/sysroots/armv7a-vfp-neon-oe-linux-gnueabi
export PKG_CONFIG_PATH=/SSD/opt/oe/sysroots/armv7a-vfp-neon-oe-linux-gnueabi/usr/lib/pkgconfig
export CONFIG_SITE=/SSD/opt/oe/site-config-armv7a-vfp-neon-oe-linux-gnueabi
export CC="arm-oe-linux-gnueabi-gcc  -march=armv7-a -mthumb-interwork -mfloat-abi=softfp -mfpu=neon -mthumb-inte
rwork --sysroot=/SSD/opt/oe/sysroots/armv7a-vfp-neon-oe-linux-gnueabi"
export CXX="arm-oe-linux-gnueabi-g++  -march=armv7-a -mthumb-interwork -mfloat-abi=softfp -mfpu=neon -mthumb-int
erwork --sysroot=/SSD/opt/oe/sysroots/armv7a-vfp-neon-oe-linux-gnueabi"
export CPP="arm-oe-linux-gnueabi-gcc -E  -march=armv7-a -mthumb-interwork -mfloat-abi=softfp -mfpu=neon -mthumb-interwork --sysroot=/SSD/opt/oe/sysroots/armv7a-vfp-neon-oe-linux-gnueabi"
export AS="arm-oe-linux-gnueabi-as "
export LD="arm-oe-linux-gnueabi-ld  --sysroot=/SSD/opt/oe/sysroots/armv7a-vfp-neon-oe-linux-gnueabi"
export GDB=arm-oe-linux-gnueabi-gdb
export STRIP=arm-oe-linux-gnueabi-strip
export RANLIB=arm-oe-linux-gnueabi-ranlib
export OBJCOPY=arm-oe-linux-gnueabi-objcopy
export OBJDUMP=arm-oe-linux-gnueabi-objdump
export AR=arm-oe-linux-gnueabi-ar
export NM=arm-oe-linux-gnueabi-nm
export M4=m4
export TARGET_PREFIX=arm-oe-linux-gnueabi-
export CONFIGURE_FLAGS="--target=arm-oe-linux-gnueabi --host=arm-oe-linux-gnueabi --build=x86_64-linux --with-libtool-sysroot=/SSD/opt/oe/sysroots/armv7a-vfp-neon-oe-linux-gnueabi"
export CFLAGS=" -O2 -fexpensive-optimizations -frename-registers -fomit-frame-pointer"
export CXXFLAGS=" -O2 -fexpensive-optimizations -frename-registers -fomit-frame-pointer -fpermissive"
export LDFLAGS="-Wl,-O1 -Wl,--hash-style=gnu -Wl,--as-needed"
export CPPFLAGS=""
export OECORE_NATIVE_SYSROOT="/SSD/opt/oe/sysroots/x86_64-oesdk-linux"
export OECORE_TARGET_SYSROOT="/SSD/opt/oe/sysroots/armv7a-vfp-neon-oe-linux-gnueabi"
export OECORE_ACLOCAL_OPTS="-I /SSD/opt/oe/sysroots/x86_64-oesdk-linux/usr/share/aclocal"
export OECORE_DISTRO_VERSION="20151225"
export OECORE_SDK_VERSION="oe-core.0"
export PYTHONHOME=/SSD/opt/oe/sysroots/x86_64-oesdk-linux/usr
export ARCH=arm
export CROSS_COMPILE=arm-oe-linux-gnueabi-


以下是我用這SDK編譯一個檔案,並放入target中執行
brook@vista:~$ source /opt/oe/environment-setup-armv7a-vfp-neon-oe-linux-gnueabi
brook@vista:~$ cat main.c
#include <stdio.h>

int main(int argc, char *argv[])
{
        printf("hello\n");
        return 0;
}

brook@vista:~$ $CC -o brook-sdk main.c

D:\Projects>adb push z:\brook-sdk /
688 KB/s (5644 bytes in 0.008s)

D:\Projects>adb shell chmod +x /brook-sdk

D:\Projects>adb shell /brook-sdk
hello

開發環境架構圖


    參考資料:
  1. Yocto Project and OpenEmbedded development course
  2. Yocto Project Quick Start -- SDK Generation





2015年12月19日 星期六

OpenEmbedded - Writing Meta Data for adding Kernel Module package


OpenEmbedded User Manual - CH3, Writing Meta Data (Adding packages)之後,這一篇是教導如何新增Kernel Module package。 BB檔的寫法與OpenEmbedded User Manual - CH3, Writing Meta Data (Adding packages)雷同,只是我們這次iherit的class是module

/oe-core/meta/recipes-kernel/brook/brook_1.0.bb

inherit module
DESCRIPTION = "Brook Out Tree Kernel Module"
LICENSE = "GPLv2"
LIC_FILES_CHKSUM = "file://LICENSE;md5=5ff2bd2dd80c7cc542a6b8de3ee4ff87"

PR = "r1-${KERNEL_VERSION}"

# This DEPENDS is to serialize kernel module builds
DEPENDS = "virtual/kernel"


SRC_URI = "file://brook.patch \
"

S = "${WORKDIR}/brook-linux-${PV}"

這邊的SRC_URI我是使用patch格式,當然你也可以使用zip格式,但是zip格式需要考慮目錄名稱必須為"${WORKDIR}/brook-linux-${PV}",即bb檔中的S,但是如果是patch就不用管S目錄名稱為何了。

完整檔案結構如下

後面會陸續介紹每個檔案
    /oe-core/meta/recipes-kernel/brook
    |-- brook_1.0.bb
    |-- files
    |   `-- brook.patch
    `-- git
        |-- LICENSE
        |-- Makefile
        `-- main.c


Makefile

ifneq ($(KERNELRELEASE),)
# obj-m := <module_name>.o
# <module_name>-y := <src1>.o <src2>.o ...

        EXTRA_CFLAGS += -DYAFFS_OUT_OF_TREE

        obj-m := brook.o

        brook-objs := main.o
else
        PWD := $(shell pwd)

modules:
 $(MAKE) -C $(KERNEL_SRC) M=$(PWD) modules

modules_install:
 $(MAKE) -C $(KERNEL_SRC) M=$(PWD) modules_install

clean:
 $(MAKE) -C $(KERNEL_SRC) M=$(PWD) clean
endif

這是一般的Kernel Module寫法,沒有特別的地方,Out Tree build時KERNELRELEASE為空字串,所以會用下面那段。

License的內容就只有"License: GPL"這個字串

main.c

Module的主程式,只是在init與exit時印出簡單字串而已。
#include <linux/module.h>

MODULE_AUTHOR("Brook");
MODULE_DESCRIPTION("Kernel module for demo");
MODULE_LICENSE("GPL");

static int __init brook_init(void)
{
        printk(KERN_INFO "Brook Module Init\n");
        return 0;
}
module_init(brook_init);

static void __exit brook_exit(void)
{
        printk(KERN_INFO "Brook Module Exit\n");
        return;
}
module_exit(brook_exit);


brook.patch

這是我把檔案全部放在git目錄底下,做source control,並用git format-patch產生的,將產生後的檔案放置files/brook.patch。




2015年12月13日 星期日

mkbootimg -- pack boot images utils


mkbootimg是Android project的一部分,用來封裝boot image的,其使用參數如下:
usage: mkbootimg
       --kernel <filename>
       --ramdisk <filename>
       [ --second <2ndbootloader-filename> ]
       [ --cmdline <kernel-commandline> ]
       [ --board <boardname> ]
       [ --base <address> ]
       [ --pagesize <pagesize> ]
       [ --ramdisk_offset <ramdisk_offset> ]
       [ --dt <filename> ]
       [ --tags-addr <address> ]
       -o|--output <filename>


基本上就是將kenrnel、ramdisk、device tree等封裝成一個檔案,讓boot loader能將其載入RAM中,並正確執行。檔案的layout如下(就如bootimg.h中註解所提到的,https://www.codeaurora.org/cgit/quic/femto/platform/system/core/tree/mkbootimg/bootimg.h?h=LNX.LE.5.0.1-57023-9x40)
/*
** +-----------------+ 
** | boot header     | 1 page
** +-----------------+
** | kernel          | n pages  
** +-----------------+
** | ramdisk         | m pages  
** +-----------------+
** | second stage    | o pages
** +-----------------+
** | device tree     | p pages
** +-----------------+
**
** n = (kernel_size + page_size - 1) / page_size
** m = (ramdisk_size + page_size - 1) / page_size
** o = (second_size + page_size - 1) / page_size
** p = (dt_size + page_size - 1) / page_size
**
** 0. all entities are page_size aligned in flash
** 1. kernel and ramdisk are required (size != 0)
** 2. second is optional (second_size == 0 -> no second)
** 3. load each element (kernel, ramdisk, second) at
**    the specified physical address (kernel_addr, etc)
** 4. prepare tags at tag_addr.  kernel_args[] is
**    appended to the kernel commandline in the tags.
** 5. r0 = 0, r1 = MACHINE_TYPE, r2 = tags_addr
** 6. if second_size != 0: jump to second_addr
**    else: jump to kernel_addr
*/

其中boot header會有一些information,讓LK能正確的將各個section load到正確的Address上,boot header定義如下
typedef struct boot_img_hdr boot_img_hdr;

#define BOOT_MAGIC "ANDROID!"
#define BOOT_MAGIC_SIZE 8
#define BOOT_NAME_SIZE 16
#define BOOT_ARGS_SIZE 512

struct boot_img_hdr
{
    unsigned char magic[BOOT_MAGIC_SIZE];

    unsigned kernel_size;  /* size in bytes */
    unsigned kernel_addr;  /* physical load addr */

    unsigned ramdisk_size; /* size in bytes */
    unsigned ramdisk_addr; /* physical load addr */

    unsigned second_size;  /* size in bytes */
    unsigned second_addr;  /* physical load addr */

    unsigned tags_addr;    /* physical addr for kernel tags */
    unsigned page_size;    /* flash page size we assume */
    unsigned dt_size;      /* device tree in bytes */
    unsigned unused;       /* future expansion: should be 0 */
    unsigned char name[BOOT_NAME_SIZE]; /* asciiz product name */
    
    unsigned char cmdline[BOOT_ARGS_SIZE];

    unsigned id[8]; /* timestamp / checksum / sha1 / etc */
};

第一個欄位magic用以識別這個image是否為有效,後續會帶著kernel、ramdisk、device tree跟second的size大小,以及要load的address。 以下是我的platform的FLASH與其RAM的layout,如下圖

基本上,main function就是將這些檔案pack成一個檔案,並做page alignment,有興趣再去看code吧。

下面這段是我寫的umkbootimg,讀取boot header資訊後印出。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>

#include "bootimg.h"

static void *load_file(const char *fn, unsigned sz)
{
    char *data;
    int fd;

    data = 0;
    fd = open(fn, O_RDONLY);
    if(fd < 0) return 0;

    data = (char*) malloc(sz);
    if(data == 0) goto oops;

    if(read(fd, data, sz) != sz) goto oops;
    close(fd);

    return data;

oops:
    close(fd);
    if(data != 0) free(data);
    return 0;
}

int usage(void)
{
    fprintf(stderr,"usage: umkbootimg <filename>\n");
    return 1;
}


int main(int argc, char **argv)
{
    boot_img_hdr *hdr;

    char *img_name = 0;
    void *img_data = 0;
    unsigned sz;

    if (argc < 2) {
        return usage();
    }

    hdr = (boot_img_hdr *) load_file(argv[1], sizeof(boot_img_hdr));
    hdr->magic[BOOT_MAGIC_SIZE] = 0;
    printf("magic:%s\n", hdr->magic);
    printf("kernel_size:%u/0x%08x\n", hdr->kernel_size, hdr->kernel_size);
    printf("kernel_addr:%u/0x%08x\n", hdr->kernel_addr, hdr->kernel_addr);

    printf("ramdisk_size:%u/0x%08x\n", hdr->ramdisk_size, hdr->ramdisk_size);
    printf("ramdisk_addr:%u/0x%08x\n", hdr->ramdisk_addr, hdr->ramdisk_addr);

    printf("second_size:%u/0x%08x\n", hdr->second_size, hdr->second_size);
    printf("second_addr:%u/0x%08x\n", hdr->second_addr, hdr->second_addr);

    printf("tags_addr:%u/0x%08x\n", hdr->tags_addr, hdr->tags_addr);

    printf("page_size:%u/0x%08x\n", hdr->page_size, hdr->page_size);

    printf("dt_size:%u/0x%08x\n", hdr->dt_size, hdr->dt_size);

    printf("name:%s\n", hdr->name);

    printf("cmdline:%s\n", hdr->cmdline);
    return 0;
}


    參考資料:
  • https://www.codeaurora.org/cgit/quic/femto/platform/system/core/tree/mkbootimg/bootimg.h?h=LNX.LE.5.0.1-57023-9x40




2015年9月29日 星期二

create an initramfs on mdm9x40


利用linux提供的script建立initramfs在先前的文章已經提過,可參考如何利用kvm/qemu練習linux module之new update,基本上就是呼叫gen_initramfs_list.sh建立file system清單,使用gen_init_cpio將清單轉成CPIO格式後,在使用gzip做壓縮。相關指令如下:
W=/home/brook/projects/9x40/apps_proc
RD=/home/brook/projects/initramfs
CPIO=/home/brook/projects/initramfs.cpio
SYSROOT=${W}/oe-core/build/tmp-eglibc/sysroots/
OUTPUT=/home/brook/projects/9x40-initramfs.img
sh ${W}/kernel/scripts/gen_initramfs_list.sh -d ${RD} > /tmp/gen_initramfs_list
${W}/oe-core/build/tmp-eglibc/sysroots/mdm9640/usr/src/kernel/usr/gen_init_cpio /tmp/gen_initramfs_list > ${CPIO}
gzip -c ${CPIO} > ${CPIO}.gz


我是copy recipes/linux-quic/linux-quic_git.bb裡面的do_deploy(),接著修改成另外一個script,來建立image,指令如下:
${SYSROOT}/x86_64-linux/usr/bin/mkbootimg --kernel ${SYSROOT}/mdm9640/boot/zImage-3.10.49 --dt ${SYSROOT}/mdm9640/boot/masterDTB --ramdisk ${CPIO}.gz --cmdline "dynamic_debug.verbose=1 root=/dev/ram rootfstype=ramfs console=ttyHSL0,115200,n8 androidboot.hardware=qcom ehci-hcd.park=3 msm_rtb.filter=0x37" --base 0x81C00000 --tags-addr 0x81900000 --pagesize 2048 --ramdisk_offset 0xd32000 --output ${OUTPUT}

這裡的重點是cmdline要改成"root=/dev/ram rootfstype=ramfs",否則在lk的lk/app/aboot/aboot.c:update_cmdline()會塞一些information給kernel,導致無法由initramfs開機。

相關檔案位置: https://www.codeaurora.org/cgit/quic/le/mdm/manifest/tree/?id=LNX.LE.5.0.1-57014-9x40
LNX.LE.5.0.1-57014-9x40.xml: repo manifest file,

https://www.codeaurora.org/cgit/quic/le/kernel/lk/tree/app/aboot/aboot.c?id=LNX.LE.5.0.1-57014-9x40
lk/app/aboot/aboot.c: unsigned char *update_cmdline(const char * cmdline)

https://www.codeaurora.org/cgit/quic/le/oe/recipes/tree/conf/machine/mdm9640.conf?h=LNX.LE.5.0.1_rb1.7
conf/machine/mdm9640.conf: MACHINE_KERNEL_TAGS_OFFSET = "0x81900000"

https://www.codeaurora.org/cgit/quic/le/oe/recipes/tree/recipes/linux-quic/linux-quic_git.bb?id=LNX.LE.5.0.1-57014-9x40
recipes/linux-quic/linux-quic_git.bb: do_deploy()



2015年6月20日 星期六

如何利用kvm/qemu練習linux module之new update


本文是如何利用kvm/qemu練習linux module的更新版。


brook@vista:~/qemu$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git linux
Cloning into 'linux'...
remote: Counting objects: 4153172, done.
remote: Compressing objects: 100% (548/548), done.
remote: Total 4153172 (delta 278), reused 0 (delta 0)
Receiving objects: 100% (4153172/4153172), 919.28 MiB | 2.32 MiB/s, done.
Resolving deltas: 100% (3423945/3423945), done.
Checking out files: 100% (49457/49457), done.
brook@vista:~/qemu$ cd linux/
brook@vista:~/qemu/linux$ git tag -l | tac | head -2
v4.1-rc8
v4.1-rc7
brook@vista:~/qemu/linux$ cp /boot/config-3.8.0-35-generic .config
brook@vista:~/qemu/linux$ make ARCH=i386 olddefconfig
  HOSTCC  scripts/basic/fixdep
  HOSTCC  scripts/kconfig/conf.o
  SHIPPED scripts/kconfig/zconf.tab.c
  SHIPPED scripts/kconfig/zconf.lex.c
  SHIPPED scripts/kconfig/zconf.hash.c
  HOSTCC  scripts/kconfig/zconf.tab.o
  HOSTLD  scripts/kconfig/conf
scripts/kconfig/conf  --olddefconfig Kconfig
.config:550:warning: symbol value 'm' invalid for ACPI_PCI_SLOT
.config:553:warning: symbol value 'm' invalid for ACPI_HOTPLUG_MEMORY
.config:665:warning: symbol value 'm' invalid for HOTPLUG_PCI_ACPI
.config:4522:warning: symbol value 'm' invalid for FB_VESA
.config:5062:warning: symbol value 'm' invalid for USB_ISP1760_HCD
.config:6150:warning: symbol value 'm' invalid for VME_BUS
#
# configuration written to .config
#
brook@vista:~/qemu/linux$ make ARCH=i386 all
scripts/kconfig/conf  --silentoldconfig Kconfig
  SYSTBL  arch/x86/syscalls/../include/generated/asm/syscalls_32.h
  SYSHDR  arch/x86/syscalls/../include/generated/uapi/asm/unistd_32.h
  SYSHDR  arch/x86/syscalls/../include/generated/uapi/asm/unistd_64.h
...(略)
  IHEX    firmware/yam/1200.bin
  IHEX    firmware/yam/9600.bin
brook@vista:~/qemu/linux$ cd ..
brook@vista:~/qemu$ git clone git://busybox.net/busybox.git
Cloning into 'busybox'...
remote: Counting objects: 91770, done.
remote: Compressing objects: 100% (23149/23149), done.
remote: Total 91770 (delta 71829), reused 86760 (delta 68061)
Receiving objects: 100% (91770/91770), 21.68 MiB | 805 KiB/s, done.
Resolving deltas: 100% (71829/71829), done.
brook@vista:~/qemu$ cd busybox
brook@vista:~/qemu/busybox$ make defconfig
scripts/kconfig/conf -d Config.in
*
* Busybox Configuration
...(略)
  Use the klogctl() interface (FEATURE_KLOGD_KLOGCTL) [Y/n/?] (NEW) y
logger (LOGGER) [Y/n/?] (NEW) y
brook@vista:~/qemu/busybox$ sed -i 's/.*CONFIG_STATIC.*/CONFIG_STATIC=y/' .config
brook@vista:~/qemu/busybox$ make CFLAGS="-m32" LDFLAGS="-m32" all
scripts/kconfig/conf -s Config.in
#
# using defaults found in .config
#
...(略)
  DOC     busybox.1
  DOC     BusyBox.html
brook@vista:~/qemu/busybox$ file busybox
busybox: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, for GNU/Linux 2.6.24, BuildID[sha1]=0x87675efbb7f7f810a462113cb2913bab73ffb1b6, stripped
brook@vista:~/qemu/busybox$ cd ..x
brook@vista:~/qemu$ ./create_initrd_by_linux_script.sh
+ INITD=initrd
+ rm -rf initrd
+ mkdir -p initrd/sbin initrd/bin initrd/sys initrd/tmp initrd/dev initrd/proc
+ mkdir -p initrd/usr/sbin initrd/usr/bin initrd/etc/init.d
+ install -m 0755 busybox/busybox initrd/bin
+ install -m 0755 init initrd/
+ ln -s ../bin/busybox initrd/sbin/mdev
+ ln -s busybox initrd/bin/sh
+ ln -s busybox initrd/bin/mkdir
+ ln -s busybox initrd/bin/mount
+ ./linux/scripts/gen_initramfs_list.sh -d initrd
+ ./linux/usr/gen_init_cpio /tmp/brook_initramfs_list
brook@vista:~/qemu$ qemu-system-i386 -kernel linux/arch/x86/boot/bzImage -initrd initrd.img


create_initrd_by_linux_script.sh

#!/bin/bash
INITD="initrd"
rm -rf ${INITD}
mkdir -p ${INITD}/sbin ${INITD}/bin ${INITD}/sys ${INITD}/tmp ${INITD}/dev ${INITD}/proc
mkdir -p ${INITD}/usr/sbin ${INITD}/usr/bin ${INITD}/etc/init.d
install -m 0755 busybox/busybox ${INITD}/bin
install -m 0755 init ${INITD}/
ln -s ../bin/busybox ${INITD}/sbin/mdev

ln -s busybox ${INITD}/bin/sh
ln -s busybox ${INITD}/bin/mkdir
ln -s busybox ${INITD}/bin/mount

./linux/scripts/gen_initramfs_list.sh -d ${INITD} > /tmp/brook_initramfs_list
./linux/usr/gen_init_cpio /tmp/brook_initramfs_list > initrd.img







2015年6月13日 星期六

apt-get update之更新non-LTS套件之解法


Ubuntu之非NON-LTS(Long Term Support)版本,通常9個月後就不再support,所以apt-get update更新往往就會看到找不到package的錯誤。 此時這些舊的package都會被移到http://old-releases.ubuntu.com/,所以要改一下路徑apt package的路徑。

brook@vista:~$ cat /etc/issue
Ubuntu 13.04 \n \l
 
brook@vista:~$ sudo apt-get update
[sudo] password for brook:
Ign http://extras.ubuntu.com raring Release.gpg
Ign http://archive.ubuntu.com raring Release.gpg
....
W: Failed to fetch http://security.ubuntu.com/ubuntu/dists/raring-security/main/binary-i386/Packages  404  Not Found [IP: 91.189.88.149 80]
 
W: Failed to fetch http://security.ubuntu.com/ubuntu/dists/raring-security/restricted/binary-i386/Packages  404  Not Found [IP: 91.189.88.149 80]
 
W: Failed to fetch http://security.ubuntu.com/ubuntu/dists/raring-security/universe/binary-i386/Packages  404  Not Found [IP: 91.189.88.149 80]
 
W: Failed to fetch http://security.ubuntu.com/ubuntu/dists/raring-security/multiverse/binary-i386/Packages  404  Not Found [IP: 91.189.88.149 80]
 
E: Some index files failed to download. They have been ignored, or old ones used instead.




Solution:

brook@vista:~$ cat /etc/apt/sources.list
#deb http://old-releases.ubuntu.com/ raring-security main
#deb http://old-releases.ubuntu.com/ubuntu/dists/raring-security/restricted/ raring-security main
deb http://old-releases.ubuntu.com/ubuntu/ raring main
deb http://old-releases.ubuntu.com/ubuntu/ raring universe


    參考資料:
  1. Ubuntu LTS(Long Term Support)
  2. Old Ubuntu Releases





2015年6月7日 星期日

LNK1123 error when bulding Visual Studio C++ 2010 project


今天忽然接到客戶指示要把NANE PIPE改成Socket,我就自告奮勇的協助,於是安裝完Visual Studio 2010後,第一個Hello World就出現了
LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt

於是google了半天後,終於在安裝完VS 2010 SP1後解了




2015年5月10日 星期日

Gerrit How-to


先建立SSH Key

利用ssh-keygen產生ssh key,為了方便,我的passphrase是空白,這樣git操作時就不用問密碼了
brook@vista:~$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/brook/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/brook/.ssh/id_ras.
Your public key has been saved in /home/brook/.ssh/id_ras.pub.
The key fingerprint is:
be:5a:86:da:2f:9f:b1:fb:97:f1:bc:bd:30:ba:2a:56 brook@vista
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|                 |
|                 |
|                 |
|        S        |
|       o E  .    |
|      . *    B   |
|     o.= =  + =. |
|    . +=O+o+. .oo|
+-----------------+
brook@vista:~$ cat /home/brook/.ssh/id_ras.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDcyqsKymOWqwb3OhfYWaFltoKZQnlbJqAEkSf1vPCOxKzZLvCQm+tOxnikTdDDY61qqr+GnitSDbiaBOLELRwg2LAa/MYATK52Di1VI6E9MRVknzdWureV5n10GGQ7zwL3kwXE6pnExwD6gm54hP9LzDM2/tsnLAcP+fvWyu53LCtaRmLC/0kCnAi57gl2d0Hpnp0Zaj/hOyy6DFoVYzBERC7zeem47OZ+NOQ77zd7l+HLujVL2DmS03iZ/e+I89dJIPWFoZbV6d9JlcVXnSkX/jC97HeBYYmELLLZ/vLk6PKNQ1axYgS0/xyodi1XwVTFOYfdk69HGKUOWfQ4B4sj brook@vista
brook@vista:~$

產生出來的Public Key就貼到Setting/SSH Public Keys中,如下圖



Create New Project

接下來就是建立一個新的Project,基本上只要點選Create New Project並填入名稱大致就完成了


接著我將Project的Submit Type設定為FF,因為我不太喜歡有很多merge的log存在

Clone/Push/Pull Project

基本上跟一般git操作沒兩樣,差在gerrit每個commit需要change-id,必須push到refs/for/branch_name等待review,這觀念可以參考下圖
brook@vista:~$ git clone ssh://brook@vista:29418/brook
Cloning into 'brook'...
The authenticity of host '[1.3.2.8]:29418 ([1.3.2.8]:29418)' can't be established.
RSA key fingerprint is cc:29:ae:12:64:ff:e0:19:9b:d1:e4:61:b1:63:4c:51.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[1.3.2.8]:29418' (RSA) to the list of known hosts.
remote: Counting objects: 2, done
remote: Finding sources: 100% (2/2)
remote: Total 2 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (2/2), done.
brook@vista:~$ cd brook/
brook@vista:~/brook$ git remote -v
origin  ssh://brook@1.3.2.8:29418/brook (fetch)
origin  ssh://brook@1.3.2.8:29418/brook (push)
brook@vista:~/brook$ git branch -a
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master
brook@vista:~/brook$ git log --stat
commit 79b2500f123690b50df8fa4e5fe9d4bf4459f4d9
Author: Brook Kuo <rene3210@gmail.com.tw>
Date:   Sat May 16 10:23:50 2015 +0800

    Initial empty repository
brook@vista:~/brook$ echo brook > myfile.txt
brook@vista:~/brook$ git add -f myfile.txt
brook@vista:~/brook$ git commit -m "brook 1st commit"
[master 7764665] brook 1st commit
 1 file changed, 1 insertion(+)
 create mode 100644 myfile.txt
brook@vista:~/brook$ git push origin HEAD:refs/for/master
Counting objects: 4, done.
Writing objects: 100% (3/3), 251 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
remote: Processing changes: refs: 1, done
remote: ERROR: missing Change-Id in commit message footer
remote:
remote: Hint: To automatically insert Change-Id, install the hook:
remote:   gitdir=$(git rev-parse --git-dir); scp -p -P 29418 brook@1.3.2.8:hooks/commit-msg ${gitdir}/hooks/
remote: And then amend the commit:
remote:   git commit --amend
remote:
To ssh://brook@1.3.2.8:29418/brook
 ! [remote rejected] HEAD -> refs/for/master (missing Change-Id in commit message footer)
error: failed to push some refs to 'ssh://brook@1.3.2.8:29418/brook'
brook@vista:~/brook$ gitdir=$(git rev-parse --git-dir); scp -p -P 29418 brook@1.3.2.8:hooks/commit-msg ${gitdir}/hooks/
commit-msg                                                                                 100% 4360     4.3KB/s   00:00
brook@vista:~/brook$ git commit --amend -m "brook 1st commit"
[master 994ca11] brook 1st commit
 1 file changed, 1 insertion(+)
 create mode 100644 myfile.txt
brook@vista:~/brook$ git log -1
commit 994ca118b141529f8b9ce4269a896c35b8730508
Author: Brook Kuo <rene3210@gmail.com.tw>
Date:   Sat May 16 11:09:11 2015 +0800

    brook 1st commit

    Change-Id: I9084cc25762e052527af98a335efb890c5ea3e89
brook@vista:~/brook$ git push origin HEAD:refs/for/master
Counting objects: 4, done.
Writing objects: 100% (3/3), 291 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
remote: Processing changes: new: 1, refs: 1, done
remote:
remote: New Changes:
remote:   http://1.3.2.8:6267/1 brook 1st commit
remote:
To ssh://brook@1.3.2.8:29418/brook
 * [new branch]      HEAD -> refs/for/master


圖來自https://review.openstack.org/Documentation/images/intro-quick-central-gerrit.png


Review and Submit


基本上Gerrit就是個網頁review system,直接網頁點選就可以完成review/submit等動作
Open頁面顯示待review之commit


點選+2,只有+2才能被submit


點選Submit,code才能真正被merge到project中


Merge頁面顯示被merge的commit





Install Simpleid


為了安裝Gerrit,於是就順便安裝了SimpleID來玩玩,順手寫一下,衝點文章數,安慰一下自己。
SimpleID is a simple, personal OpenID provider written in PHP.

什麼是OpenID?
我喜歡用這張圖來解說

來源: http://konstantin.beznosov.net/professional/archives/241

終端使用者(User)
        想要向某個網站表明身份的人。
標識(Identifier)
        終端使用者用以標識其身份的URL或XRI。
身份提供者(Identity Provider, IdP)
        提供OpenID URL或XRI註冊和驗證服務的服務提供者。
依賴方(Relying Party, RP)
        想要對終端使用者的標識進行驗證的網站。

User想要登入網站RP,而RP會提供OpenID的認證方式,於是就會有一個表單讓User填入Openid Identifier,如圖中的ecc.ubc.ca/alice,於是RP就會跟IdP進行認證,於是User只要輸入IdP上面的帳號密碼,IdP會向RP回報認證結果。

安裝SimpleID非常簡單,sudo apt-get install simpleid即可安裝完畢,接著copy /usr/share/simpleid/sample/example.identity.dist到/var/lib/simpleid/identities底下,並且更名為brook.identity,一定要以identity當附檔名,前面則是user name,接著編輯pass="password"這行,密碼可以透過php指令去generate,指令如下
brook@vista:/var/lib/simpleid/identities# php -a
Interactive shell

php > print md5('example password') . "\n";
ea07017619350413c8a0d604cffdbe50
php >
php > exit
將著就可以登入simpleid了,請輸入http://127.0.0.1/simpleid,輸入user帳號與剛剛設定的密碼即可登入。



比如當你要登入gerrit時,OpenID欄位表單就可以輸入http://your.ip/simpleid/,就可以透過SimpleID做認證了。


    參考資料:
  1. SimpleID 1 Documentation - Identity files
  2. WIKI, OpenID




2015年5月2日 星期六

Sendmail之SMART_HOST設定


話說Sendmail是大學時候看過的東西,對它還真是越來越陌生。

Smart Host是一種email message transfer agent,簡單來說就是一台中繼的Mail Server,凡是User要送出的信,並不會直接送給收件者的Mail Server,而是先送到該中繼點,再由Smart Host送給收件者的Mail Server,如下圖所示。


透過 sendmail 的sendmail.mc 設定,讓外寄的信都轉送到該SMART HOST(我的SMART HOST是1.1.1.3),為了避免外寄來的信都轉給該主機的User,必須加上FEATURE(stickyhost)。
所以請將以下兩行加入/etc/mail/sendmail.mc 中,建議用copy and paste,避免符號寫錯。
...
FEATURE(stickyhost)
define(`SMART_HOST', `relay.dnsexit.com') 
...

接著執行更新
# m4 sendmail.mc > sendmail.cf
# /etc/init.d/sendmail restart




接著利用mail這個指令,與/var/log/mail.log進行check與deubg。
brook@vista:~$ mail --debug-line-info --debug-level=30 rene3210@gmail.com -s "brook"
Cc:
in
sendmail.c:112: sendmail (/usr/sbin/sendmailn
mu_auth.c:255: Getting auth info for UID 1000
mu_auth.c:195: Trying generic...
mu_auth.c:198: generic yields 38=Function not implemented
mu_auth.c:195: Trying system...
mu_auth.c:198: system yields 0=Success
mu_auth.c:206: source=system, name=brook, passwd=x, uid=1000, gid=1000, gecos=BROOK,,,, dir=/home/brook, shell=/bin/bash, mailbox=/var/mail/brook, quota=0, change_uid=1
mu_auth.c:255: Getting auth info for UID 1000
mu_auth.c:195: Trying generic...
mu_auth.c:198: generic yields 38=Function not implemented
mu_auth.c:195: Trying system...
mu_auth.c:198: system yields 0=Success
mu_auth.c:206: source=system, name=brook, passwd=x, uid=1000, gid=1000, gecos=BROOK,,,, dir=/home/brook, shell=/bin/bash, mailbox=/var/mail/brook, quota=0, change_uid=1
mailer.c:454: mu_mailer_send_message(): using From: brook@vista
progmailer.c:188: Sending headers...
progmailer.c:221: Sending body...
progmailer.c:269: /usr/sbin/sendmail exited with: 0

brook@vista:~$ tail -f /var/log/mail.log
May  2 21:35:44 vista sendmail[383]: My unqualified host name (vista) unknown; sleeping for retry
May  2 21:36:44 vista sendmail[383]: unable to qualify my own domain name (vista) -- using short name
May  2 21:36:44 vista sendmail[383]: t42DaiZa000383: from=brook@vista, size=85, class=0, nrcpts=1, msgid=<201505021336.t42DaiZa000383@vista>, relay=brook@localhost
May  2 21:36:44 vista sm-mta[388]: t42DaiNp000388: from=<brook@vista>, size=364, class=0, nrcpts=1, msgid=<201505021336.t42DaiZa000383@vista>, proto=ESMTP, daemon=MTA-v4, relay=localhost [127.0.0.1]
May  2 21:36:44 vista sendmail[383]: t42DaiZa000383: to=<rene3210@gmail.com>, ctladdr=brook@vista (1000/1000), delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=30085, relay=[127.0.0.1] [127.0.0.1], dsn=2.0.0, stat=Sent (t42DaiNp000388 Message accepted for delivery)
May  2 21:36:45 vista sm-mta[390]: t42DaiNp000388: to=<rene3210@gmail.com>, ctladdr=<brook@vista> (1000/1000), delay=00:00:01, xdelay=00:00:01, mailer=relay, pri=120364, relay=[1.1.1.3] [1.1.1.3], dsn=2.0.0, stat=Sent (<201505021336.t42DaiZa000383@vista> [InternalId=109168394] Queued mail for delivery)



關於FEATURE(stickyhost)的說明
Beginning with V8.7 sendmail, addresses with and without a host part that resolve to local delivery are handled in the same way. For example, user and user@local.host are both looked up with the User Database (userdb on page 942) and processed by the localaddr rule set 5 (The localaddr Rule Set 5 on page 700). This processing can result in those addresses being forwarded to other machines.

user               ← not sticky
user@local.host    ← sticky


如果該Smart Host想要開放給其他Mail Server做relay用,請在/etc/mail/access做設定,如我要開放給jpr-Version-M4610這台機器做relay用,設定畫面如下。
接著執行
# makemap -v hash /etc/mail/access.db < /etc/mail/access
# /etc/init.d/sendmail restart


    參考資料:
  1. SMART_HOST, http://www.codemud.net/~thinker/GinGin_CGI.py/show_id_doc/237
  2. https://www.dnsexit.com/support/mailrelay/sendmail.html





2015年5月1日 星期五

安裝Gerrit


Gerrit,是一種以GIT作為底層的code review system,它使用網頁介面,讓團隊進行review,決定是否能夠提交,退回或是繼續修改。
可以由此download, https://gerrit-releases.storage.googleapis.com/index.html

安裝步驟可以參考裡面的Documentation,

1. 先建立database

我是採用mysql,其他db的設定可以參考Gerrit的Document。
  CREATE USER 'gerrit2'@'localhost' IDENTIFIED BY 'secret';
  CREATE DATABASE reviewdb;
  GRANT ALL ON reviewdb.* TO 'gerrit2'@'localhost';
  FLUSH PRIVILEGES;


2. Initialize the Site

基本上gerrit2會跳出對話框,將問題的資訊填完就可以安奘成功了。
gerrit2@vista:~$ ls
examples.desktop  gerrit-2.11.war
gerrit2@vista:~$ java -jar gerrit-2.11.war init -d review_site
Using secure store: com.google.gerrit.server.securestore.DefaultSecureStore

*** Gerrit Code Review 2.11
***

Create '/home/gerrit2/review_site' [Y/n]?

*** Git Repositories
***

Location of Git repositories   [git]:

*** SQL Database
***

Database server type           [h2]: mysql

Gerrit Code Review is not shipped with MySQL Connector/J 5.1.21
**  This library is required for your configuration. **
Download and install it now [Y/n]?
Downloading http://repo2.maven.org/maven2/mysql/mysql-connector-java/5.1.21/mysql-connector-java-5.1.21.jar ... OK
Checksum mysql-connector-java-5.1.21.jar OK
Server hostname                [localhost]:
Server port                    [(mysql default)]:
Database name                  [reviewdb]:
Database username              [gerrit2]:
gerrit2's password             :
              confirm password :

*** Index
***

Type                           [LUCENE/?]:

*** User Authentication
***

Authentication method          [OPENID/?]:

*** Review Labels
***

Install Verified label         [y/N]?

*** Email Delivery
***

SMTP server hostname           [localhost]:
SMTP server port               [(default)]:
SMTP encryption                [NONE/?]:
SMTP username                  :

*** Container Process
***

Run as                         [gerrit2]:
Java runtime                   [/usr/lib/jvm/java-7-openjdk-amd64/jre]:
Copy gerrit-2.11.war to /home/gerrit2/review_site/bin/gerrit.war [Y/n]?
Copying gerrit-2.11.war to /home/gerrit2/review_site/bin/gerrit.war

*** SSH Daemon
***


Listen on address              [*]:
Listen on port                 [29418]:

Gerrit Code Review is not shipped with Bouncy Castle Crypto SSL v151
  If available, Gerrit can take advantage of features
  in the library, but will also function without it.
Download and install it now [Y/n]?
Downloading http://www.bouncycastle.org/download/bcpkix-jdk15on-151.jar ... OK
Checksum bcpkix-jdk15on-151.jar OK

Gerrit Code Review is not shipped with Bouncy Castle Crypto Provider v151
** This library is required by Bouncy Castle Crypto SSL v151. **
Download and install it now [Y/n]?
Downloading http://www.bouncycastle.org/download/bcprov-jdk15on-151.jar ... OK
Checksum bcprov-jdk15on-151.jar OK
Generating SSH host key ... rsa... dsa... done

*** HTTP Daemon
***

Behind reverse proxy           [y/N]?
Use SSL (https://)             [y/N]?
Listen on address              [*]:
Listen on port                 [8080]: 6267
Canonical URL                  [http://localhost:6267/]:

*** Plugins
***

Installing plugins.
Install plugin download-commands version v2.11 [y/N]?
Install plugin reviewnotes version v2.11 [y/N]?
Install plugin singleusergroup version v2.11 [y/N]?
Install plugin replication version v2.11 [y/N]?
Install plugin commit-message-length-validator version v2.11 [y/N]?
Initializing plugins.
No plugins found with init steps.

Execute now [Y/n]?
Initialized /home/gerrit2/review_site
Executing /home/gerrit2/review_site/bin/gerrit.sh start
Starting Gerrit Code Review: OK
Waiting for server on localhost:6267 ... OK


3. Start/Stop Daemon


可以透過review_site/bin/gerrit.sh將deamon進行開關,通常我會在rc5.d中建立link到該script中
review_site/bin/gerrit.sh start
review_site/bin/gerrit.sh stop
review_site/bin/gerrit.sh restart


4. Setup Administrator

可以用Web開啟gerrit並且設定第一個User,即Adminstrator。

基本上我是自己建立一個OpenID,你可以選擇其他認證方式。








參考資料: Gerrit Document






2015年4月19日 星期日

Table Of Content for tag "tools"







2015年2月27日 星期五

OpenEmbedded User Manual - CH3, Writing Meta Data (Adding packages)


如同User manual提的,讓我們從寫package的description跟license開始,我們寫一個brook_1.0.bb開始

description

DESCRIPTION = "Brook's first application"
HOMEPAGE = "http://www.brook.com/oe/"
LICENSE = "Brook-Proprietary"
基本上這些參數都只是描述,也就是字串,至於LICENSE有公用哪些選項,請參考Recipe License Fields

define dependency

DEPENDS = "gtk+"
RDEPENDS = "cool-ttf-fonts"
DEPENDS是build時需要哪個package,RDEPENDS則是執行時需要哪個package,也就是說如果該brook_1.0被加到image,則RDEPENDS所列的也都會被加到image之中。

source location

SRC_URI = "http://127.0.0.1/brook/${P}.tar.bz2"
SRC_URI[md5sum] = "6abf52e3f874f67bc4663d0986493970"
SRC_URI[sha256sum] = "7aa5130f9648f0948ebaad270a4fe1112e4cc06895580dab85da26baa37fd4f6"
SRC_URI是指定檔案所在的位置,可以支援http、ftp、git、svn、file等,詳情可參考SRC_URI variable,SRC_URI[md5sum]與SRC_URI[sha256sum]是去驗證檔案是否正確,可以透過md5sum file_name與sha256sum file_name算出。當中的${P}=${PN}-${PV},${PN}是Package Name,${PV}是Package Version。

build system selection

在開始真正build package之前,我們必須決定這個package使用哪個build system,如果這個package需要先執行configure script然後在make,那麼通常就會選用autotools,更多關於autotools class,其他inherit之後再來討論。

到此可以真正開始build brook這個package了,bitbake brook

完整brook_1.0.bb

DESCRIPTION = "Brook's first application"
HOMEPAGE = "http://www.brook.com/oe/"
LICENSE = "Brook-Proprietary"
LIC_FILES_CHKSUM = "file://COPYING;md5=dcb2a5c2b6d6fea1a0835c08d71ad817"

SRC_URI = "http://127.0.0.1/brook/${P}.tar.bz2"
SRC_URI[md5sum] = "6abf52e3f874f67bc4663d0986493970"
SRC_URI[sha256sum] = "7aa5130f9648f0948ebaad270a4fe1112e4cc06895580dab85da26baa37fd4f6"
inherit autotools


Example of Source Code

brook-1.0/Makefile
all: brook

brook: main.o
 ${CC} $? -o $@
install:
 install -d -m 755 ${DESTDIR}/bin
 install -m 755 brook ${DESTDIR}/bin


brook-1.0/main.c
#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("Hello world, Brook\n");
    return 0;
}


    參考資料:
  1. OpenEmbedded User Manual
  2. OpenEmbedded - Style Guide
  3. OpenEmbedded - Recipe License Fields


LIC_FILES_CHKSUM does not match

如果出現以下錯誤
ERROR: brook: Recipe file does not have license file information (LIC_FILES_CHKSUM)
ERROR: Licensing Error: LIC_FILES_CHKSUM does not match, please fix
可以在bb file中加入
LIC_FILES_CHKSUM = "file://COPYING;md5=dcb2a5c2b6d6fea1a0835c08d71ad817"

其中COPYING就是LICENSE檔案位置,我是指到source file解開後的COPYING檔案位置與其對應的md5sum。


2015年2月7日 星期六

nc — arbitrary TCP and UDP connections and listens


幾乎任何使用 TCP,UDP或UNIX-domain socket的動作都可以用nc來達成,常見的功能如。
  • simple TCP proxies
  • shell-script based HTTP clients and servers
  • network daemon testing
  • a SOCKS or HTTP ProxyCommand for ssh(1)
  • and much, much more


SYNOPSIS
     nc [-46bCDdhklnrStUuvZz] [-I length] [-i interval] [-O length]
        [-P proxy_username] [-p source_port]
        [-q seconds] [-s source] [-T toskeyword] [-V rtable]
        [-w timeout] [-X proxy_protocol] [-x proxy_address[:port]]
        [destination] [port]


options: -v, verbose

不加-v,發生錯誤時不會有訊息。
brook@vista:~$ nc 127.0.0.1 12345
brook@vista:~$ nc -v 127.0.0.1 12345
nc: connect to 127.0.0.1 port 12345 (tcp) failed: Connection refused
brook@vista:~$ nc -v 127.0.0.1 80
Connection to 127.0.0.1 80 port [tcp/http] succeeded!
輸入GET / HTTP/1.1
輸入HOST: 127.0.0.1
輸入[enter]
輸入[enter]

HTTP/1.1 200 OK
Date: Tue, 27 Jan 2015 08:24:17 GMT
Server: Apache/2.2.22 (Ubuntu)
Last-Modified: Mon, 23 Dec 2013 04:13:45 GMT
ETag: "1b806ff-b1-4ee2bdaa24ac8"
Accept-Ranges: bytes
Content-Length: 177
Vary: Accept-Encoding
Content-Type: text/html
X-Pad: avoid browser bug

<html><body><h1>It works!</h1>
<p>This is the default web page for this server.</p>
<p>The web server software is running but no content has been added, yet.</p>
</body></html>


options: -l, listen for an incoming connection rather than initiate a connection to a remote host

等同開socket在listen,預設是tcp。
brook@vista:~$ nc -l 127.0.0.1 5000 -> server
brook@vista:~$ netstat -nal | grep 5000
tcp        0      0 127.0.0.1:5000          0.0.0.0:*               LISTEN
brook@vista:~$ nc 127.0.0.1 5000 -> client


options: -u, Use UDP instead of the default option of TCP.

使用UDP取代預設的TCP
brook@vista:~$ nc -lu 127.0.0.1 5000 -> server
brook@vista:~$ nc -u 127.0.0.1 5000 -> client


使用nc當Web Server

{ echo -ne "HTTP/1.0 200 OK\r\nContent-Length: $(wc -c < some.file)\r\n\r\n"; cat some.file; } | nc -l 5050
開啟Browser,http://127.0.0.1:5050/,就可以看到網頁了。

Works as a Port Scanner

brook@vista:~$ nc -v -z 127.0.0.1 80-200 2>&1 | grep -v failed
Connection to 127.0.0.1 80 port [tcp/http] succeeded!
Connection to 127.0.0.1 139 port [tcp/netbios-ssn] succeeded!


Transfering Files

sender
brook@vista:~$ md5sum usb_eth.txt
2367562f85f99fe972b9d6a83ce38099  usb_eth.txt
brook@vista:~$ tar cvf - usb_eth.txt | nc 127.0.0.1 5000
usb_eth.txt

receiver
brook@vista:/tmp$ nc -l 5000 | tar xvf -
usb_eth.txt
brook@vista:/tmp$ md5sum usb_eth.txt
2367562f85f99fe972b9d6a83ce38099  usb_eth.txt


Git Proxy

以下的Script是我拿用當gitproxy用的
#!/bin/bash
# http://tech-tacolin.blogspot.tw/2013/04/git-http-proxy.html
PROXY=1.2.3.4
PROXYPORT=3128
case $1 in
    192.168.1.1 | internal-ip)
        nc -X connect $*
        ;;
    *)
        nc -x $PROXY:$PROXYPORT -X connect $*
        ;;
esac


    參考資料
  1. Netcat WIKI
  2. Netcat(Linux nc 指令)網路管理者工具實用範例



2014年10月19日 星期日

od - dump files in octal and other formats


od(octal dump)主要是用來將資料轉成可讀的格式(human-readable formats),預設顯示格式如同名稱,顯示8進位資料,顯示格式包含8/10/16進位,以及ASCII顯示格式。
brook@vista:~$ echo abc| od
0000000 061141 005143
0000004
brook@vista:~$ echo abc| od -o
0000000 061141 005143
0000004
brook@vista:~$ echo abc| od -d
0000000 25185  2659
0000004
jpr@jpr-Veriton-M4610:~$ echo abc| od -h
0000000 6261 0a63
0000004
brook@vista:~$ echo abc| od -c
0000000   a   b   c  \n
0000004
brook@vista:~$ echo abc| od -b
0000000 141 142 143 012
0000004
brook@vista:~$ echo abc| od -i
0000000   174285409
0000004
jpr@jpr-Veriton-M4610:~$ echo abc| od -l
0000000            174285409
0000004
brook@vista:~$ echo abc| od -s
0000000  25185   2659
0000004
brook@vista:~$ echo abc| od -x
0000000 6261 0a63
0000004

"a"的ascii值為,8/10/16進位值為97/61/141,所以有看到沒有參數和"-o"顯示一樣的內容,061141的10/16進位值為25185/H6261,看得出是一次顯示兩個byte,-b則是顯示一個byte,-h/-x一次顯示兩個byte的16進位,-d和-s一樣一次顯示兩個byte的10進位。
再來下面的例子是顯示address/offset的格式"-A",可以搭配"oxnd",o是8進位,d是10進位,d是16進位,n是不顯示address/offset。
brook@vista:~$ od -Ad sleep.sh
0000000  1647255843  1932488297  1752631912   543517801
0000016  1920213083  1562404213  1868827195  1819478282
0000032   544236901  1695091249   544172131  1701606183
0000048   824209509   660825459  1852793866   168442725
0000064
brook@vista:~$ od -Ao sleep.sh
0000000  1647255843  1932488297  1752631912   543517801
0000020  1920213083  1562404213  1868827195  1819478282
0000040   544236901  1695091249   544172131  1701606183
0000060   824209509   660825459  1852793866   168442725
0000100
brook@vista:~$ od -Ax sleep.sh
000000  1647255843  1932488297  1752631912   543517801
000010  1920213083  1562404213  1868827195  1819478282
000020   544236901  1695091249   544172131  1701606183
000030   824209509   660825459  1852793866   168442725
000040
brook@vista:~$ od -An sleep.sh
  1647255843  1932488297  1752631912   543517801
  1920213083  1562404213  1868827195  1819478282
   544236901  1695091249   544172131  1701606183
   824209509   660825459  1852793866   168442725

其餘參數包含"-N"讀幾個byte,與"-j"offset幾個byte,"-t"輸出格式顯示方式,"-t"可以搭配dfoux,後面再搭配數字,以一次幾個byte顯示。如
brook@vista:~$ od -An -N6 -t x1 sleep.sh
 23 21 2f 62 69 6e
brook@vista:~$ od -An -N6 -t x2 sleep.sh
 2123 622f 6e69
brook@vista:~$ od -An -N6 -t x4 sleep.sh
 622f2123 00006e69


我常拿od來產生random MAC,
brook@vista:~$ od -An -N6 -t x1 sleep.sh | tr ' ' ':' | cut -d':' -f2-7
23:21:2f:62:69:6e




2014年7月6日 星期日

[轉載]Linux中tty、pty、pts的概念區別


轉自 http://www.wretch.cc/blog/redsonoma/14021073

基本概念:

1> tty(終端設備的統稱):
tty一詞源於Teletypes,或者teletypewriters,原來指的是電傳打字機,是通過串行線用打印機鍵盤通過閱讀和發送信息的東西,後來這東西被鍵盤與顯示器取代,所以現在叫終端比較合適。
終端是一種字符型設備,它有多種類型,通常使用tty來簡稱各種類型的終端設備。


2> pty(虛擬終端):
但是如果我們遠程telnet到主機或使用xterm時不也需要一個終端交互麼?是的,這就是虛擬終端pty(pseudo-tty)


3> pts/ptmx(pts/ptmx結合使用,進而實現pty):
pts(pseudo-terminal slave)是pty的實現方法,與ptmx(pseudo-terminal master)配合使用實現pty。

Linux終端:

在Linux系統的設備特殊文件目錄/dev/下,終端特殊設備文件一般有以下幾種:
1、串行端口終端(/dev/ttySn)
串行端口終端(Serial Port Terminal)是使用計算機串行端口連接的終端設備。計算機把每個串行端口都看作是一個字符設備。有段時間這些串行端口設備通常被稱為終端設備,因為 那時它的最大用途就是用來連接終端。這些串行端口所對應的設備名稱是/dev/tts/0(或/dev/ttyS0), /dev/tts/1(或/dev/ttyS1)等,設備號分別是(4,0), (4,1)等,分別對應於DOS系統下的COM1、COM2等。若要向一個端口發送資料,可以在命令行上把標準輸出重定向到這些特殊文件名上即可。例如, 在命令行提示符下鍵入:echo test > /dev/ttyS1會把單詞」test」發送到連接在ttyS1(COM2)端口的設備上。可接串口來實驗。

2、偽終端(/dev/pty/)
偽終端(Pseudo Terminal)是成對的邏輯終端設備(即master和slave設備, 對master的操作會反映到slave上)。
例如/dev/ptyp3和/dev/ttyp3(或者在設備文件系統中分別是/dev/pty/m3和 /dev/pty/s3)。它們與實際物理設備並不直接相關。如果一個程序把ptyp3(master設備)看作是一個串行端口設備,則它對該端口的讀/ 寫操作會反映在該邏輯終端設備對應的另一個ttyp3(slave設備)上面。而ttyp3則是另一個程序用於讀寫操作的邏輯設備。

這樣,兩個程序就可以通過這種邏輯設備進行互相交流,而其中一個使用ttyp3的程序則認為自己正在與一個串行端口進行通信。這很像是邏輯設備對之間的管 道操作。對於ttyp3(s3),任何設計成使用一個串行端口設備的程序都可以使用該邏輯設備。但對於使用ptyp3的程序,則需要專門設計來使用 ptyp3(m3)邏輯設備。

例如,如果某人在網上使用telnet程序連接到你的計算機上,則telnet程序就可能會開始連接到設備 ptyp2(m2)上(一個偽終端端口上)。此時一個getty程序就應該運行在對應的ttyp2(s2)端口上。當telnet從遠端獲取了一個字符 時,該字符就會通過m2、s2傳遞給 getty程序,而getty程序就會通過s2、m2和telnet程序往網絡上返回」login:」字符串信息。這樣,登錄程序與telnet程序就通 過「偽終端」進行通信。通過使用適當的軟件,就可以把兩個甚至多個偽終端設備連接到同一個物理串行端口上。

在使用設備文件系統 (device filesystem)之前,為了得到大量的偽終端設備特殊文件,使用了比較複雜的文件名命名方式。因為只存在16個ttyp(ttyp0—ttypf) 的設備文件,為了得到更多的邏輯設備對,就使用了象q、r、s等字符來代替p。例如,ttys8和ptys8就是一個偽終端設備對。不過這種命名方式目前 仍然在RedHat等Linux系統中使用著。

但Linux系統上的Unix98並不使用上述方法,而使用了」pty master」方式,例如/dev/ptm3。它的對應端則會被自動地創建成/dev/pts/3。這樣就可以在需要時提供一個pty偽終端。目錄 /dev/pts是一個類型為devpts的文件系統,並且可以在被加載文件系統列表中看到。雖然「文件」/dev/pts/3看上去是設備文件系統中的 一項,但其實它完全是一種不同的文件系統。
即: TELNET ---> TTYP3(S3: slave) ---> PTYP3(M3: master) ---> GETTY
=========================================================================
實驗:
1、在X下打開一個或N個終端窗口
2、#ls /dev/pt*
3、關閉這個X下的終端窗口,再次運行;比較兩次輸出信息就明白了。
在RHEL4環境下: 輸出為/dev/ptmx /dev/pts/1存在一(master)對多(slave)的情況
=========================================================================


3、控制終端(/dev/tty)
如果當前程序有控制終端(Controlling Terminal)的話,那麼/dev/tty就是當前程序的控制終端的設備特殊文件。可以使用命令」ps –ax」來查看程序與哪個控制終端相連。對於你登錄的shell,/dev/tty就是你使用的終端,設備號是(5,0)。使用命令」tty」可以查看它 具體對應哪個實際終端設備。/dev/tty有些類似於到實際所使用終端設備的一個聯接。


4、控制台終端(/dev/ttyn, /dev/console)
在Linux 系統中,計算機顯示器通常被稱為控制台終端 (Console)。它仿真了類型為Linux的一種終端(TERM=Linux),並且有一些設備特殊文件與之相關聯:tty0、tty1、tty2 等。當你在控制台上登錄時,使用的是tty1。使用Alt+[F1—F6]組合鍵時,我們就可以切換到tty2、tty3等上面去。tty1–tty6等 稱為虛擬終端,而tty0則是當前所使用虛擬終端的一個別名,系統所產生的信息會發送到該終端上(這時也叫控制台終端)。因此不管當前正在使用哪個虛擬終 端,系統信息都會發送到控制台終端上。你可以登錄到不同的虛擬終端上去,因而可以讓系統同時有幾個不同的會話期存在。只有系統或超級用戶root可以向 /dev/tty0進行寫操作 即下例:
1、# tty(查看當前TTY)
/dev/tty1
2、#echo "test tty0" > /dev/tty0
test tty0


5 虛擬終端(/dev/pts/n)
在Xwindows模式下的偽終端.


6 其它類型
Linux系統中還針對很多不同的字符設備存在有很多其它種類的終端設備特殊文件。例如針對ISDN設備的/dev/ttyIn終端設備等。這裡不再贅述。


FAQ: 終端和控制台

Q:/dev/console 是什麼?

A:/dev/console即控制台,是與操作系統交互的設備,系統將一些信息直接輸出到控制台上。目前只有在單用戶模式下,才允許用戶登錄控制台。


Q:/dev/tty是什麼?

A:tty設備包括虛擬控制台,串口以及偽終端設備。
/dev/tty代表當前tty設備,在當前的終端中輸入 echo 「hello」 > /dev/tty ,都會直接顯示在當前的終端中。


Q:/dev/ttyS*是什麼?

A:/dev/ttyS*是串行終端設備。


Q:/dev/pty*是什麼?

A:/dev/pty*即偽終端,所謂偽終端是邏輯上的終端設備,多用於模擬終端程序。例如,我們在X Window下打開的終端,以及我們在Windows使用telnet 或ssh等方式登錄Linux主機,此時均在使用pty設備(準確的說在使用pty從設備)。

Q:/dev/tty0與/dev/tty1 …/dev/tty63是什麼?它們之間有什麼區別?

A:/dev/tty0代表當前虛擬控制台,而/dev/tty1等代表第一個虛擬控制台,例如當使用ALT+F2進行切換時,系統的虛擬控制台為/dev/tty2 ,當前的控制台則指向/dev/tty2

Q:如何確定當前所在的終端(或控制台)?

A:使用tty命令可以確定當前的終端或者控制台。

Q:/dev/console是到/dev/tty0的符號鏈接嗎?

A: 目前的大多數文本中都稱/dev/console是到/dev/tty0的鏈接(包括《Linux內核原始碼情景分析》),但是這樣說是不確切的。根據內 核文檔,在2.1.71之前,/dev/console根據不同系統的設定可以鏈接到/dev/tty0或者其他tty*上,在2.1.71版本之後則完 全由內核控制。目前,只有在單用戶模式下可以登錄/dev/console(可以在單用戶模式下輸入tty命令進行確認)。

Q:/dev/tty0與/dev/fb*有什麼區別?

A: 在Framebuffer設備沒有啟用的系統中,可以使用/dev/tty0訪問顯卡。

Q:關於終端和控制台的區別可以參考哪些文本

A: 可以參考內核文檔中的 Documents/devices.txt 中關於」TERMINAL DEVICES」的章節。另外,《Linux內核原始碼情景分析》的8.7節 以及《Operating Systems : Design and Implementation》中的3.9節(第3版中為3.8節)都對終端設備的概念和歷史做了很好的介紹。另外在《Modern Operating system》中也有對終端設備的介紹,由於與《Operating Systems : Design and Implementation》的作者相同,所以文本內容也大致相同。需要注意的一點是《Operating Systems : Design and Implementation》中將終端設備分為3類,而《Modern Operating system》將終端硬體設備分為2類,差別在於前者將 X Terminal作為一個類別。

PS:

只有2410的2.6才叫ttySAC0,9200等的還是叫ttyS0





vim - statusline


status line會在vim底下有一個視窗,用以顯示狀態,透過laststatus=0關閉status line,或laststatus=2永遠開啟status line。透過statusline設定要顯示那些東西,以及如何顯示,基本上就是"%"加上修飾字(vim的document稱為item),如%F會顯示含路徑檔案名稱,%f顯示不含路徑檔案名稱,其他一般文字會被直接顯示,如set statusline=%l/%L,就會顯示"目前所在行數/全部行數",如8/50之類的字眼。而空白要用"\"escape。

有幾個特別的修飾字(item),如"*"是設定highlight group,根據group number設定前景與背景顏色,如
set statusline=%2*%F
hi User2 ctermfg=3  ctermbg=0
會將%F(顯示含路徑檔案名稱)顯示前景為黃色的字體。


修飾字(item)"<"則會截去過長的字串。修飾字(item)"="會把status分成左右兩部分,即靠左靠右對齊。其餘的翻翻document吧。


以下是我常用的vim設定,

set statusline=
set statusline+=%1*\[%n]                                  "buffernr
set statusline+=%2*\ %<%F\                                "File+path
set statusline+=%3*\ %=\ %{''.(&fenc!=''?&fenc:&enc).''}\ "Encoding
set statusline+=%4*\ %{(&bomb?\",BOM\":\"\")}\            "Encoding2
set statusline+=%5*\ %{&ff}\                              "FileFormat (dos/unix..)
set statusline+=%6*\ row:%l/%L\ col:%03c\ (%03p%%)\             "Rownumber/total (%)
set statusline+=%0*\ \ %m%r%w\ %P\ \                      "Modified? Readonly? Top/bot.
hi User2 ctermfg=3  ctermbg=0
hi User6 ctermfg=3  ctermbg=4
set laststatus=2




參考資料
  1. vim document - statusline, http://vimdoc.sourceforge.net/htmldoc/options.html#'statusline'
  2. vim document - status-line, http://vimdoc.sourceforge.net/htmldoc/windows.html#status-line
  3. Learn Vimscript the Hard Way, Status Lines





2014年6月15日 星期日

git - push to non-bare repository


如果push到non-bare的repository,則會被reject,必須將該repository的receive.denyCurrentBranch設為ignore

brook@vista:~/x2$ git push origin HEAD
Counting objects: 3, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (2/2), 227 bytes, done.
Total 2 (delta 0), reused 0 (delta 0)
remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require 'git reset --hard' to match
remote: error: the work tree to HEAD.
remote: error:
remote: error: You can set 'receive.denyCurrentBranch' configuration variable t
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing int
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in some
remote: error: other way.
remote: error:
remote: error: To squelch this message and still keep the default behaviour, see
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.
To /home/brook/x
 ! [remote rejected] HEAD -> master (branch is currently checked out)
error: failed to push some refs to '/home/brook/x'

編輯該repoistory底下的.git/config
[receive]
    denyCurrentBranch = ignore


相關文章:
git筆記





2013年9月28日 星期六

RFC 5969 - IPv6 Rapid Deployment on IPv4 Infrastructures (6rd) -- Protocol Specification之筆記


Abstract

描述6rd prefix + IPv4 address的方式定址的優點,如automatic IPv6 prefix delegation to site, statless operation, simple provisioning and service等等。


Introduction

6rd機制成功的被商業化,被詳細記錄在RFC 5569。6rd是基於6to4改善而來,主要差異是在IPv6 Prefix的部分,6to4是用2002::/16,6rd是SP(service provider)自訂的prefix。6to4也可以被視為是6rd的subset,因為如果6rd的prefix是2002::/16就是6to4了。


Terminology

6rd prefix 被SP用來給6rd domain的IPv6 prefix。SP可以布署一個以上的6rd domain。
6rd CE (Customer Edge) 在6rd的布置中擔任CPE(Customer Premises Equipment)的角色或稱RG (Residential Gateway)。典型的CE有一個WAN site interface和一個以上的LAN interface,LAN端也稱為Customer-facing。提供IP6能力,WAN端也稱SP-facing。
6rd delegated prefix 由CE計算給Customer site端使用的IPv6 Prefix。
6rd domain 使用相同的virtual 6rd link的CEs和BRs的集合。SP可以有一個以上的6rd doamin。每個6rd domain必須使用不同的6rd prefix。
6rd Border Relay 被佈署在6rd domain的edge位置。IPv4-enabled interface用於6rd的IPv6 in IPv4 tunnel端。IPv6 interface用於連接IPv6網路。
BR IPv4 address 6rd Border Relay的IPv4 address。
6rd virtual interface encapsulation and decapsulation of IPv6 packets inside IPv4。


6rd Prefix Delegation

6rd delegated prefix是利用6rd prefix和CE的IPv4計算出來,用於customer site。如圖一:
當IPv4 address在6rd domain可以被aggregate,如10.0.0.0/8,則不使用全部的IPv4來計算,因為前面8bit可以被aggregate,所以使用後面24bit(即o bit為24)。
6rd不限於使用public IP,但如果private address會overlap,就應該被切成不同的6rd domain(使用不同的6rd prefix, 可以確保唯一性)。
即使相同的SP,也可能使用不同的IPv4 bit數,比如10.0.0.0/8和192.168.0.1/16之間的差異就可能會使用不同的IPv4MaskLen。
6rd delegated prefix是使用IPv4計算,所以IPv4 address的變動,也會影響6rd delegated prefix,因此建議以IPv4 address的lease time當成prefix的lifetime。


6rd Configuration

6rd有四個重要的configured value:
IPv4MaskLen ignore最高的幾個bit,比如IPv4 address range是10.0.0./8,那麼IPv4MaskLen就是8,使用後面24bit來計算6rd delegated prefix。
6rdPrefix 6rd IPv6 prefix
6rdPrefixLen 6rd IPv6 prefix length.
6rdBRIPv4Address 6rd Border Relay的IPv4 address.


Customer Edge Configuration
這四個configured value可透過TR-69,PPP或手動方式設定,這份RFC使用DHCP方式取得參數。

6rd DHCPv4 Option

6rdBRIPv4Address允許一個以上,不過OPTION_6RD只能限制最多只有一個6rd domain,不支援多個6rd domain。當6rd被啟動, CE會設定default route到BR,比如CE IP: 10.100.100.1/8, BR IP: 10.0.0.1, 6rdPrefix: 201:db8/32,那麼CE的routing table會是這樣:
     ::/0 -> 6rd-virtual-int0 via 2001:db8:0:100:: (default route)
     2001:db8::/32 -> 6rd-virtual-int0 (direct connect to 6rd)
     2001:db8:6464:100::/56 -> Null0 (delegated prefix null route)
     2001:db8:6464:100::/64 -> Ethernet0 (LAN interface)

Border Relay Configuration
BR的位址可以利用anycast address達到loading baalancing和reliability.


IPv6 in IPv4 Encapsulation

IPv6的Traffic class field必須被複製到IPv4的Tos欄位(可以參考RFC 4213/3056/2983/3168等)。

Maximum Transmission Unit
6rd的MTU應該被設成CE WAN side的MTU - 20 bytes(IPv4 header),如果IPv4 MTU是1500,那麼6rd Tunnel MTU應該被設成1500-20=1480。如果缺乏資訊,6rd MTU應該被設成1280。

Receiving Rules
為了防止spoofing攻擊,6rd的BR和CE應該根據6rd domain的參數,驗證6rd Tunnel的IPv4 address和IPv6 address的IPv4部分是否相符,不符合就drop。


IPv6 Address Space Usage

基本上就是6rd prefix length和IPv4MaskLen的取捨,如果要給user的6rd delegated prefix是 /60,而IPv4MaskLen是24(根據IPv4 aggregate的程度),那麼6rdPrefixLen就要給60-24=36。



    參考資料:
  1. RFC 5969 - IPv6 Rapid Deployment on IPv4 Infrastructures (6rd) -- Protocol Specification




2013年9月21日 星期六

RFC 5569 - IPv6 Rapid Deployment on IPv4 Infrastructures (6rd)之筆記


Abstract

6rd是建立在6to4的機制上,提供ISP快速布建IPv6網路的機制,
和6to4相似處:
  statless IPv6(IPv6 prefix + IPv4 address information),並且將IPv6封裝在IPv4上在IPv4-only網路上傳送。
和6to4不同處:
  6to4使用2002::/16的prefix,而6rd使用ISP給的prefix。


Introduction

描述Free這間ISP成功的使用6rd快速布建IPv6網路(5周),而且低成本,變動少。


Problem Statement and Purpose of 6rd

ISP/Customer/Application之間的死結,影響IPv6布置的速度。
ISP等待Customer有需求才會想布置IPv6,而客戶只有當應程式需要IPv6才會想用IPv6,應用程式卻因為沒有IPv6所以在NAT底下繼續奮鬥。
ISPs wait for customer demand before deploying IPv6; customers don't demand IPv6 as long as application vendors announce that their products work on existing infrastructures (that are IPv4 with NATs); application vendors focus their investments on NAT traversal compatibility as long as ISPs don't deploy IPv6.

Problem
6to4的routing問題,6to4的IPv6 address是由IPv4算出來的,如:ISP給你10.1.1.1,你的6to4 address就是2001:0a01:0101::,另外一個ISP也給他的client相同的IPv4 Addresss,而他也使用了6to4,routing就出問題了。這個問題的癥結點就是相同的prefix,如果由ISP各自給合法的Prefix,就沒這問題了。因為即使是NAT,各自的Prefix還是會不同,IPv6 address仍可保證唯一。


Specification

6rd relay server的IPv4 anycast address可以由ISP自行決定,通常會避免掉192.88.99.1這個6to4專用address。

圖中說明,6rd CPE會負責將IPv6的packet封裝在IPv4裡面,並且往6rd relay server傳送,之後就可以送到IPv6的Network去,反過來,目的地是ISP的IPv6 prefix就會經由6RD relay server送到6rd CPE去。

    參考資料:
  1. 6to4 and 6rd
  2. RFC 5569 - IPv6 Rapid Deployment on IPv4 Infrastructures (6rd)





2013年9月14日 星期六

融券現償


102/09/04券賣國泰金$42.35,保證金38,200。
102/09/12現償國泰金$43.25,應退$42.35,因為已經賣在42.35。
102/09/13收到$38200 + $42350 - 費用(60+127+33) + 利息(3) = 80333。

年/月/日 股票別 股數 單價 價金 手續費 交易稅 淨付額 擔保品 融資金額 融券保證金 借券費
102/09/04
券賣
2882
國泰金
1,000 42.35 42,350 60 127 38,200 0 42,130 38,200 33

金額詳細算法:
保證金:成交價金x 保證金成數(90%)
42350 x 0.9 = 38115

借卷費:又稱融券手續費,成交價金x融券手續費率(0.08%)
42350 x 0.0008 = 33.88

賣出手續費:成交價金 x 賣出手續費率(0.1425% X 折扣)
42350 x 0.001425 = 60.35

證交稅:成交價金x證交稅率(0.3%)
42350 x 0.003 = 127.05

融卷放空可向券商收取利息,
利息=(擔保品價金+保證金) x 融卷利率(0.2%) x 融資券計息天數/365
(38200 + 42350) x 0.002 x 8 / 365 = 3.531


    參考資料:
  1. 券商優惠列表(含融資劵利率)




2013年9月7日 星期六

DHCPv6-PD


DHCPv6 Prefix Delegation (DHCPv6-PD)定義在RFC 3633,是DHCPv6的extension (option)。主要是用來和DHCPv6-PD server要求prefix給DHCPv6-PD client其他的interface。

Network layout如下:


Server端是Windows,使用dibber,設定檔如下(server.conf):
# Logging level range: 1(Emergency)-8(Debug)
log-level 8

# Don't log full date
log-mode short

iface "區域連線 35"
{

# clients should renew every half an hour
 T1 1800

# In case of troubles, after 45 minutes, ask any server
 T2 2700

# Addresses should be prefered for an hour
 prefered-lifetime 3600

# and should be valid for 2 hours
 valid-lifetime 7200
 
 class {
   pool 5000:1234::/48
 }

 # the following lines instruct server to grant each client
 # 1 or 2 prefixes (if you have uncommented second line with pd-pool or not). 
 # For example, client might get
 # 2222:2222:2222:222:2222:993f:6485:0/112 and 
 # 1111:1111:1111:1111:1111::993f:6485:0/112
 pd-class {
        pd-pool 2222:2222:1234::/48
        pd-length 48
        T1 11111
        T2 22222
    }
 
}


pd-pool 2222:2222:1234::/48
DHCPv6-PD server管理的prefix為2222:2222:1234::/48

pd-length 48
切割單位為48,等於全部發送出去。如果pd-length 56,則會切分2^(56-48) = 256個單位分發。也就是client會收到Prefix length = 56,Prefix Address = 2222:2222:1234:xx00::的訊息。


Client端是Linux,使用wide-dhcpv6,設定檔如下(/tmp/dhcp6c.conf):
interface br0 {
   send ia-pd 1;
};

id-assoc pd 1 {
    prefix-interface usb0 {
        sla-id 2;
    };
    prefix-interface usb1 {
        sla-id 3;
    };
};


send ia-pd 1:
送出id為1的pd請求

sla-len:
這裡省略了sla-len,sla-len的設定原則如下:
64 - (The length of the delegation you are getting)
如Server的pd-length為48,那麼這邊的sla-len就要設16,不過可以省略不設。

sla-id 0:
設定prefix id,範圍為0 ~ 2^sla-len,如 sla-len = 8,那麼範圍就是0~255。


執行結果
root@lte-iad:/ramdisk/tmp# ifconfig usb0
usb0      Link encap:Ethernet  HWaddr 11:22:33:E0:E3:B9
          inet6 addr: fe80::1122:33ff:fee0:e3b9/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:20 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX byt.s:RX1920 (1.8 KiB)

root@lte-iad:/ramdisk/tmp# ifconfig usb1
usb1      Link encap:Ethernet  HWaddr 11:22:33:07:16:C7
          inet6 addr: fe80::1122:33ff:fe07:16c7/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:18 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:1700 (1.6 KiB)

root@lte-iad:/ramdisk/tmp# ifconfig br0
br0       Link encap:Ethernet  HWaddr 11:22:33:97:F0:E6
          inet6 addr: fe80::1122:33ff:fe97:f0e6/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:630 errors:0 dropped:0 overruns:0 frame:0
          TX packets:14577 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:75873 (74.0 KiB)  TX bytes:10922a79 (1.0 MiB)

root@lte-iad:/ramdisk/tmp# dhcp6c -c /tmp/dhcp6c.conf br0
Line: 418 *** family: 10, socktype: 1, protocol: 17, flags: 1, (sockaddr) address: ::, address len: 28 ***
Line: 502 *** family: 10, socktype: 1, protocol: 17, flags: 0, (sockaddr) addres,s: ff02::1:2, address len: 28 ***

root@lte-iad:/ramdisk/tmp# ifconfig usb0
usb0      Link encap:Ethernet  HWaddr 11:22:33:E0:E3:B9
          inet6 addr: 2222:2222:1234:2:1122:33ff:fee0:e3b9/64 Scope:Global
          inet6 addr: fe80::1122:33ff:fee0:e3b9/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:51 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:5090 (4.9 KiB)

root@lte-iad:/ramdisk/tmp# ifconfig usb1
usb1      Link encap:Ethernet  HWaddr 11:22:33:07:16:C7
          inet6 addr: 2222:2222:1234:3:1122:33ff:fe07:16c7/64 Scope:Global
          inet6 addr: fe80::1122:33ff:fe07:16c7/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:50 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:4928 (4.8 KiB)

root@lte-iad:/ramdisk/tmp# ifconfig br0
br0       Link encap:Ethernet  HWaddr 11:22:33:97:F0:E6
          inet6 addr: fe80::1122:33ff:fe97:f0e6/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1086 errors:0 dropped:0 overruns:0 frame:0
          TX packets:30600 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:134671 (131.5 KiB)  TX bytes:2324630 (2.2 MiB)







2013年8月4日 星期日

RFC 4862 - IPv6 Stateless Address Autoconfiguration之筆記


1. Introduction


這份文件主要是在規範如何自動組態(autoconfigure)host的interface的IPv6 address,以及DAD(Duplicate Address Detection)驗證address的唯一性程序。
自動組態(autoconfigure)一詞有時候也稱為無狀態自動組態(stateless autoconfigure),也僅用於host,router則不在此RFC範圍內,而之所以稱為stateless autoconfigure是因為相較於statefull DHCPv6而言,網路上並沒有像DHCP server一樣的機器記錄address使用情況,所以稱為stateless。
"autoconfigure" = "prefix" + "interface ID",router會發出RA(Router Advertisement),RA通常會攜帶Prefix information,Host收到就會根據此Prefix information再加上"interface ID"組出IPv6 address。


IPv6 address有幾個狀態,當開始autoconfigure到DAD完成前,address是不能被指定到interface的,此時稱為tentative,當唯一性確認,並指定到interface開始到Preferred Lifetime結束前稱為"preferred",之後到Valid Lifetime結束前稱為"Deprecated",Valid Lifetime結束後就稱為Invalid。
如圖:



2. Terminology


tentative address、preferred address、deprecated address、invalid address分別被標是在上圖(IPv6 Address status)綠色線(time)以上的部分。preferred lifetime、valid lifetime則是分別被標示在綠色線(time)以下的部分。



3. Design Goals

  1. 不需要手動設定address
  2. 在Small sites底下沒有DHCPv6或router也能透過Link-local address進行通訊。
  3. 在large sites底下沒有DHCPv6也能透過Router的RA進行address的configuration。
  4. 有renumbering的能力,透過lifetimes達成此目標。



4. Protocol Overview


Autoconfiguration只有在multicast-capable的link上執行,而且當該interface被enable就開始執行link-local的部分,這樣就能符合設計目標之一"在Small sites底下沒有DHCPv6或router也能透過Link-local address進行通訊"。
Autoconfiguration的處理程序
  1. tentative link-local address自動產生,此時為tentative狀態。
  2. 執行DAD(Duplicate Address Detection),送出NS(Neighbor Solicitation)。
  3. DAD成功(隔一段時間沒有收到Neighbor Advertisement),將該address指定給該interface,相關的solicited-node multicast link-layer address也會被註冊到interface中。
    DAD失敗,需要手動設定IPv6 Address。



5. Protocol Specification


5.5.3 Router Advertisement Processing
  • 如果Autonomous flag沒被設定,忽略該Prefix Information。
  • 如果Prefix是Link-Local prefix,忽略該Prefix Information。
  • 如果Preferred lifetime大於Valid lifetime,忽略該Prefix Information。



Note
RFC 2464 - Transmission of IPv6 Packets over Ethernet Networks
    4. Stateless Autoconfiguration
        An IPv6 address prefix used for stateless autoconfiguration 
        of an Ethernet interface must have a length of 64 bits.



在XP上顯示IPv6 Address


在XP中可以使用指令"ipv6"操作IPv6相關設定,也可以使用netsh指令來操作。
以下圖是顯示IPv6的information:

其中第二條紅線, 是因為privacy為enable,XP自動產生位置。
第三條紅線, 則是根據網卡資訊,自動產生,後面的時間為 valid time / preferred time,因為preffered還大於0,所以這個Address處於preffered狀態(顯示於最前面的preferred)。
第四行紅線,則是會根據指定的IPv6 address,會註冊相對應的Solicited-node multicast address。


    參考資料:
  1. RFC 4862
  2. IPv6 Address Autoconfiguration
  3. RFC 2462 IPv6 Stateless Address Autoconfiguration




熱門文章