vivi与Linux kernel的参数传递情景分析(上)

在上一部分提到过了,vivi作为bootloader,向内核传递启动参数是其本职工作之一。要把这个情景分析清楚,不仅仅需要分析vivi的参数机制,而且要分析Linux kernel的接收机制。因为这是一个简单的通信过程,比起本科所学习的TCP/IP来简单的多,但是因为简单,所以在协议上并不规范,理解上反而不如TCP/IP协议。下面就分为两个方面对此情景分析。

 
一、综述内核参数传递机制
 
    现在内核参数传递机制有两种:一种是基于struct param_struct,这种已经比较老了。缺点是该结构每个成员的位置是固定的,受限比较大。另外一种就是新的struct tag way。说新是相对的,Linux kernel 2.4.x都希望采用这种tag的方式。关于这方面的资料,可以有如下参考(所给出的目录是基于linux-2.4.18的内核,以顶层Makefile所在目录为当前目录。这里基于ARM架构的S3C2410,其他的SoC可以类比很容易得到):
 
1、关于bootloader的理解--【Documentation/arm/booting】
 
    此文档详细的讲述了bootloader的作用,具体内容如下:
 

[armlinux@lqm arm]$ cat Booting
                        Booting ARM Linux
                        =================

Author: Russell King
Date : 18 May 2002

The following documentation is relevant to 2.4.18-rmk6 and beyond.

In order to boot ARM Linux, you require a boot loader, which is a small
program that runs before the main kernel. The boot loader is expected
to initialise various devices, and eventually call the Linux kernel,
passing information to the kernel.

Essentially, the boot loader should provide (as a minimum) the
following:

1. Setup and initialise the RAM.
2. Initialise one serial port.
3. Detect the machine type.
4. Setup the kernel tagged list.
5. Call the kernel image.


1. Setup and initialise RAM
---------------------------

Existing boot loaders: MANDATORY
New boot loaders: MANDATORY

The boot loader is expected to find and initialise all RAM that the
kernel will use for volatile data storage in the system. It performs
this in a machine dependent manner. (It may use internal algorithms
to automatically locate and size all RAM, or it may use knowledge of
the RAM in the machine, or any other method the boot loader designer
sees fit.)


2. Initialise one serial port
-----------------------------

Existing boot loaders: OPTIONAL, RECOMMENDED
New boot loaders: OPTIONAL, RECOMMENDED

The boot loader should initialise and enable one serial port on the
target. This allows the kernel serial driver to automatically detect
which serial port it should use for the kernel console (generally
used for debugging purposes, or communication with the target.)

As an alternative, the boot loader can pass the relevant 'console='
option to the kernel via the tagged lists specifing the port, and
serial format options as described in

       linux/Documentation/kernel-parameters.txt.


3. Detect the machine type
--------------------------

Existing boot loaders: OPTIONAL
New boot loaders: MANDATORY

The boot loader should detect the machine type its running on by some
method. Whether this is a hard coded value or some algorithm that
looks at the connected hardware is beyond the scope of this document.
The boot loader must ultimately be able to provide a MACH_TYPE_xxx
value to the kernel. (see linux/arch/arm/tools/mach-types).


4. Setup the kernel tagged list
-------------------------------

Existing boot loaders: OPTIONAL, HIGHLY RECOMMENDED
New boot loaders: MANDATORY

The boot loader must create and initialise the kernel tagged list.
A valid tagged list starts with ATAG_CORE and ends with ATAG_NONE.
The ATAG_CORE tag may or may not be empty. An empty ATAG_CORE tag
has the size field set to '2' (0x00000002). The ATAG_NONE must set
the size field to zero.

Any number of tags can be placed in the list. It is undefined
whether a repeated tag appends to the information carried by the
previous tag, or whether it replaces the information in its
entirety; some tags behave as the former, others the latter.

The boot loader must pass at a minimum the size and location of
the system memory, and root filesystem location. Therefore, the
minimum tagged list should look:

        +-----------+
base -> | ATAG_CORE | |
        +-----------+ |
        | ATAG_MEM | | increasing address
        +-----------+ |
        | ATAG_NONE | |
        +-----------+ v

