[转]关于uboot的main_loop

http://www.linuxidc.com/Linux/2011-12/49044.htm

http://blog.chinaunix.net/uid-23670869-id-2391643.html

 

//

1。main_loop

common/main.c
 
 
 
main_loop又臭又长,去掉宏注释掉的部分就只剩下一点点了。如下:
 
 
 
void main_loop (void)
{
#ifndef CONFIG_SYS_HUSH_PARSER
    static char lastcommand[CONFIG_SYS_CBSIZE] = { 0, };
    int len;
    int rc = 1;
    int flag;
#endif

#if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
    char *s;
    int bootdelay;
#endif

#ifdef CONFIG_AUTO_COMPLETE
    install_auto_complete();  //安装自动补全的函数,分析如下 。
#endif

#if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
    s = getenv ("bootdelay");
    bootdelay = s ? (int)simple_strtol(s, NULL, 10) : CONFIG_BOOTDELAY;

    debug ("### main_loop entered: bootdelay=%d/n/n", bootdelay);


        s = getenv ("bootcmd"); //获取引导命令。分析见下面。

    debug ("### main_loop: bootcmd=/"%s/"/n", s ? s : "<UNDEFINED>");

    if (bootdelay >= 0 && s && !abortboot (bootdelay)) {//如果延时大于等于零,并且没有在延时过程中接收到按键,则引导内核。abortboot函数的分析见下面。
        run_command (s, 0);            //运行引导内核的命令。这个命令是在配置头文件中定义的。run_command的分析在下面。
    }

#endif    /* CONFIG_BOOTDELAY */

    for (;;) {
        len = readline (CONFIG_SYS_PROMPT); //CONFIG_SYS_PROMPT的意思是回显字符,一般是“>”。这是由配置头文件定义的

        flag = 0;    /* assume no special flags for now */
        if (len > 0)
            strcpy (lastcommand, console_buffer); //保存输入的数据。
        else if (len == 0)
            flag |= CMD_FLAG_REPEAT;//如果输入数据为零,则重复执行上次的命令,如果上次输入的是一个命令的话

        if (len == -1)
            puts ("<INTERRUPT>/n");
        else
            rc = run_command (lastcommand, flag); //执行命令

        if (rc <= 0) {//执行失败,则清空记录
            /* invalid command or not repeatable, forget it */
            lastcommand[0] = 0;
        }
    }

}


2。自动补全
common/common.c
int var_complete(int argc, char *argv[], char last_char, int maxv, char *cmdv[])
{
    static char tmp_buf[512];
    int space;

    space = last_char == '/0' || last_char == ' ' || last_char == '/t';

    if (space && argc == 1)
        return env_complete("", maxv, cmdv, sizeof(tmp_buf), tmp_buf);

    if (!space && argc == 2)
        return env_complete(argv[1], maxv, cmdv, sizeof(tmp_buf), tmp_buf);

    return 0;
}

static void install_auto_complete_handler(const char *cmd,
        int (*complete)(int argc, char *argv[], char last_char, int maxv, char *cmdv[]))
{
    cmd_tbl_t *cmdtp;

    cmdtp = find_cmd(cmd);
    if (cmdtp == NULL)
        return;

    cmdtp->complete = complete; //命令结构体的complete指针指向传入的函数。
}

void install_auto_complete(void)
{
#if defined(CONFIG_CMD_EDITENV)
    install_auto_complete_handler("editenv", var_complete);
#endif
    install_auto_complete_handler("printenv", var_complete);
    install_auto_complete_handler("setenv", var_complete);
#if defined(CONFIG_CMD_RUN)
    install_auto_complete_handler("run", var_complete);
#endif
}

可以看到将editenv、printenv、setenv和run的自动补全函数安装为 var_complete。
 var_complete的功能是根据给出的前缀字符串,找出所有前缀相同的命令。

