Linux内核分析:实验六

安常青   原创作品转载请注明出处    《Linux内核分析》MOOC课程http://mooc.study.163.com/course/USTC-1000029000 


1.什么是进程

所谓进程,就是一个程序的一个运行的动态实体,每个进程都有自己的进程控制块,里面记录了进程的各种信息,并通过pid唯一的标识。操作系统就是通过获取和改变进程控制块里面的成员变量,从而控制进程的运行。


2.进程的创建

进程可以通过多个系统调用进行创建,fork,vfork,clone都可以创建一个进程,但它们本质上都调用do_fork来实现的。而do_fork主要调用了copy_process来创建一个新的进程。
copy_process主要完成了以下几部分:
1.调用dup_task_struct复制当前的task_struct
2.调用sched_fork初始化数据结构,并把进程状态设置为TASK_RUNNING
3.复制父进程的所有信息
4.调用copy_thread初始化子进程的内核栈
5.为新的进程分配并设置行的pid
下面是copy_process的代码:
[cpp]  view plain  copy
 print ?
  1. /* 
  2.  * This creates a new process as a copy of the old one, 
  3.  * but does not actually start it yet. 
  4.  * 
  5.  * It copies the registers, and all the appropriate 
  6.  * parts of the process environment (as per the clone 
  7.  * flags). The actual kick-off is left to the caller. 
  8.  */  
  9. static struct task_struct *copy_process(unsigned long clone_flags,  
  10.                     unsigned long stack_start,  
  11.                     struct pt_regs *regs,  
  12.                     unsigned long stack_size,  
  13.                     int __user *child_tidptr,  
  14.                     struct pid *pid,  
  15.                     int trace)  
  16. {  
  17.     int retval;  
  18.     struct task_struct *p;  
  19.     int cgroup_callbacks_done = 0;  
  20.     /*下面为参数有效性检查*/  
  21.     if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))  
  22.         return ERR_PTR(-EINVAL);  
  23.   
  24.     /* 
  25.      * Thread groups must share signals as well, and detached threads 
  26.      * can only be started up within the thread group. 
  27.      */  
  28.     if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))  
  29.         return ERR_PTR(-EINVAL);  
  30.   
  31.     /* 
  32.      * Shared signal handlers imply shared VM. By way of the above, 
  33.      * thread groups also imply shared VM. Blocking this case allows 
  34.      * for various simplifications in other code. 
  35.      */  
  36.     if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))  
  37.         return ERR_PTR(-EINVAL);  
  38.   
  39.     /* 
  40.      * Siblings of global init remain as zombies on exit since they are 
  41.      * not reaped by their parent (swapper). To solve this and to avoid 
  42.      * multi-rooted process trees, prevent global and container-inits 
  43.      * from creating siblings. 
  44.      */  
  45.     if ((clone_flags & CLONE_PARENT) &&  
  46.                 current->signal->flags & SIGNAL_UNKILLABLE)  
  47.         return ERR_PTR(-EINVAL);  
  48.     /*Check permission before creating a child process.  See the clone(2) 
  49.  *  manual page for definitions of the @clone_flags. 
  50.  *  @clone_flags contains the flags indicating what should be shared. 
  51.  *  Return 0 if permission is granted.*/  
  52.     retval = security_task_create(clone_flags);  
  53.     if (retval)  
  54.         goto fork_out;  
  55.   
  56.     retval = -ENOMEM;  
  57.     /*为新进程创建一个内核栈、thread_iofo和task_struct, 
  58.     这里完全copy父进程的内容,所以到目前为止, 
  59.     父进程和子进程是没有任何区别的。,从这里也 
  60.     可以看出,这个版本的内核在创建时需要为自己 
  61.     分配内核栈*/  
  62.     p = dup_task_struct(current);  
  63.     if (!p)  
  64.         goto fork_out;  
  65.     /*task结构中ftrace_ret_stack结构变量的初始化,即函数 
  66.     返回用的栈*/  
  67.     ftrace_graph_init_task(p);  
  68.     /*task中互斥变量的初始化*/  
  69.     rt_mutex_init_task(p);  
  70.   
  71. #ifdef CONFIG_PROVE_LOCKING/*not set*/  
  72.     DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);  
  73.     DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);  
  74. #endif  
  75.     retval = -EAGAIN;  
  76.     /*首先看前面的两个if,第一个if里面的rlim数组包含在task_sturct数组中。 
  77.     对进程占用的资源数做出限制,rlim[RLIMIT_NPROC]限制了改进程用户 
  78.     可以拥有的总进程数量,如果当前用户所拥有的进程数量超过了 
  79.     规定的最大拥有进程数量,在内核中就直接goto bad_fork_free了。 
  80.     第2个if使用了capable()函数来对权限做出检查,检查是否有权 
  81.     对指定的资源进行操作,该函数返回0则代表无权操作。*/  
  82.     if (atomic_read(&p->real_cred->user->processes) >=  
  83.             p->signal->rlim[RLIMIT_NPROC].rlim_cur) {  
  84.         if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE) &&  
  85.             p->real_cred->user != INIT_USER)  
  86.             goto bad_fork_free;  
  87.     }  
  88.     /*Copy credentials for the new process*/  
  89.     retval = copy_creds(p, clone_flags);  
  90.     if (retval < 0)  
  91.         goto bad_fork_free;  
  92.   
  93.     /* 
  94.      * If multiple threads are within copy_process(), then this check 
  95.      * triggers too late. This doesn't hurt, the check is only there 
  96.      * to stop root fork bombs. 
  97.      */  
  98.     retval = -EAGAIN;  
  99.     /*检查创建的进程是否超过了系统进程总量*/  
  100.     if (nr_threads >= max_threads)  
  101.         goto bad_fork_cleanup_count;  
  102.   
  103.     if (!try_module_get(task_thread_info(p)->exec_domain->module))  
  104.         goto bad_fork_cleanup_count;  
  105.   
  106.     p->did_exec = 0;  
  107.     delayacct_tsk_init(p);  /* Must remain after dup_task_struct() */  
  108.     /*更新task_struct结构中flags成员*/  
  109.     copy_flags(clone_flags, p);  
  110.     INIT_LIST_HEAD(&p->children);  
  111.     INIT_LIST_HEAD(&p->sibling);  
  112.     rcu_copy_process(p);/*rcu相关变量的初始化*/  
  113.     p->vfork_done = NULL;  
  114.     spin_lock_init(&p->alloc_lock);  
  115.   
  116.     init_sigpending(&p->pending);  
  117.   
  118.     p->utime = cputime_zero;  
  119.     p->stime = cputime_zero;  
  120.     p->gtime = cputime_zero;  
  121.     p->utimescaled = cputime_zero;  
  122.     p->stimescaled = cputime_zero;  
  123.     p->prev_utime = cputime_zero;  
  124.     p->prev_stime = cputime_zero;  
  125.   
  126.     p->default_timer_slack_ns = current->timer_slack_ns;  
  127.   
  128.     task_io_accounting_init(&p->ioac);/*task中io数据记录的初始化*/  
  129.     acct_clear_integrals(p);/*clear the mm integral fields in task_struct*/  
  130.   
  131.     posix_cpu_timers_init(p);/*timer初始化*/  
  132.   
  133.     p->lock_depth = -1;      /* -1 = no lock */  
  134.     do_posix_clock_monotonic_gettime(&p->start_time);  
  135.     p->real_start_time = p->start_time;  
  136.     monotonic_to_bootbased(&p->real_start_time);  
  137.     p->io_context = NULL;  
  138.     p->audit_context = NULL;  
  139.     cgroup_fork(p);/*attach newly forked task to its parents cgroup.*/  
  140. #ifdef CONFIG_NUMA/*not set*/  
  141.     p->mempolicy = mpol_dup(p->mempolicy);  
  142.     if (IS_ERR(p->mempolicy)) {  
  143.         retval = PTR_ERR(p->mempolicy);  
  144.         p->mempolicy = NULL;  
  145.         goto bad_fork_cleanup_cgroup;  
  146.     }  
  147.     mpol_fix_fork_child_flag(p);  
  148. #endif  
  149. #ifdef CONFIG_TRACE_IRQFLAGS/*yes*/  
  150.     p->irq_events = 0;  
  151. #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW/*not found*/  
  152.     p->hardirqs_enabled = 1;  
  153. #else  
  154.     p->hardirqs_enabled = 0;  
  155. #endif  
  156.     p->hardirq_enable_ip = 0;  
  157.     p->hardirq_enable_event = 0;  
  158.     p->hardirq_disable_ip = _THIS_IP_;  
  159.     p->hardirq_disable_event = 0;  
  160.     p->softirqs_enabled = 1;  
  161.     p->softirq_enable_ip = _THIS_IP_;  
  162.     p->softirq_enable_event = 0;  
  163.     p->softirq_disable_ip = 0;  
  164.     p->softirq_disable_event = 0;  
  165.     p->hardirq_context = 0;  
  166.     p->softirq_context = 0;  
  167. #endif  
  168. #ifdef CONFIG_LOCKDEP/*yes*/  
  169.     p->lockdep_depth = 0; /* no locks held yet */  
  170.     p->curr_chain_key = 0;  
  171.     p->lockdep_recursion = 0;  
  172. #endif  
  173.   
  174. #ifdef CONFIG_DEBUG_MUTEXES/*not set */  
  175.     p->blocked_on = NULL; /* not blocked yet */  
  176. #endif  
  177.   
  178.     p->bts = NULL;  
  179.   
  180.     p->stack_start = stack_start;  
  181.   
  182.     /* Perform scheduler related setup. Assign this task to a CPU. */  
  183.     sched_fork(p, clone_flags);/*调度相关初始化*/  
  184.     /* 
  185.     * Initialize the perf_event context in task_struct 
  186.     */  
  187.     retval = perf_event_init_task(p);  
  188.     if (retval)  
  189.         goto bad_fork_cleanup_policy;  
  190.   
  191.     if ((retval = audit_alloc(p)))  
  192.         goto bad_fork_cleanup_policy;  
  193.   
  194.     /*下面的操作中,根据flag中是否设置了相关标志 
  195.     进行重新分配或者共享父进程的内容*/  
  196.     /* copy all the process information */  
  197.     if ((retval = copy_semundo(clone_flags, p)))  
  198.         goto bad_fork_cleanup_audit;  
  199.     if ((retval = copy_files(clone_flags, p)))  
  200.         goto bad_fork_cleanup_semundo;  
  201.     if ((retval = copy_fs(clone_flags, p)))  
  202.         goto bad_fork_cleanup_files;  
  203.     if ((retval = copy_sighand(clone_flags, p)))  
  204.         goto bad_fork_cleanup_fs;  
  205.     if ((retval = copy_signal(clone_flags, p)))  
  206.         goto bad_fork_cleanup_sighand;  
  207.     if ((retval = copy_mm(clone_flags, p)))  
  208.         goto bad_fork_cleanup_signal;  
  209.     if ((retval = copy_namespaces(clone_flags, p)))  
  210.         goto bad_fork_cleanup_mm;  
  211.     if ((retval = copy_io(clone_flags, p)))  
  212.         goto bad_fork_cleanup_namespaces;  
  213.     retval = copy_thread(clone_flags, stack_start, stack_size, p, regs);  
  214.     if (retval)  
  215.         goto bad_fork_cleanup_io;  
  216.   
  217.     if (pid != &init_struct_pid) {  
  218.         retval = -ENOMEM;  
  219.         pid = alloc_pid(p->nsproxy->pid_ns);  
  220.         if (!pid)  
  221.             goto bad_fork_cleanup_io;  
  222.   
  223.         if (clone_flags & CLONE_NEWPID) {  
  224.             retval = pid_ns_prepare_proc(p->nsproxy->pid_ns);  
  225.             if (retval < 0)  
  226.                 goto bad_fork_free_pid;  
  227.         }  
  228.     }  
  229.   
  230.     p->pid = pid_nr(pid);  
  231.     p->tgid = p->pid;  
  232.     /*如果设置了同在一个线程组则继承TGID。 
  233.     对于普通进程来说TGID和PID相等, 
  234.     对于线程来说,同一线程组内的所有线程的TGID都相等, 
  235.     这使得这些多线程可以通过调用getpid()获得相同的PID。*/  
  236.     if (clone_flags & CLONE_THREAD)  
  237.         p->tgid = current->tgid;  
  238.     /*如果命名空间不相等,clone the cgroup the given subsystem is attached to*/  
  239.     if (current->nsproxy != p->nsproxy) {  
  240.         retval = ns_cgroup_clone(p, pid);  
  241.         if (retval)  
  242.             goto bad_fork_free_pid;  
  243.     }  
  244.     /*如果设置了CLONE_CHILD_SETTID,将变量设置为参数*/  
  245.     p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;  
  246.     /* 
  247.      * Clear TID on mm_release()? 
  248.      */  
  249.     p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr: NULL;  
  250. #ifdef CONFIG_FUTEX/*yes*/  
  251.     p->robust_list = NULL;  
  252. #ifdef CONFIG_COMPAT/*not found*/  
  253.     p->compat_robust_list = NULL;  
  254. #endif  
  255.     INIT_LIST_HEAD(&p->pi_state_list);  
  256.     p->pi_state_cache = NULL;  
  257. #endif  
  258.     /* 
  259.      * sigaltstack should be cleared when sharing the same VM 
  260.      */  
  261.     if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)  
  262.         p->sas_ss_sp = p->sas_ss_size = 0;  
  263.   
  264.     /* 
  265.      * Syscall tracing should be turned off in the child regardless 
  266.      * of CLONE_PTRACE. 
  267.      */  
  268.     clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);  
  269. #ifdef TIF_SYSCALL_EMU/*not found*/  
  270.     clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);  
  271. #endif  
  272.     clear_all_latency_tracing(p);  
  273.   
  274.     /* ok, now we should be set up.. */  
  275.     p->exit_signal = (clone_flags & CLONE_THREAD) ? -1 : (clone_flags & CSIGNAL);  
  276.     p->pdeath_signal = 0;  
  277.     p->exit_state = 0;  
  278.   
  279.     /* 
  280.      * Ok, make it visible to the rest of the system. 
  281.      * We dont wake it up yet. 
  282.      */  
  283.     p->group_leader = p;  
  284.     INIT_LIST_HEAD(&p->thread_group);  
  285.   
  286.     /* Now that the task is set up, run cgroup callbacks if 
  287.      * necessary. We need to run them before the task is visible 
  288.      * on the tasklist. */  
  289.     cgroup_fork_callbacks(p);  
  290.     cgroup_callbacks_done = 1;  
  291.   
  292.     /* Need tasklist lock for parent etc handling! */  
  293.     write_lock_irq(&tasklist_lock);  
  294.   
  295.     /* 
  296.      * The task hasn't been attached yet, so its cpus_allowed mask will 
  297.      * not be changed, nor will its assigned CPU. 
  298.      * 
  299.      * The cpus_allowed mask of the parent may have changed after it was 
  300.      * copied first time - so re-copy it here, then check the child's CPU 
  301.      * to ensure it is on a valid CPU (and if not, just force it back to 
  302.      * parent's CPU). This avoids alot of nasty races. 
  303.      */  
  304.     p->cpus_allowed = current->cpus_allowed;  
  305.     p->rt.nr_cpus_allowed = current->rt.nr_cpus_allowed;  
  306.     if (unlikely(!cpu_isset(task_cpu(p), p->cpus_allowed) ||  
  307.             !cpu_online(task_cpu(p))))  
  308.         set_task_cpu(p, smp_processor_id());  
  309.   
  310.     /* CLONE_PARENT re-uses the old parent */  
  311.     /*如果这两个标志设定了,那么和父进程 
  312.     有相同的父进程*/  
  313.     if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {  
  314.         p->real_parent = current->real_parent;  
  315.         p->parent_exec_id = current->parent_exec_id;  
  316.     } else {/*父进程为实际父进程*/  
  317.         p->real_parent = current;  
  318.         p->parent_exec_id = current->self_exec_id;  
  319.     }  
  320.   
  321.     spin_lock(¤t->sighand->siglock);  
  322.   
  323.     /* 
  324.      * Process group and session signals need to be delivered to just the 
  325.      * parent before the fork or both the parent and the child after the 
  326.      * fork. Restart if a signal comes in before we add the new process to 
  327.      * it's process group. 
  328.      * A fatal signal pending means that current will exit, so the new 
  329.      * thread can't slip out of an OOM kill (or normal SIGKILL). 
  330.      */  
  331.     recalc_sigpending();  
  332.     if (signal_pending(current)) {  
  333.         spin_unlock(¤t->sighand->siglock);  
  334.         write_unlock_irq(&tasklist_lock);  
  335.         retval = -ERESTARTNOINTR;  
  336.         goto bad_fork_free_pid;  
  337.     }  
  338.     /*如果和父进程有相同的线程组*/  
  339.     if (clone_flags & CLONE_THREAD) {  
  340.         atomic_inc(¤t->signal->count);  
  341.         atomic_inc(¤t->signal->live);  
  342.         p->group_leader = current->group_leader;/*和父进程相同的组领导*/  
  343.         /*将进程加入组leader的链表尾部*/  
  344.         list_add_tail_rcu(&p->thread_group, &p->group_leader->thread_group);  
  345.     }  
  346.   
  347.     if (likely(p->pid)) {  
  348.         /*保持进程应有的关系*/  
  349.         list_add_tail(&p->sibling, &p->real_parent->children);  
  350.         /*ptrace的相关初始化*/  
  351.         tracehook_finish_clone(p, clone_flags, trace);  
  352.   
  353.         if (thread_group_leader(p)) {/*如果进程p时线程组leader*/  
  354.             if (clone_flags & CLONE_NEWPID)  
  355.                 /*如果是新创建的pid命名空间,那么将 
  356.                 命名空间的child_reaper变量置为p,从这里看出 
  357.                 这个变量设置为创建者进程控制块*/  
  358.                 p->nsproxy->pid_ns->child_reaper = p;  
  359.   
  360.             p->signal->leader_pid = pid;  
  361.             tty_kref_put(p->signal->tty);/*释放tty引用*/  
  362.             p->signal->tty = tty_kref_get(current->signal->tty);/*得到tty引用*/  
  363.             /*下面两行为加入对应的pid哈希表,关于pid 
  364.             的组织参考前一篇文章*/  
  365.             attach_pid(p, PIDTYPE_PGID, task_pgrp(current));  
  366.             attach_pid(p, PIDTYPE_SID, task_session(current));  
  367.             list_add_tail_rcu(&p->tasks, &init_task.tasks);/*加入队列*/  
  368.             __get_cpu_var(process_counts)++;/*将per cpu变量加一*/  
  369.         }  
  370.         attach_pid(p, PIDTYPE_PID, pid);/*维护pid变量*/  
  371.         nr_threads++;/*线程数加一*/  
  372.     }  
  373.   
  374.     total_forks++;  
  375.     spin_unlock(¤t->sighand->siglock);  
  376.     write_unlock_irq(&tasklist_lock);  
  377.     proc_fork_connector(p);  
  378.     /*Adds the task to the list running through its css_set if necessary.*/  
  379.     cgroup_post_fork(p);  
  380.     perf_event_fork(p);  
  381.     return p;  
  382.   
  383. bad_fork_free_pid:  
  384.     if (pid != &init_struct_pid)  
  385.         free_pid(pid);  
  386. bad_fork_cleanup_io:  
  387.     put_io_context(p->io_context);  
  388. bad_fork_cleanup_namespaces:  
  389.     exit_task_namespaces(p);  
  390. bad_fork_cleanup_mm:  
  391.     if (p->mm)  
  392.         mmput(p->mm);  
  393. bad_fork_cleanup_signal:  
  394.     if (!(clone_flags & CLONE_THREAD))  
  395.         __cleanup_signal(p->signal);  
  396. bad_fork_cleanup_sighand:  
  397.     __cleanup_sighand(p->sighand);  
  398. bad_fork_cleanup_fs:  
  399.     exit_fs(p); /* blocking */  
  400. bad_fork_cleanup_files:  
  401.     exit_files(p); /* blocking */  
  402. bad_fork_cleanup_semundo:  
  403.     exit_sem(p);  
  404. bad_fork_cleanup_audit:  
  405.     audit_free(p);  
  406. bad_fork_cleanup_policy:  
  407.     perf_event_free_task(p);  
  408. #ifdef CONFIG_NUMA  
  409.     mpol_put(p->mempolicy);  
  410. bad_fork_cleanup_cgroup:  
  411. #endif  
  412.     cgroup_exit(p, cgroup_callbacks_done);  
  413.     delayacct_tsk_free(p);  
  414.     module_put(task_thread_info(p)->exec_domain->module);  
  415. bad_fork_cleanup_count:  
  416.     atomic_dec(&p->cred->user->processes);  
  417.     exit_creds(p);  
  418. bad_fork_free:  
  419.     free_task(p);  
  420. fork_out:  
  421.     return ERR_PTR(retval);  
  422. }  