The tagged list should be stored in system RAM.

The tagged list must be placed in a region of memory where neither
the kernel decompressor nor initrd 'bootp' program will overwrite
it. The recommended placement is in the first 16KiB of RAM.

5. Calling the kernel image
---------------------------

Existing boot loaders: MANDATORY
New boot loaders: MANDATORY

There are two options for calling the kernel zImage. If the zImage
is stored in flash, and is linked correctly to be run from flash,
then it is legal for the boot loader to call the zImage in flash
directly.

The zImage may also be placed in system RAM (at any location) and
called there. Note that the kernel uses 16K of RAM below the image
to store page tables. The recommended placement is 32KiB into RAM.

In either case, the following conditions must be met:

- CPU register settings
  r0 = 0,
  r1 = machine type number discovered in (3) above.
  r2 = physical address of tagged list in system RAM.

- CPU mode
  All forms of interrupts must be disabled (IRQs and FIQs)
  The CPU must be in SVC mode. (A special exception exists for Angel)

- Caches, MMUs
  The MMU must be off.
  Instruction cache may be on or off.
  Data cache must be off.

- The boot loader is expected to call the kernel image by jumping
  directly to the first instruction of the kernel image.

 
    可以看出bootloader最少具备5项功能,上面比较清晰。可以看出,现在2.4的内核都是希望采用tagged list的方式来进行传递的,这里没有提到比较老的方式。这里要特别注意的是,r2 = physical address of tagged list in system RAM.,这里的“必须”是针对于tagged list而言的,如果采用param_struct,则并没有这个限制。这在后面将会详细分析,而这正是可能导致疑惑的地方。
 r2是内存中由bootloader传递过来的参数列表的起始地址,一般存放在0x30000100处,但是不是必须的,因为在内核中并没有利用r2传递过去的地址来获取参数列表,而是利用宏来填充某个结构体获取到的参数列表的地址。
2、参数传递数据结构的定义位置【include/asm/setup.h】,在这里就可以看到两种参数传递方式了。可以说,现在bootloader和Linux kernel约定的参数传递机制就是这两种,必须严格按照这两种机制进行传输,否则的话,kernel可能因为无法识别bootloader传递过来的参数而导致无法启动。关于这两种方式,在这里还有说明:
 

/*
 * linux/include/asm/setup.h
 *
 * Copyright (C) 1997-1999 Russell King
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 * Structure passed to kernel to tell it about the
 * hardware it's running on. See linux/Documentation/arm/Setup
 * for more info.
 *
 * NOTE:
 * This file contains two ways to pass information from the boot
 * loader to the kernel. The old struct param_struct is deprecated,
 * but it will be kept in the kernel for 5 years from now
 * (2001).
This will allow boot loaders to convert to the new struct
 * tag way.
 */

 
    这说明,现在参数传递必须要采用tag方式,因为现在新的kernel已经不支持param_struct方式了。不幸的是,vivi还是采用的param_struct方式。这里暂时以param_struct为主分析,考虑以后更新为tag方式。在这里你也可以参考【Documentation/arm/setup】,里面有关于选项具体含义的详细说明。(在这里多说几句。Linux的Documentation是一个很好的学习库,几乎所有的问题在这里都能有初步的解答。如果要想继续深入,那么就要读源代码了。学习上,先看README,然后翻阅Documentation,无疑是一条捷径。而且,是否有完备的文档,也是判断这个软件是否优秀的重要标准。)
 
二、vivi设置Linux参数分析
 
    上面对bootloader与Linux kernel之间参数传递的两种方式已经有了一个总体的理解。下面就来先看vivi部分如何设置Linux参数。
 
【init/main.c】boot_or_vivi()-->run_autoboot()-->exec_string("boot")
 先来看看exec_string函数的执行(lib/command.c):