每个命令在内存中用一个cmd_tbl_t 表示。
include/command.h
struct cmd_tbl_s {
    char        *name;        /* 命令名,输入的就是它            */
    int        maxargs;    /* 最大参数个数    */
    int        repeatable;    /* 允许自动重发,也就是在按下空格键之后执行最后一条命令。        */
                   
    int        (*cmd)(struct cmd_tbl_s *, int, int, char *[]); /* 实现命令的参数 */
    char        *usage;        /* 短的提示信息    */
#ifdef    CONFIG_SYS_LONGHELP
    char        *help;        /* 详细的帮助信息。    */
#endif
#ifdef CONFIG_AUTO_COMPLETE
    /* do auto completion on the arguments */
    int        (*complete)(int argc, char *argv[], char last_char, int maxv, char *cmdv[]);
#endif
};

typedef struct cmd_tbl_s    cmd_tbl_t;

extern cmd_tbl_t  __u_boot_cmd_start;
extern cmd_tbl_t  __u_boot_cmd_end;

#define U_BOOT_CMD(name,maxargs,rep,cmd,usage,help) /
cmd_tbl_t __u_boot_cmd_##name Struct_Section = {#name, maxargs, rep, cmd, usage, help}

#define U_BOOT_CMD_MKENT(name,maxargs,rep,cmd,usage,help) /
{#name, maxargs, rep, cmd, usage, help}

uboot中的命令使用U_BOOT_CMD这个宏声明来注册进系统,链接脚本会把所有的cmd_tbl_t结构体放在相邻的地方。
链接脚本中的一些内容如下:
. = .;
 __u_boot_cmd_start = .;
 .u_boot_cmd : { *(.u_boot_cmd) }
 __u_boot_cmd_end = .;
可见,__u_boot_cmd_start 和__u_boot_cmd_end 分别对应命令结构体在内存中开始和结束的地址。

3。abortboot函数的分析
abortboot是uboot在引导期间的延时函数。期间可以按键进入uboot的命令行。
common/main.c
static __inline__ int abortboot(int bootdelay)
{
    int abort = 0;
    printf("Hit any key to stop autoboot: %2d ", bootdelay);

#if defined CONFIG_ZERO_BOOTDELAY_CHECK   //如果定义了这个宏,即使定义延时为0,也会检查一次是否有按键按下。只要在这里执行之前按键,还是能进入uboot的命令行。
    if (bootdelay >= 0) {
        if (tstc()) {    /* we got a key press    */ 测试是否有按键按下
            (void) getc();  /* consume input    */接收按键值
            puts ("/b/b/b 0");
            abort = 1;    /* don't auto boot    */修改标记,停止自动引导
        }
    }
#endif

    while ((bootdelay > 0) && (!abort)) { //如果延时大于零并且停止标记没有赋值则进入延时循环,直到延时完或者接收到了按 键
        int i;

        --bootdelay;
        /* delay 100 * 10ms */ 每秒中测试按键100次,之后延时10ms。
        for (i=0; !abort && i<100; ++i) {
            if (tstc()) {    /* we got a key press    */
                abort  = 1;    /* don't auto boot    */*/修改标记,停止自动引导
                bootdelay = 0;    /* no more delay    */延时归零
                (void) getc();  /* consume input    */获取按键
                break;
            }
            udelay(10000);//延时10000us,也就是10ms
        }

        printf("/b/b/b%2d ", bootdelay);//打印当前剩余时间
    }

    putc('/n');
    return abort;//返回结果:1-停止引导,进入命令行; 0-引导内核。
}

可以看到uboot延时的单位是秒,如果想提高延时的精度,比如想进行10ms级的延时,将udelay(10000)改为udelay(100)就可以了 。

4。引导命令
include/configs/smartarm.h

#define CONFIG_BOOTCOMMAND "run yboot "
#define CONFIG_EXTRA_ENV_SETTINGS /
            "serverip=192.168.1.110/0" /
            "gatewayip=192.168.1.254/0" /
            "ipaddr=192.168.1.164/0" /
            "bootfile=uImage/0"/
            /
            "upkernel=" "tftp 80008000 uImage;"/
            "nand erase clean 0x00200000 $(filesize);"/
            "nand write.jffs2 0x80008000 0x00200000 $(filesize);"/
            "setenv kernelsize $(filesize); saveenv/0"/
            /
            "upsafefs=" "tftp 80008000 safefs.cramfs;"/
            "nand erase clean 0x00600000 $(filesize);"/
            "nand write.jffs2 0x80008000 0x00600000 $(filesize)/0"/
            /
            "yboot=" "nand read.jffs2 0x81000000 0x00200000 $(filesize);"/
            "bootm 81000000/0"/
            /
            "safemode=" "setenv bootargs root=/dev/mtdblock3 console=ttyS0,115200, mem=64M rootfstype=cramfs; run yboot/0"/
            /
            "zhiyuan=" "run upsafefs; run upkernel/0"

可见,引导内核其实就是将内核读取到内存中然后再跳到那个地方引导。

5。run_command
common/main.c
int run_command (const char *cmd, int flag)
{
    cmd_tbl_t *cmdtp;
    char cmdbuf[CONFIG_SYS_CBSIZE];    /* working copy of cmd        */
    char *token;            /* start of token in cmdbuf    */
    char *sep;            /* end of token (separator) in cmdbuf */
    char finaltoken[CONFIG_SYS_CBSIZE];
    char *str = cmdbuf;
    char *argv[CONFIG_SYS_MAXARGS + 1];    /* NULL terminated    */
    int argc, inquotes;
    int repeatable = 1;
    int rc = 0;

    clear_ctrlc();        /* forget any previous Control C */

    if (!cmd || !*cmd) {
        return -1;    /* empty command */  空命令
    }

    if (strlen(cmd) >= CONFIG_SYS_CBSIZE) {  //命令太长
        puts ("## Command too long!/n");
        return -1;
    }

    strcpy (cmdbuf, cmd);            //将命令拷贝到临时命令缓冲cmdbuf

    /* Process separators and check for invalid
     * repeatable commands
     */
    while (*str) {  //str指向cmdbuf

        /*
         * Find separator, or string end
         * Allow simple escape of ';' by writing "/;"
         */
        for (inquotes = 0, sep = str; *sep; sep++) {  //寻找分割符或者命令尾部。相邻的句子之间是用;隔开的。每次处理一句命令
            if ((*sep=='/'') &&
                (*(sep-1) != '//'))
                inquotes=!inquotes;

            if (!inquotes &&
                (*sep == ';') &&    /* separator        */
                ( sep != str) &&    /* past string start    */
                (*(sep-1) != '//'))    /* and NOT escaped    */
                break;
        }

        /*
         * Limit the token to data between separators
         */
        token = str;        //token指向命令的开头
        if (*sep) {                      //如果是分隔符的话,将分隔符替换为空字符
            str = sep + 1;    /* start of command for next pass */str指向下一句的开头
            *sep = '/0';
        }
        else
            str = sep;    /* no more commands for next pass */如果没有其它命令了,str指向命令尾部

        /* find macros in this token and replace them */
        process_macros (token, finaltoken);        //将token指向的命令中的宏替换掉,如把$(kernelsize)替换成内核的大小

        /* Extract arguments */
        if ((argc = parse_line (finaltoken, argv)) == 0) {//将每一个参数用‘/0’隔开,argv中的每一个指针指向一个参数的起始地址。 返回值为参数的个数
            rc = -1;    /* no command at all */
            continue;
        }

        /* Look up command in command table */
        if ((cmdtp = find_cmd(argv[0])) == NULL) {  //第一个参数就是要运行的命令,首先在命令表中找到它的命令结构体的指针
            printf ("Unknown command '%s' - try 'help'/n", argv[0]);
            rc = -1;    /* give up after bad command */
            continue;
        }

        /* found - check max args */
        if (argc > cmdtp->maxargs) { //检查参数个数是否过多
            cmd_usage(cmdtp);
            rc = -1;
            continue;
        }

        /* OK - call function to do the command */
        if ((cmdtp->cmd) (cmdtp, flag, argc, argv) != 0) {//调用命令执行函数。这是最重要的一步。
            rc = -1;
        }

        repeatable &= cmdtp->repeatable;//设置命令自动重复执行的标志。也就是只按下enter键是否可以执行最近执行的命令 .

        /* Did the user stop this? */
        if (had_ctrlc ())                 //检查是否有ctrl+c按键按下,如果有,结束当前命令。本函数并没有从中断接收字符,接收ctrl+c的是一些执行命令的函数。
            return -1;    /* if stopped then not repeatable */
    }

    return rc ? rc : repeatable;
}

本篇文章来源于 Linux公社网站(www.linuxidc.com)  原文链接:http://www.linuxidc.com/Linux/2011-12/49044.htm

 

 

main_loop()函数做的都是与具体平台无关的工作,主要包括初始化启动次数限制机制、设置软件版本号、打印启动信息、解析命令等。

(1)设置启动次数有关参数。在进入main_loop()函数后,首先是根据配置加载已经保留的启动次数,并且根据配置判断是否超过启动次数。代码如下:

295 void main_loop (void)  
296 {  
297 #ifndef CFG_HUSH_PARSER  
298   static char lastcommand[CFG_CBSIZE] = { 0, };  
299   int len;  
300   int rc = 1;  
301   int flag;  
302 #endif  
303   
304 #if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)  
305   char *s;  
306   int bootdelay;  
307 #endif  
308 #ifdef CONFIG_PREBOOT  
309   char *p;  
310 #endif  
311 #ifdef CONFIG_BOOTCOUNT_LIMIT  
312   unsigned long bootcount = 0;  
313   unsigned long bootlimit = 0;  
314   char *bcs;  
315   char bcs_set[16];  
316 #endif /* CONFIG_BOOTCOUNT_LIMIT */  
317   
318 #if defined(CONFIG_VFD) && defined(VFD_TEST_LOGO)  
319   ulong bmp = 0;    /* default bitmap */  
320   extern int trab_vfd (ulong bitmap);  
321   
322 #ifdef CONFIG_MODEM_SUPPORT  
323   if (do_mdm_init)  
324     bmp = 1;  /* alternate bitmap */  
325 #endif  
326   trab_vfd (bmp);  
327 #endif  /* CONFIG_VFD && VFD_TEST_LOGO */  
328   
329 #ifdef CONFIG_BOOTCOUNT_LIMIT  
330   bootcount = bootcount_load();         // 加载保存的启动次数  
331   bootcount++;                          // 启动次数加1  
332   bootcount_store (bootcount);          // 更新启动次数  
333   sprintf (bcs_set, "%lu", bootcount);  // 打印启动次数  
334   setenv ("bootcount", bcs_set);  
335   bcs = getenv ("bootlimit");  
336   bootlimit = bcs ? simple_strtoul (bcs, NULL, 10) : 0;  
                                            // 转换启动次数字符串为UINT类型  
337 #endif /* CONFIG_BOOTCOUNT_LIMIT */ 

第329~337行是启动次数限制功能,启动次数限制可以被用户设置一个启动次数,然后保存在Flash存储器的特定位置,当到达启动次数后,U-Boot无法启动。该功能适合一些商业产品,通过配置不同的License限制用户重新启动系统。

(2)程序第339~348行是Modem功能。如果系统中有Modem,打开该功能可以接受其他用户通过电话网络的拨号请求。Modem功能通常供一些远程控制的系统使用,代码如下:

339 #ifdef CONFIG_MODEM_SUPPORT  
340   debug ("DEBUG: main_loop:   do_mdm_init=%d\n", do_mdm_init);  
341   if (do_mdm_init) {                           // 判断是否需要初始化Modem  
342     char *str = strdup(getenv("mdm_cmd"));     // 获取Modem参数  
343     setenv ("preboot", str);  /* set or delete definition */  
344     if (str != NULL)  
345       free (str);  
346     mdm_init(); /* wait for modem connection */ // 初始化Modem  
347   }  
348 #endif  /* CONFIG_MODEM_SUPPORT */ 

(3)接下来设置U-Boot的版本号,初始化命令自动完成功能等。代码如下:

350 #ifdef CONFIG_VERSION_VARIABLE  
351   {  
352     extern char version_string[];  
353   
354     setenv ("ver", version_string);  /* set version variable */   
                                                // 设置版本号  
355   }  
356 #endif /* CONFIG_VERSION_VARIABLE */  
357   
358 #ifdef CFG_HUSH_PARSER  
359   u_boot_hush_start ();                     // 初始化Hash功能  
360 #endif  
361   
362 #ifdef CONFIG_AUTO_COMPLETE  
363   install_auto_complete();                  // 初始化命令自动完成功能  
364 #endif  
365   
366 #ifdef CONFIG_PREBOOT  
367   if ((p = getenv ("preboot")) != NULL) {  
368 # ifdef CONFIG_AUTOBOOT_KEYED  
369     int prev = disable_ctrlc(1);  /* disable Control C checking */  
                                                // 关闭Crtl+C组合键  
370 # endif  
371   
372 # ifndef CFG_HUSH_PARSER  
373     run_command (p, 0); // 运行Boot参数  
374 # else  
375     parse_string_outer(p, FLAG_PARSE_SEMICOLON |  
376             FLAG_EXIT_FROM_LOOP);  
377 # endif  
378   
379 # ifdef CONFIG_AUTOBOOT_KEYED  
380     disable_ctrlc(prev);  /* restore Control C checking */  
                                                // 恢复Ctrl+C组合键  
381 # endif  
382   }  
383 #endif /* CONFIG_PREBOOT */ 

程序第350~356行是动态版本号功能支持代码,version_string变量是在其他文件定义的一个字符串变量,当用户改变U-Boot版本的时候会更新该变量。打开动态版本支持功能后,U-Boot在启动的时候会显示最新的版本号。

程序第363行设置命令行自动完成功能,该功能与Linux的shell类似,当用户输入一部分命令后,可以通过按下键盘上的Tab键补全命令的剩余部分。main_loop()函数不同的功能使用宏开关控制不仅能提高代码模块化,更主要的是针对嵌入式系统Flash存储器大小设计的。在嵌入式系统上,不同的系统Flash存储空间不同。对于一些Flash空间比较紧张的设备来说,通过宏开关关闭一些不是特别必要的功能如命令行自动完成,可以减小U-Boot编译后的文件大小。

(4)在进入主循环之前,如果配置了启动延迟功能,需要等待用户从串口或者网络接口输入。如果用户按下任意键打断,启动流程,会向终端打印出一个启动菜单。代码如下:

385 #if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)  
386   s = getenv ("bootdelay");  
387   bootdelay = s ? (int)simple_strtol(s, NULL, 10) : CONFIG_BOOTDELAY;  
                                                        // 启动延迟  
388   
389   debug ("### main_loop entered: bootdelay=%d\n\n", bootdelay);  
390   
391 # ifdef CONFIG_BOOT_RETRY_TIME  
392   init_cmd_timeout ();      // 初始化命令行超时机制  
393 # endif /* CONFIG_BOOT_RETRY_TIME */  
394   
395 #ifdef CONFIG_BOOTCOUNT_LIMIT  
396   if (bootlimit && (bootcount > bootlimit)) { // 检查是否超出启动次数限制  
397     printf ("Warning: Bootlimit (%u) exceeded. Using altbootcmd.\n",  
398             (unsigned)bootlimit);  
399     s = getenv ("altbootcmd");  
400   }  
401   else  
402 #endif /* CONFIG_BOOTCOUNT_LIMIT */  
403     s = getenv ("bootcmd"); // 获取启动命令参数  
404   
405   debug ("### main_loop: bootcmd=\"%s\"\n", s ? s : "<UNDEFINED>");  
406   
407   if (bootdelay >= 0 && s && !abortboot (bootdelay)) {    
                                                    //检查是否支持启动延迟功能  
408 # ifdef CONFIG_AUTOBOOT_KEYED  
409     int prev = disable_ctrlc(1);  /* disable Control C checking */    
                                                    // 关闭Ctrl+C组合键  
410 # endif  
411   
412 # ifndef CFG_HUSH_PARSER  
413     run_command (s, 0);     // 运行启动命令行  
414 # else  
415     parse_string_outer(s, FLAG_PARSE_SEMICOLON |  
416             FLAG_EXIT_FROM_LOOP);  
417 # endif  
418   
419 # ifdef CONFIG_AUTOBOOT_KEYED  
420     disable_ctrlc(prev);  /* restore Control C checking */  
                                                    // 打开Ctrl+C组合键  
421 # endif  
422   }  
423   
424 # ifdef CONFIG_MENUKEY  
425   if (menukey == CONFIG_MENUKEY) {  // 检查是否支持菜单键  
426       s = getenv("menucmd");  
427       if (s) {  
428 # ifndef CFG_HUSH_PARSER  
429     run_command (s, 0);  
430 # else  
431     parse_string_outer(s, FLAG_PARSE_SEMICOLON |  
432             FLAG_EXIT_FROM_LOOP);  
433 # endif  
434       }  
435   }  
436 #endif /* CONFIG_MENUKEY */  
437 #endif  /* CONFIG_BOOTDELAY */  
438   
439 #ifdef CONFIG_AMIGAONEG3SE  
440   {  
441       extern void video_banner(void);  
442       video_banner();               // 打印启动图标  
443   }  
444 #endif 

(5)在各功能设置完毕后,程序第454行进入一个for死循环,该循环不断使用readline()函数(第463行)从控制台(一般是串口)读取用户的输入,然后解析。有关如何解析命令请参考U-Boot代码中run_command()函数的定义,本书不再赘述。代码如下:

446   /*  
447    * Main Loop for Monitor Command Processing  
448    */  
449 #ifdef CFG_HUSH_PARSER  
450   parse_file_outer();  
451   /* This point is never reached */  
452   for (;;);  
453 #else  
454   for (;;) {                        // 进入命令行循环  
455 #ifdef CONFIG_BOOT_RETRY_TIME  
456     if (rc >= 0) {  
457       /* Saw enough of a valid command to  
458        * restart the timeout.  
459        */  
460       reset_cmd_timeout();          // 设置命令行超时  
461     }  
462 #endif  
463     len = readline (CFG_PROMPT);    // 读取命令  
464   
465     flag = 0; /* assume no special flags for now */  
466     if (len > 0)  
467       strcpy (lastcommand, console_buffer);  
468     else if (len == 0)  
469       flag |= CMD_FLAG_REPEAT;  
470 #ifdef CONFIG_BOOT_RETRY_TIME  
471     else if (len == -2) {  
472       /* -2 means timed out, retry autoboot  
473        */  
474       puts ("\nTimed out waiting for command\n");  
475 # ifdef CONFIG_RESET_TO_RETRY  
476       /* Reinit board to run initialization code again */  
477       do_reset (NULL, 0, 0, NULL);  
478 # else  
479       return;   /* retry autoboot */  
480 # endif  
481     }  
482 #endif  
483   
484     if (len == -1)  
485       puts ("<INTERRUPT>\n");  
486     else  
487       rc = run_command (lastcommand, flag); // 运行命令  
488   
489     if (rc <= 0) {  
490       /* invalid command or not repeatable, forget it */  
491       lastcommand[0] = 0;  
492     }  
493   }  
494 #endif /*CFG_HUSH_PARSER*/  
495 } 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值