子进程创建后,我们就有两个问题,子进程的返回值为什么是0?子进程从哪里开始执行?
其实,这两个问题在copy_thread中解决了。
在copy_thread中,childregs->ax=0,把子进程的eax赋值为0,这样,子进程的返回值就是0.
在copy_thread中,p->thread.ip=(unsigned long)ret_from_fork,将子进程的ip设为ret_from_fork的首地址,因此子进程是从ret_form_fork执行的。

代码如下:
int copy_thread(int nr, unsigned long clone_flags, unsigned long esp,
 unsigned long unused,
 struct task_struct * p, struct pt_regs * regs)
{
 struct pt_regs * childregs;
 childregs = ((struct pt_regs *) (THREAD_SIZE + (unsigned long) p)) - 1;
 struct_cpy(childregs, regs);
 childregs->eax = 0;
 childregs->esp = esp;
 p->thread.esp = (unsigned long) childregs;
 p->thread.esp0 = (unsigned long) (childregs+1);
 p->thread.eip = (unsigned long) ret_from_fork;
 savesegment(fs,p->thread.fs);
 savesegment(gs,p->thread.gs);
 unlazy_fpu(current);
 struct_cpy(&p->thread.i387, ¤t->thread.i387);
 return 0;
}

3.总结

通过这次实验,对进程和进程的创建有了更深的理解。



你可能感兴趣的:(嵌入式,操作系统,linux)