void exec_string(char *buf)
{
 int argc;
 char *argv[128];//用来存放解析出来的多个命令
 char *resid;
 while (*buf) {
  memset(argv, 0, sizeof(argv));
  parseargs(buf, &argc, argv, &resid);//因为有可能buf传递过来的命令行中包括多条命令,所以需要将每条命令都解析出来然后存放到argv数组中
  if (argc > 0)
   execcmd(argc, (const char **)argv);//解析之后就开始执行argv中存放的命令,这里argv里面只有一条命令,就是boot
  buf = resid;
 }
}
继续来看看execcmd函数的执行(lib/command.c)
void execcmd(int argc, const char **argv)
{
 user_command_t *cmd = find_cmd(argv[0]);//在user_command_t列表中找到boot命令的结构体,
 if (cmd == NULL) {
  printk("Could not found '%s' command/n", argv[0]);
  printk("If you want to konw available commands, type 'help'/n");
  return;
 }
 /*printk("execcmd: cmd=%s, argc=%d/n", argv[0], argc);*/
 cmd->cmdfunc(argc, argv);找到后然后执行boot对应的user_command_t结构体中对应的命令函数,可以看看boot命令对应的该结构体:
}
(lib/boot_kernel.c)
user_command_t boot_cmd = {
 "boot",
 command_boot,//可以看到上面到了最后就是要执行command_boot函数
 NULL,
 "boot [{cmds}] /t/t/t-- Booting linux kernel"
};
    到此,也就是要执行boot命令。与命令相关部分都在【lib/command.c】中,找到boot_cmd,然后跟踪至【lib/boot_kernel.c】,boot的执行行为函数为command_boot(),继续分析:
 
【lib/boot_kernel.c】command_boot()-->
 
主要就是三步工作。
 
    · 获取media_type。
 

media_type = get_param_value("media_type", &ret);

 
    media_type是重要的,因为对于不同的存储介质,底层的驱动函数是不同的。通过media_type这个顶层抽象,实现了与底层驱动的联系。
 

[armlinux@lqm include]$ cat boot_kernel.h
#ifndef _VIVI_BOOT_KERNEL_H_
#define _VIVI_BOOT_KERNEL_H_

/*
 * Media Type: A type of storage device that contains the linux kernel
 *
 * +----------------+-----------------------------------------+
 * | Value(Integer) | Type |
 * +----------------+-----------------------------------------+
 * | 0 | UNKNOWN |
 * | 1 | RAM |
 * | 2 | NOR Flash Memory |
 * | 3 | SMC (NAND Flash Memory) on the S3C2410 |
 * +----------------+-----------------------------------------+
 */

enum {
        MT_UNKNOWN = 0,
        MT_RAM,
        MT_NOR_FLASH,
        MT_SMC_S3C2410
};

#endif /* _VIVI_BOOT_KERNEL_H_ */

 
    上面就是vivi支持的media_type,现在此开发板是MT_SMC_S3C2410,也就是nand flash memory的选择部分。
 
    ·获取nand flash的kernel分区信息,为下载做好准备(一般会将nandflash分为几个不同的区分别用来存放boot,params,kernel,root),这里获取到kernel在nandflash中位于哪个分区,则可以获取到内核在nandflash上的地址
 

kernel_part = get_mtd_partition("kernel");
                        if (kernel_part == NULL) {
                                printk("Can't find default 'kernel' partition/n");
                                return;
                        }
                        from = kernel_part->offset;
                        size = kernel_part->size;

 
    这里获得了kernel所在nand flash的起始地址和大小。这里应该注意,虽然kernel_part->offset是偏移量,但是这个偏移是相对于0x00000000而言,所以这时的offset就是对应的起始地址。当然,对nand flash来说,这里的地址并非是内存映射,需要做一系列的变化,具体是在nand_read_ll函数中,前面的基本实验已经做过了。
 
    ·启动内核
 

boot_kernel(from, size, media_type);

 
    利用前面得到的media_type,from,size就可以来启动内核了,在boot_kernel中当然还有多步工作要去做。具体包括如下内容:
 
(1)获取内存基地址
 

boot_mem_base = get_param_value("boot_mem_base", &ret);

 
    在vivi中,sdram是从0x30000000开始的,所以这里的boot_mem_base就是0x30000000.
 
(2)把kernel映象从nand flash复制到sdram的固定位置
 

    to = boot_mem_base + LINUX_KERNEL_OFFSET;
    printk("Copy linux kernel from 0x%08lx to 0x%08lx, size = 0x%08lx ... ",
        from, to, size);
    ret = copy_kernel_img(to, (char *)from, size, media_type);

 
   我们可以看看是如何将kernel从nandflash中拷贝到内存中来的:
static inline int copy_kernel_img(ulong dst, const char *src, size_t size, int mt)
{
 int ret = 0;
 switch (mt) {//根据获取得到的media类型来做不同方式的拷贝
  case MT_RAM: 
   /* noting to do */
   break;
  case MT_NOR_FLASH://如果kernel存放在NOR上,则直接利用memcpy进行互拷
   memcpy((char *)dst, (src + FLASH_UNCACHED_BASE), size);
   break;
  case MT_SMC_S3C2410:
#ifdef CONFIG_S3C2410_NAND_BOOT
   ret = nand_read_ll((unsigned char *)dst,
        (unsigned long)src, (int)size);
#endif
   break;
  case MT_UNKNOWN:
  default:
   printk("Undefined media type./n");
   return -1;
 }
 return ret;
}
 这里LINUX_KERNEL_OFFSET是0x8000,关于为什么是0x8000,这是历史原因造成的,是Linux内核的一个约定,具体可以查看Linux内核的源代码中的arch/arm/kernel/head_armv.S,如下:
 

/*
 * We place the page tables 16K below TEXTADDR. Therefore, we must make sure
 * that TEXTADDR is correctly set. Currently, we expect the least significant
 * "short" to be 0x8000
, but we could probably relax this restriction to
 * TEXTADDR > PAGE_OFFSET + 0x4000
 *
 * Note that swapper_pg_dir is the virtual address of the page tables, and
 * pgtbl gives us a position-independent reference to these tables. We can
 * do this because stext == TEXTADDR
 *
 * swapper_pg_dir, pgtbl and krnladr are all closely related.
 */

 
    可以看出,TEXTADDR就是stext的地址,本开发板上为0x30008000,在0x30008000往下,会放置16K的页表,预计是0x8000.不过此处可能会放松这个限制。另外,我们的一些参数也会放到内存起始区域。这在后面就可以看到。总之,这个地方的位置boot_mem_base也就是kernel的第一条指令所在地,最后的程序跳转要跳到这个位置。
 
(3)验证magic number
 

    if (*(ulong *)(to + 9*4) != LINUX_ZIMAGE_MAGIC) {
        printk("Warning: this binary is not compressed linux kernel image/n");
        printk("zImage magic = 0x%08lx/n", *(ulong *)(to + 9*4));
    } else {
        printk("zImage magic = 0x%08lx/n", *(ulong *)(to + 9*4));
    }

 
    这个地方是判断是否有zImage的存在,而zImage的判别的magic number为0x016f2818,这个也是和内核约定好的。你可以用ultra-edit32查看一下zImage,这是我的zImage的头的部分内容(注意,为小端存放格式):
 
00000000h: 00 00 A0 E1 00 00 A0 E1 00 00 A0 E1 00 00 A0 E1
00000010h: 00 00 A0 E1 00 00 A0 E1 00 00 A0 E1 00 00 A0 E1
00000020h: 02 00 00 EA 18 28 6f 01 00 00 00 00 DB 86 09 00
 
    至于为什么magic number在0x00000024这个位置,需要分析zImage是如何生成的,它的内容是什么,起始的几个字节是什么,这部分内容放到Linux kernel端进行深入分析。不过在这里应该提一句,此处的验证是考虑到Linux kernel相对比较大,而嵌入式系统的资源受限,为了节省资源,一般会将Linux kernel来压缩成zImage格式(识别方式就是在第9个字后有magic number0x016f2818);但是应该明确,这步工作并非是必需的。因为如果内核比较小,为了加快启动速度,我可以不使用压缩的映象,直接采用非压缩映象,那么vivi此处应该把无法找到maigc number的提示更改为printk("this binary is not compressed linux kernel image/n");。就Linux kernel来说,启动中支持压缩映象和非压缩映象两种启动方式,不管是那种启动方式,第一条指令的地址总是boot_mem_base,只不过放在这里的指令并非一定是真正的kernel启动指令。这个在后面会详细分析Linux kernel启动方式。
 
(4)设置Linux参数
 

setup_linux_param(boot_mem_base + LINUX_PARAM_OFFSET);

 
    现在看一下setup_linux_param的具体动作。
 

static void setup_linux_param(ulong param_base)
{
    struct param_struct *params = (struct param_struct *)param_base;
    char *linux_cmd;

    //第一步:打印出param_base的基地址,这里就是0x30000100

    //这里的这个位置实际上是约定的,预留了256字节

    //然后初始化param_struct这个数据结构
    printk("Setup linux parameters at 0x%08lx/n", param_base);
    memset(params, 0, sizeof(struct param_struct));

    //填写params的两个成员

    //Linux kernel采用了页表方式,设置页的大小,这里是4K
    params->u1.s.page_size = LINUX_PAGE_SIZE;//这里是内核中定义的每一个页的大小
    params->u1.s.nr_pages = (DRAM_SIZE >> LINUX_PAGE_SHIFT);//而这里则是要计算整个内存有多少个页,一夜大小为4K,所以需要将整个内存大小向右移动12位。


    /* set linux command line */
    linux_cmd = get_linux_cmd_line();这个地方的command line是uboot中传递过来的  还是在配置内核中设置的?
    if (linux_cmd == NULL) {
        printk("Wrong magic: could not found linux command line/n");
    } else {

        //把命令行参数复制到params的commandline成员
        memcpy(params->commandline, linux_cmd, strlen(linux_cmd) + 1);
        printk("linux command line is: /"%s/"/n", linux_cmd);
    }
}

 

   
    如上,把不相关部分去掉了,加了注释。可以看出,这里就设置了param_struct必需的三个成员,核心是commandline。关于param_struct在linux内核的【include/arm/setup.h】中,各个成员的含义是:
 

/*
 * Usage:
 * - do not go blindly adding fields, add them at the end
 * - when adding fields, don't rely on the address until
 * a patch from me has been released
 * - unused fields should be zero (for future expansion)
 * - this structure is relatively short-lived - only
 * guaranteed to contain useful data in setup_arch()
 */

#define COMMAND_LINE_SIZE 1024

/* This is the old deprecated way to pass parameters to the kernel */
struct param_struct {
    union {
        struct {
            unsigned long page_size; /* 0 */
            unsigned long nr_pages; /* 4 */
            unsigned long ramdisk_size; /* 8 */
            unsigned long flags; /* 12 */
#define FLAG_READONLY 1
#define FLAG_RDLOAD 4
#define FLAG_RDPROMPT 8
            unsigned long rootdev; /* 16 */
            unsigned long video_num_cols; /* 20 */
            unsigned long video_num_rows; /* 24 */
            unsigned long video_x; /* 28 */
            unsigned long video_y; /* 32 */
            unsigned long memc_control_reg; /* 36 */
            unsigned char sounddefault; /* 40 */
            unsigned char adfsdrives; /* 41 */
            unsigned char bytes_per_char_h; /* 42 */
            unsigned char bytes_per_char_v; /* 43 */
            unsigned long pages_in_bank[4]; /* 44 */
            unsigned long pages_in_vram; /* 60 */
            unsigned long initrd_start; /* 64 */
            unsigned long initrd_size; /* 68 */
            unsigned long rd_start; /* 72 */
            unsigned long system_rev; /* 76 */
            unsigned long system_serial_low; /* 80 */
            unsigned long system_serial_high; /* 84 */
            unsigned long mem_fclk_21285; /* 88 */
        } s;
        char unused[256];
    } u1;
    union {
        char paths[8][128];
        struct {
            unsigned long magic;
            char n[1024 - sizeof(unsigned long)];
        } s;
    } u2;
    char commandline[COMMAND_LINE_SIZE];
};

 
    如上,具体选项的含义,可以参考【Documentation/arm/setup】,这里仅就用到的三个来进行解释。
 

page_size

   This parameter must be set to the page size of the machine, and
   will be checked by the kernel.

 nr_pages

   This is the total number of pages of memory in the system. If
   the memory is banked, then this should contain the total number
   of pages in the system.

   If the system contains separate VRAM, this value should not
   include this information.
 commandline

   Kernel command line parameters. Details can be found elsewhere.

 
    可以看出,这步的设置工作还是非常简单的。现在使用的页大小为4K,也就是page_size的值。因为现在使用的sdram是64M,总页表项自然就是64M/page_size,也就是进行简单的右移就可以了(4K等效右移12位)。后面就是获取命令行参数的地址,然后填充comandline成员,最长的限度为1024.
 
    至此,vivi设置参数就完成了,约定参数的起始地址为boot_mem_base+0x0100处。这个地方是否需要作为参数传递给kernel,就需要与内核配合了。如果像Linux kernel约定的boot_mem_base+0x8000处存放内核映象一样,Linux kernel对s3c2410的支持同样可以约定参数固定存放于boot_mem_base+0x0100。如果没有此约定,那么就需要传递参数首地址了。
 
(5)获取机器号
 

mach_type = get_param_value("mach_type", &ret);

 
    这个号是固定的。可以参考arch/arm/tools/mach-types。这里列出了所有支持的机器号。应该是按照先后的支持顺序排列。可以看到smdk2410为:
 

smdk2410        S3C2410_SMDK        SMDK2410        193

 
(6)启动内核
 

call_linux(0, mach_type, to);

 
    到这里才算是真正启动内核了,使用内嵌汇编写的。这里的三个参数,根据APCS原则,应该分别给R0,R1, R2.这样也就是说,现在:
 
    · R0 设置为0
    · R1 machine type number(193)
    · R2 内核的第一条指令的起始地址(注意,这里并非参数表的首地址)
 

void call_linux(long a0, long a1, long a2)
{
    cache_clean_invalidate();
    tlb_invalidate();

__asm__(
    "mov    r0, %0/n"
    "mov    r1, %1/n"
    "mov    r2, %2/n"
    "mov    ip, #0/n"
    "mcr    p15, 0, ip, c13, c0, 0/n"    /* zero PID */
    "mcr    p15, 0, ip, c7, c7, 0/n"    /* invalidate I,D caches */
    "mcr    p15, 0, ip, c7, c10, 4/n"    /* drain write buffer */
    "mcr    p15, 0, ip, c8, c7, 0/n"    /* invalidate I,D TLBs */
    "mrc    p15, 0, ip, c1, c0, 0/n"    /* get control register */
    "bic    ip, ip, #0x0001/n"        /* disable MMU */
    "mcr    p15, 0, ip, c1, c0, 0/n"    /* write control register */
    "mov    pc, r2/n"
    "nop/n"
    "nop/n"
    : /* no outpus */
    : "r" (a0), "r" (a1), "r" (a2)
    );

}

 
    汇编很简洁。参考前面booting文档,就是做上述工作。现在对R0、R1、R2参数传递完成,不过R2在这里并非tag的首地址,因为采用的是param_struct模式,所以可以猜测kernel的arch(实际上就是HAL层)肯定有对应的默认地址起始地址(这里是0x30000100)。其余部分,中断都关闭了,PID为0,I cache和D cache都禁止,write buffer清理,I D TLBS也禁止,禁止MMU。最后mov pc, r2则跳转到内核映象的第一条指令位置。
 
    到这里,vivi的使命完全完成了!后续的工作就交给kernel了。
 
    为了对参数传递这个情景分析清楚,所以还必须分析Linux kernel如何启动。这部分不打算过多的深入细节,首先应该从整体上分析。然而,还是应该借助代码才能理解的更为清晰。这里,有taoyuetao的Linux启动分析系列文章可以参考,我想,他分析Linux启动也是如同我分析vivi一样,一步一步走过来的。借鉴一下,省去了我不少劳动,在此感谢。后续的描述中Linux kernel启动部分借鉴taoyuetao的经验,但是对其进行了扩展,增加了zImage如何生成的更为详细的解释。
展开阅读全文

没有更多推荐了,返回首页