     1	/*
     2	 *  linux/kernel/sched.c
     3	 *
     4	 *  Kernel scheduler and related syscalls
     5	 *
     6	 *  Copyright (C) 1991, 1992  Linus Torvalds
     7	 *
     8	 *  1996-12-23  Modified by Dave Grothe to fix bugs in semaphores and
     9	 *              make semaphores SMP safe
    10	 *  1998-11-19	Implemented schedule_timeout() and related stuff
    11	 *		by Andrea Arcangeli
    12	 *  1998-12-28  Implemented better SMP scheduling by Ingo Molnar
    13	 */
    14	
    15	/*
    16	 * 'sched.c' is the main kernel file. It contains scheduling primitives
    17	 * (sleep_on, wakeup, schedule etc) as well as a number of simple system
    18	 * call functions (type getpid()), which just extract a field from
    19	 * current-task
    20	 */
    21	
    22	#include <linux/config.h>
    23	#include <linux/mm.h>
    24	#include <linux/init.h>
    25	#include <linux/smp_lock.h>
    26	#include <linux/nmi.h>
    27	#include <linux/interrupt.h>
    28	#include <linux/kernel_stat.h>
    29	#include <linux/completion.h>
    30	#include <linux/prefetch.h>
    31	#include <linux/compiler.h>
    32	
    33	#include <asm/uaccess.h>
    34	#include <asm/mmu_context.h>
    35	
    36	extern void timer_bh(void);
    37	extern void tqueue_bh(void);
    38	extern void immediate_bh(void);
    39	
    40	/*
    41	 * scheduler variables
    42	 */
    43	
    44	unsigned securebits = SECUREBITS_DEFAULT; /* systemwide security settings */
    45	
    46	extern void mem_use(void);
    47	
    48	/*
    49	 * Scheduling quanta.
    50	 *
    51	 * NOTE! The unix "nice" value influences how long a process
    52	 * gets. The nice value ranges from -20 to +19, where a -20
    53	 * is a "high-priority" task, and a "+10" is a low-priority
    54	 * task.
    55	 *
    56	 * We want the time-slice to be around 50ms or so, so this
    57	 * calculation depends on the value of HZ.
    58	 */
    59	#if HZ < 200
    60	#define TICK_SCALE(x)	((x) >> 2)
    61	#elif HZ < 400
    62	#define TICK_SCALE(x)	((x) >> 1)
    63	#elif HZ < 800
    64	#define TICK_SCALE(x)	(x)
    65	#elif HZ < 1600
    66	#define TICK_SCALE(x)	((x) << 1)
    67	#else
    68	#define TICK_SCALE(x)	((x) << 2)
    69	#endif
    70	
    71	#define NICE_TO_TICKS(nice)	(TICK_SCALE(20-(nice))+1)
    72	
    73	
    74	/*
    75	 *	Init task must be ok at boot for the ix86 as we will check its signals
    76	 *	via the SMP irq return path.
    77	 */
    78	 
    79	struct task_struct * init_tasks[NR_CPUS] = {&init_task, };
    80	
    81	/*
    82	 * The tasklist_lock protects the linked list of processes.
    83	 *
    84	 * The runqueue_lock locks the parts that actually access
    85	 * and change the run-queues, and have to be interrupt-safe.
    86	 *
    87	 * If both locks are to be concurrently held, the runqueue_lock
    88	 * nests inside the tasklist_lock.
    89	 *
    90	 * task->alloc_lock nests inside tasklist_lock.
    91	 */
    92	spinlock_t runqueue_lock __cacheline_aligned = SPIN_LOCK_UNLOCKED;  /* inner */
    93	rwlock_t tasklist_lock __cacheline_aligned = RW_LOCK_UNLOCKED;	/* outer */
    94	
    95	static LIST_HEAD(runqueue_head);
    96	
    97	/*
    98	 * We align per-CPU scheduling data on cacheline boundaries,
    99	 * to prevent cacheline ping-pong.
   100	 */
   101	static union {
   102		struct schedule_data {
   103			struct task_struct * curr;
   104			cycles_t last_schedule;
   105		} schedule_data;
   106		char __pad [SMP_CACHE_BYTES];
   107	} aligned_data [NR_CPUS] __cacheline_aligned = { {{&init_task,0}}};
   108	
   109	#define cpu_curr(cpu) aligned_data[(cpu)].schedule_data.curr
   110	#define last_schedule(cpu) aligned_data[(cpu)].schedule_data.last_schedule
   111	
   112	struct kernel_stat kstat;
   113	extern struct task_struct *child_reaper;
   114	
   115	#ifdef CONFIG_SMP
   116	
   117	#define idle_task(cpu) (init_tasks[cpu_number_map(cpu)])
   118	#define can_schedule(p,cpu) \
   119		((p)->cpus_runnable & (p)->cpus_allowed & (1 << cpu))
   120	
   121	#else
   122	
   123	#define idle_task(cpu) (&init_task)
   124	#define can_schedule(p,cpu) (1)
   125	
   126	#endif
   127	
   128	void scheduling_functions_start_here(void) { }
   129	
   130	/*
   131	 * This is the function that decides how desirable a process is..
   132	 * You can weigh different processes against each other depending
   133	 * on what CPU they've run on lately etc to try to handle cache
   134	 * and TLB miss penalties.
   135	 *
   136	 * Return values:
   137	 *	 -1000: never select this
   138	 *	     0: out of time, recalculate counters (but it might still be
   139	 *		selected)
   140	 *	   +ve: "goodness" value (the larger, the better)
   141	 *	 +1000: realtime process, select this.
   142	 */
   143	
   144	static inline int goodness(struct task_struct * p, int this_cpu, struct mm_struct *this_mm)
   145	{
   146		int weight;
   147	
   148		/*
   149		 * select the current process after every other
   150		 * runnable process, but before the idle thread.
   151		 * Also, dont trigger a counter recalculation.
   152		 */
   153		weight = -1;
   154		if (p->policy & SCHED_YIELD)
   155			goto out;
   156	
   157		/*
   158		 * Non-RT process - normal case first.
   159		 */
   160		if (p->policy == SCHED_OTHER) {
   161			/*
   162			 * Give the process a first-approximation goodness value
   163			 * according to the number of clock-ticks it has left.
   164			 *
   165			 * Don't do any other calculations if the time slice is
   166			 * over..
   167			 */
   168			weight = p->counter;
   169			if (!weight)
   170				goto out;
   171				
   172	#ifdef CONFIG_SMP
   173			/* Give a largish advantage to the same processor...   */
   174			/* (this is equivalent to penalizing other processors) */
   175			if (p->processor == this_cpu)
   176				weight += PROC_CHANGE_PENALTY;
   177	#endif
   178	
   179			/* .. and a slight advantage to the current MM */
   180			if (p->mm == this_mm || !p->mm)
   181				weight += 1;
   182			weight += 20 - p->nice;
   183			goto out;
   184		}
   185	
   186		/*
   187		 * Realtime process, select the first one on the
   188		 * runqueue (taking priorities within processes
   189		 * into account).
   190		 */
   191		weight = 1000 + p->rt_priority;
   192	out:
   193		return weight;
   194	}
   195	
   196	/*
   197	 * the 'goodness value' of replacing a process on a given CPU.
   198	 * positive value means 'replace', zero or negative means 'dont'.
   199	 */
   200	static inline int preemption_goodness(struct task_struct * prev, struct task_struct * p, int cpu)
   201	{
   202		return goodness(p, cpu, prev->active_mm) - goodness(prev, cpu, prev->active_mm);
   203	}
   204	
   205	/*
   206	 * This is ugly, but reschedule_idle() is very timing-critical.
   207	 * We are called with the runqueue spinlock held and we must
   208	 * not claim the tasklist_lock.
   209	 */
   210	static FASTCALL(void reschedule_idle(struct task_struct * p));
   211	
   212	static void reschedule_idle(struct task_struct * p)
   213	{
   214	#ifdef CONFIG_SMP
   215		int this_cpu = smp_processor_id();
   216		struct task_struct *tsk, *target_tsk;
   217		int cpu, best_cpu, i, max_prio;
   218		cycles_t oldest_idle;
   219	
   220		/*
   221		 * shortcut if the woken up task's last CPU is
   222		 * idle now.
   223		 */
   224		best_cpu = p->processor;
   225		if (can_schedule(p, best_cpu)) {
   226			tsk = idle_task(best_cpu);
   227			if (cpu_curr(best_cpu) == tsk) {
   228				int need_resched;
   229	send_now_idle:
   230				/*
   231				 * If need_resched == -1 then we can skip sending
   232				 * the IPI altogether, tsk->need_resched is
   233				 * actively watched by the idle thread.
   234				 */
   235				need_resched = tsk->need_resched;
   236				tsk->need_resched = 1;
   237				if ((best_cpu != this_cpu) && !need_resched)
   238					smp_send_reschedule(best_cpu);
   239				return;
   240			}
   241		}
   242	
   243		/*
   244		 * We know that the preferred CPU has a cache-affine current
   245		 * process, lets try to find a new idle CPU for the woken-up
   246		 * process. Select the least recently active idle CPU. (that
   247		 * one will have the least active cache context.) Also find
   248		 * the executing process which has the least priority.
   249		 */
   250		oldest_idle = (cycles_t) -1;
   251		target_tsk = NULL;
   252		max_prio = 0;
   253	
   254		for (i = 0; i < smp_num_cpus; i++) {
   255			cpu = cpu_logical_map(i);
   256			if (!can_schedule(p, cpu))
   257				continue;
   258			tsk = cpu_curr(cpu);
   259			/*
   260			 * We use the first available idle CPU. This creates
   261			 * a priority list between idle CPUs, but this is not
   262			 * a problem.
   263			 */
   264			if (tsk == idle_task(cpu)) {
   265	#if defined(__i386__) && defined(CONFIG_SMP)
   266	                        /*
   267				 * Check if two siblings are idle in the same
   268				 * physical package. Use them if found.
   269				 */
   270				if (smp_num_siblings == 2) {
   271					if (cpu_curr(cpu_sibling_map[cpu]) == 
   272				            idle_task(cpu_sibling_map[cpu])) {
   273						oldest_idle = last_schedule(cpu);
   274						target_tsk = tsk;
   275						break;
   276					}
   277					
   278	                        }
   279	#endif		
   280				if (last_schedule(cpu) < oldest_idle) {
   281					oldest_idle = last_schedule(cpu);
   282					target_tsk = tsk;
   283				}
   284			} else {
   285				if (oldest_idle == -1ULL) {
   286					int prio = preemption_goodness(tsk, p, cpu);
   287	
   288					if (prio > max_prio) {
   289						max_prio = prio;
   290						target_tsk = tsk;
   291					}
   292				}
   293			}
   294		}
   295		tsk = target_tsk;
   296		if (tsk) {
   297			if (oldest_idle != -1ULL) {
   298				best_cpu = tsk->processor;
   299				goto send_now_idle;
   300			}
   301			tsk->need_resched = 1;
   302			if (tsk->processor != this_cpu)
   303				smp_send_reschedule(tsk->processor);
   304		}
   305		return;
   306			
   307	
   308	#else /* UP */
   309		int this_cpu = smp_processor_id();
   310		struct task_struct *tsk;
   311	
   312		tsk = cpu_curr(this_cpu);
   313		if (preemption_goodness(tsk, p, this_cpu) > 0)
   314			tsk->need_resched = 1;
   315	#endif
   316	}
   317	
   318	/*
   319	 * Careful!
   320	 *
   321	 * This has to add the process to the _beginning_ of the
   322	 * run-queue, not the end. See the comment about "This is
   323	 * subtle" in the scheduler proper..
   324	 */
   325	static inline void add_to_runqueue(struct task_struct * p)
   326	{
   327		list_add(&p->run_list, &runqueue_head);
   328		nr_running++;
   329	}
   330	
   331	static inline void move_last_runqueue(struct task_struct * p)
   332	{
   333		list_del(&p->run_list);
   334		list_add_tail(&p->run_list, &runqueue_head);
   335	}
   336	
   337	static inline void move_first_runqueue(struct task_struct * p)
   338	{
   339		list_del(&p->run_list);
   340		list_add(&p->run_list, &runqueue_head);
   341	}
   342	
   343	/*
   344	 * Wake up a process. Put it on the run-queue if it's not
   345	 * already there.  The "current" process is always on the
   346	 * run-queue (except when the actual re-schedule is in
   347	 * progress), and as such you're allowed to do the simpler
   348	 * "current->state = TASK_RUNNING" to mark yourself runnable
   349	 * without the overhead of this.
   350	 */
   351	static inline int try_to_wake_up(struct task_struct * p, int synchronous)
   352	{
   353		unsigned long flags;
   354		int success = 0;
   355	
   356		/*
   357		 * We want the common case fall through straight, thus the goto.
   358		 */
   359		spin_lock_irqsave(&runqueue_lock, flags);
   360		p->state = TASK_RUNNING;
   361		if (task_on_runqueue(p))
   362			goto out;
   363		add_to_runqueue(p);
   364		if (!synchronous || !(p->cpus_allowed & (1 << smp_processor_id())))
   365			reschedule_idle(p);
   366		success = 1;
   367	out:
   368		spin_unlock_irqrestore(&runqueue_lock, flags);
   369		return success;
   370	}
   371	
   372	inline int wake_up_process(struct task_struct * p)
   373	{
   374		return try_to_wake_up(p, 0);
   375	}
   376	
   377	static void process_timeout(unsigned long __data)
   378	{
   379		struct task_struct * p = (struct task_struct *) __data;
   380	
   381		wake_up_process(p);
   382	}
   383	
   384	/**
   385	 * schedule_timeout - sleep until timeout
   386	 * @timeout: timeout value in jiffies
   387	 *
   388	 * Make the current task sleep until @timeout jiffies have
   389	 * elapsed. The routine will return immediately unless
   390	 * the current task state has been set (see set_current_state()).
   391	 *
   392	 * You can set the task state as follows -
   393	 *
   394	 * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
   395	 * pass before the routine returns. The routine will return 0
   396	 *
   397	 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
   398	 * delivered to the current task. In this case the remaining time
   399	 * in jiffies will be returned, or 0 if the timer expired in time
   400	 *
   401	 * The current task state is guaranteed to be TASK_RUNNING when this 
   402	 * routine returns.
   403	 *
   404	 * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
   405	 * the CPU away without a bound on the timeout. In this case the return
   406	 * value will be %MAX_SCHEDULE_TIMEOUT.
   407	 *
   408	 * In all cases the return value is guaranteed to be non-negative.
   409	 */
   410	signed long schedule_timeout(signed long timeout)
   411	{
   412		struct timer_list timer;
   413		unsigned long expire;
   414	
   415		switch (timeout)
   416		{
   417		case MAX_SCHEDULE_TIMEOUT:
   418			/*
   419			 * These two special cases are useful to be comfortable
   420			 * in the caller. Nothing more. We could take
   421			 * MAX_SCHEDULE_TIMEOUT from one of the negative value
   422			 * but I' d like to return a valid offset (>=0) to allow
   423			 * the caller to do everything it want with the retval.
   424			 */
   425			schedule();
   426			goto out;
   427		default:
   428			/*
   429			 * Another bit of PARANOID. Note that the retval will be
   430			 * 0 since no piece of kernel is supposed to do a check
   431			 * for a negative retval of schedule_timeout() (since it
   432			 * should never happens anyway). You just have the printk()
   433			 * that will tell you if something is gone wrong and where.
   434			 */
   435			if (timeout < 0)
   436			{
   437				printk(KERN_ERR "schedule_timeout: wrong timeout "
   438				       "value %lx from %p\n", timeout,
   439				       __builtin_return_address(0));
   440				current->state = TASK_RUNNING;
   441				goto out;
   442			}
   443		}
   444	
   445		expire = timeout + jiffies;
   446	
   447		init_timer(&timer);
   448		timer.expires = expire;
   449		timer.data = (unsigned long) current;
   450		timer.function = process_timeout;
   451	
   452		add_timer(&timer);
   453		schedule();
   454		del_timer_sync(&timer);
   455	
   456		timeout = expire - jiffies;
   457	
   458	 out:
   459		return timeout < 0 ? 0 : timeout;
   460	}
   461	
   462	/*
   463	 * schedule_tail() is getting called from the fork return path. This
   464	 * cleans up all remaining scheduler things, without impacting the
   465	 * common case.
   466	 */
   467	static inline void __schedule_tail(struct task_struct *prev)
   468	{
   469	#ifdef CONFIG_SMP
   470		int policy;
   471	
   472		/*
   473		 * prev->policy can be written from here only before `prev'
   474		 * can be scheduled (before setting prev->cpus_runnable to ~0UL).
   475		 * Of course it must also be read before allowing prev
   476		 * to be rescheduled, but since the write depends on the read
   477		 * to complete, wmb() is enough. (the spin_lock() acquired
   478		 * before setting cpus_runnable is not enough because the spin_lock()
   479		 * common code semantics allows code outside the critical section
   480		 * to enter inside the critical section)
   481		 */
   482		policy = prev->policy;
   483		prev->policy = policy & ~SCHED_YIELD;
   484		wmb();
   485	
   486		/*
   487		 * fast path falls through. We have to clear cpus_runnable before
   488		 * checking prev->state to avoid a wakeup race. Protect against
   489		 * the task exiting early.
   490		 */
   491		task_lock(prev);
   492		task_release_cpu(prev);
   493		mb();
   494		if (prev->state == TASK_RUNNING)
   495			goto needs_resched;
   496	
   497	out_unlock:
   498		task_unlock(prev);	/* Synchronise here with release_task() if prev is TASK_ZOMBIE */
   499		return;
   500	
   501		/*
   502		 * Slow path - we 'push' the previous process and
   503		 * reschedule_idle() will attempt to find a new
   504		 * processor for it. (but it might preempt the
   505		 * current process as well.) We must take the runqueue
   506		 * lock and re-check prev->state to be correct. It might
   507		 * still happen that this process has a preemption
   508		 * 'in progress' already - but this is not a problem and
   509		 * might happen in other circumstances as well.
   510		 */
   511	needs_resched:
   512		{
   513			unsigned long flags;
   514	
   515			/*
   516			 * Avoid taking the runqueue lock in cases where
   517			 * no preemption-check is necessery:
   518			 */
   519			if ((prev == idle_task(smp_processor_id())) ||
   520							(policy & SCHED_YIELD))
   521				goto out_unlock;
   522	
   523			spin_lock_irqsave(&runqueue_lock, flags);
   524			if ((prev->state == TASK_RUNNING) && !task_has_cpu(prev))
   525				reschedule_idle(prev);
   526			spin_unlock_irqrestore(&runqueue_lock, flags);
   527			goto out_unlock;
   528		}
   529	#else
   530		prev->policy &= ~SCHED_YIELD;
   531	#endif /* CONFIG_SMP */
   532	}
   533	
   534	asmlinkage void schedule_tail(struct task_struct *prev)
   535	{
   536		__schedule_tail(prev);
   537	}
   538	
   539	/*
   540	 *  'schedule()' is the scheduler function. It's a very simple and nice
   541	 * scheduler: it's not perfect, but certainly works for most things.
   542	 *
   543	 * The goto is "interesting".
   544	 *
   545	 *   NOTE!!  Task 0 is the 'idle' task, which gets called when no other
   546	 * tasks can run. It can not be killed, and it cannot sleep. The 'state'
   547	 * information in task[0] is never used.
   548	 */
   549	asmlinkage void schedule(void)
   550	{
   551		struct schedule_data * sched_data;
   552		struct task_struct *prev, *next, *p;
   553		struct list_head *tmp;
   554		int this_cpu, c;
   555	
   556	
   557		spin_lock_prefetch(&runqueue_lock);
   558	
   559		if (!current->active_mm) BUG();
   560	need_resched_back:
   561		prev = current;
   562		this_cpu = prev->processor;
   563	
   564		if (unlikely(in_interrupt())) {
   565			printk("Scheduling in interrupt\n");
   566			BUG();
   567		}
   568	
   569		release_kernel_lock(prev, this_cpu);
   570	
   571		/*
   572		 * 'sched_data' is protected by the fact that we can run
   573		 * only one process per CPU.
   574		 */
   575		sched_data = & aligned_data[this_cpu].schedule_data;
   576	
   577		spin_lock_irq(&runqueue_lock);
   578	
   579		/* move an exhausted RR process to be last.. */
   580		if (unlikely(prev->policy == SCHED_RR))
   581			if (!prev->counter) {
   582				prev->counter = NICE_TO_TICKS(prev->nice);
   583				move_last_runqueue(prev);
   584			}
   585	
   586		switch (prev->state) {
   587			case TASK_INTERRUPTIBLE:
   588				if (signal_pending(prev)) {
   589					prev->state = TASK_RUNNING;
   590					break;
   591				}
   592			default:
   593				del_from_runqueue(prev);
   594			case TASK_RUNNING:;
   595		}
   596		prev->need_resched = 0;
   597	
   598		/*
   599		 * this is the scheduler proper:
   600		 */
   601	
   602	repeat_schedule:
   603		/*
   604		 * Default process to select..
   605		 */
   606		next = idle_task(this_cpu);
   607		c = -1000;
   608		list_for_each(tmp, &runqueue_head) {
   609			p = list_entry(tmp, struct task_struct, run_list);
   610			if (can_schedule(p, this_cpu)) {
   611				int weight = goodness(p, this_cpu, prev->active_mm);
   612				if (weight > c)
   613					c = weight, next = p;
   614			}
   615		}
   616	
   617		/* Do we need to re-calculate counters? */
   618		if (unlikely(!c)) {
   619			struct task_struct *p;
   620	
   621			spin_unlock_irq(&runqueue_lock);
   622			read_lock(&tasklist_lock);
   623			for_each_task(p)
   624				p->counter = (p->counter >> 1) + NICE_TO_TICKS(p->nice);
   625			read_unlock(&tasklist_lock);
   626			spin_lock_irq(&runqueue_lock);
   627			goto repeat_schedule;
   628		}
   629	
   630		/*
   631		 * from this point on nothing can prevent us from
   632		 * switching to the next task, save this fact in
   633		 * sched_data.
   634		 */
   635		sched_data->curr = next;
   636		task_set_cpu(next, this_cpu);
   637		spin_unlock_irq(&runqueue_lock);
   638	
   639		if (unlikely(prev == next)) {
   640			/* We won't go through the normal tail, so do this by hand */
   641			prev->policy &= ~SCHED_YIELD;
   642			goto same_process;
   643		}
   644	
   645	#ifdef CONFIG_SMP
   646	 	/*
   647	 	 * maintain the per-process 'last schedule' value.
   648	 	 * (this has to be recalculated even if we reschedule to
   649	 	 * the same process) Currently this is only used on SMP,
   650		 * and it's approximate, so we do not have to maintain
   651		 * it while holding the runqueue spinlock.
   652	 	 */
   653	 	sched_data->last_schedule = get_cycles();
   654	
   655		/*
   656		 * We drop the scheduler lock early (it's a global spinlock),
   657		 * thus we have to lock the previous process from getting
   658		 * rescheduled during switch_to().
   659		 */
   660	
   661	#endif /* CONFIG_SMP */
   662	
   663		kstat.context_swtch++;
   664		/*
   665		 * there are 3 processes which are affected by a context switch:
   666		 *
   667		 * prev == .... ==> (last => next)
   668		 *
   669		 * It's the 'much more previous' 'prev' that is on next's stack,
   670		 * but prev is set to (the just run) 'last' process by switch_to().
   671		 * This might sound slightly confusing but makes tons of sense.
   672		 */
   673		prepare_to_switch();
   674		{
   675			struct mm_struct *mm = next->mm;
   676			struct mm_struct *oldmm = prev->active_mm;
   677			if (!mm) {
   678				if (next->active_mm) BUG();
   679				next->active_mm = oldmm;
   680				atomic_inc(&oldmm->mm_count);
   681				enter_lazy_tlb(oldmm, next, this_cpu);
   682			} else {
   683				if (next->active_mm != mm) BUG();
   684				switch_mm(oldmm, mm, next, this_cpu);
   685			}
   686	
   687			if (!prev->mm) {
   688				prev->active_mm = NULL;
   689				mmdrop(oldmm);
   690			}
   691		}
   692	
   693		/*
   694		 * This just switches the register state and the
   695		 * stack.
   696		 */
   697		switch_to(prev, next, prev);
   698		__schedule_tail(prev);
   699	
   700	same_process:
   701		reacquire_kernel_lock(current);
   702		if (current->need_resched)
   703			goto need_resched_back;
   704		return;
   705	}
   706	
   707	/*
   708	 * The core wakeup function.  Non-exclusive wakeups (nr_exclusive == 0) just wake everything
   709	 * up.  If it's an exclusive wakeup (nr_exclusive == small +ve number) then we wake all the
   710	 * non-exclusive tasks and one exclusive task.
   711	 *
   712	 * There are circumstances in which we can try to wake a task which has already
   713	 * started to run but is not in state TASK_RUNNING.  try_to_wake_up() returns zero
   714	 * in this (rare) case, and we handle it by contonuing to scan the queue.
   715	 */
   716	static inline void __wake_up_common (wait_queue_head_t *q, unsigned int mode,
   717				 	     int nr_exclusive, const int sync)
   718	{
   719		struct list_head *tmp;
   720		struct task_struct *p;
   721	
   722		CHECK_MAGIC_WQHEAD(q);
   723		WQ_CHECK_LIST_HEAD(&q->task_list);
   724		
   725		list_for_each(tmp,&q->task_list) {
   726			unsigned int state;
   727	                wait_queue_t *curr = list_entry(tmp, wait_queue_t, task_list);
   728	
   729			CHECK_MAGIC(curr->__magic);
   730			p = curr->task;
   731			state = p->state;
   732			if (state & mode) {
   733				WQ_NOTE_WAKER(curr);
   734				if (try_to_wake_up(p, sync) && (curr->flags&WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
   735					break;
   736			}
   737		}
   738	}
   739	
   740	void __wake_up(wait_queue_head_t *q, unsigned int mode, int nr)
   741	{
   742		if (q) {
   743			unsigned long flags;
   744			wq_read_lock_irqsave(&q->lock, flags);
   745			__wake_up_common(q, mode, nr, 0);
   746			wq_read_unlock_irqrestore(&q->lock, flags);
   747		}
   748	}
   749	
   750	void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr)
   751	{
   752		if (q) {
   753			unsigned long flags;
   754			wq_read_lock_irqsave(&q->lock, flags);
   755			__wake_up_common(q, mode, nr, 1);
   756			wq_read_unlock_irqrestore(&q->lock, flags);
   757		}
   758	}
   759	
   760	void complete(struct completion *x)
   761	{
   762		unsigned long flags;
   763	
   764		spin_lock_irqsave(&x->wait.lock, flags);
   765		x->done++;
   766		__wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE, 1, 0);
   767		spin_unlock_irqrestore(&x->wait.lock, flags);
   768	}
   769	
   770	void wait_for_completion(struct completion *x)
   771	{
   772		spin_lock_irq(&x->wait.lock);
   773		if (!x->done) {
   774			DECLARE_WAITQUEUE(wait, current);
   775	
   776			wait.flags |= WQ_FLAG_EXCLUSIVE;
   777			__add_wait_queue_tail(&x->wait, &wait);
   778			do {
   779				__set_current_state(TASK_UNINTERRUPTIBLE);
   780				spin_unlock_irq(&x->wait.lock);
   781				schedule();
   782				spin_lock_irq(&x->wait.lock);
   783			} while (!x->done);
   784			__remove_wait_queue(&x->wait, &wait);
   785		}
   786		x->done--;
   787		spin_unlock_irq(&x->wait.lock);
   788	}
   789	
   790	#define	SLEEP_ON_VAR				\
   791		unsigned long flags;			\
   792		wait_queue_t wait;			\
   793		init_waitqueue_entry(&wait, current);
   794	
   795	#define	SLEEP_ON_HEAD					\
   796		wq_write_lock_irqsave(&q->lock,flags);		\
   797		__add_wait_queue(q, &wait);			\
   798		wq_write_unlock(&q->lock);
   799	
   800	#define	SLEEP_ON_TAIL						\
   801		wq_write_lock_irq(&q->lock);				\
   802		__remove_wait_queue(q, &wait);				\
   803		wq_write_unlock_irqrestore(&q->lock,flags);
   804	
   805	void interruptible_sleep_on(wait_queue_head_t *q)
   806	{
   807		SLEEP_ON_VAR
   808	
   809		current->state = TASK_INTERRUPTIBLE;
   810	
   811		SLEEP_ON_HEAD
   812		schedule();
   813		SLEEP_ON_TAIL
   814	}
   815	
   816	long interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
   817	{
   818		SLEEP_ON_VAR
   819	
   820		current->state = TASK_INTERRUPTIBLE;
   821	
   822		SLEEP_ON_HEAD
   823		timeout = schedule_timeout(timeout);
   824		SLEEP_ON_TAIL
   825	
   826		return timeout;
   827	}
   828	
   829	void sleep_on(wait_queue_head_t *q)
   830	{
   831		SLEEP_ON_VAR
   832		
   833		current->state = TASK_UNINTERRUPTIBLE;
   834	
   835		SLEEP_ON_HEAD
   836		schedule();
   837		SLEEP_ON_TAIL
   838	}
   839	
   840	long sleep_on_timeout(wait_queue_head_t *q, long timeout)
   841	{
   842		SLEEP_ON_VAR
   843		
   844		current->state = TASK_UNINTERRUPTIBLE;
   845	
   846		SLEEP_ON_HEAD
   847		timeout = schedule_timeout(timeout);
   848		SLEEP_ON_TAIL
   849	
   850		return timeout;
   851	}
   852	
   853	void scheduling_functions_end_here(void) { }
   854	
   855	#ifndef __alpha__
   856	
   857	/*
   858	 * This has been replaced by sys_setpriority.  Maybe it should be
   859	 * moved into the arch dependent tree for those ports that require
   860	 * it for backward compatibility?
   861	 */
   862	
   863	asmlinkage long sys_nice(int increment)
   864	{
   865		long newprio;
   866	
   867		/*
   868		 *	Setpriority might change our priority at the same moment.
   869		 *	We don't have to worry. Conceptually one call occurs first
   870		 *	and we have a single winner.
   871		 */
   872		if (increment < 0) {
   873			if (!capable(CAP_SYS_NICE))
   874				return -EPERM;
   875			if (increment < -40)
   876				increment = -40;
   877		}
   878		if (increment > 40)
   879			increment = 40;
   880	
   881		newprio = current->nice + increment;
   882		if (newprio < -20)
   883			newprio = -20;
   884		if (newprio > 19)
   885			newprio = 19;
   886		current->nice = newprio;
   887		return 0;
   888	}
   889	
   890	#endif
   891	
   892	static inline struct task_struct *find_process_by_pid(pid_t pid)
   893	{
   894		struct task_struct *tsk = current;
   895	
   896		if (pid)
   897			tsk = find_task_by_pid(pid);
   898		return tsk;
   899	}
   900	
   901	static int setscheduler(pid_t pid, int policy, 
   902				struct sched_param *param)
   903	{
   904		struct sched_param lp;
   905		struct task_struct *p;
   906		int retval;
   907	
   908		retval = -EINVAL;
   909		if (!param || pid < 0)
   910			goto out_nounlock;
   911	
   912		retval = -EFAULT;
   913		if (copy_from_user(&lp, param, sizeof(struct sched_param)))
   914			goto out_nounlock;
   915	
   916		/*
   917		 * We play safe to avoid deadlocks.
   918		 */
   919		read_lock_irq(&tasklist_lock);
   920		spin_lock(&runqueue_lock);
   921	
   922		p = find_process_by_pid(pid);
   923	
   924		retval = -ESRCH;
   925		if (!p)
   926			goto out_unlock;
   927				
   928		if (policy < 0)
   929			policy = p->policy;
   930		else {
   931			retval = -EINVAL;
   932			if (policy != SCHED_FIFO && policy != SCHED_RR &&
   933					policy != SCHED_OTHER)
   934				goto out_unlock;
   935		}
   936		
   937		/*
   938		 * Valid priorities for SCHED_FIFO and SCHED_RR are 1..99, valid
   939		 * priority for SCHED_OTHER is 0.
   940		 */
   941		retval = -EINVAL;
   942		if (lp.sched_priority < 0 || lp.sched_priority > 99)
   943			goto out_unlock;
   944		if ((policy == SCHED_OTHER) != (lp.sched_priority == 0))
   945			goto out_unlock;
   946	
   947		retval = -EPERM;
   948		if ((policy == SCHED_FIFO || policy == SCHED_RR) && 
   949		    !capable(CAP_SYS_NICE))
   950			goto out_unlock;
   951		if ((current->euid != p->euid) && (current->euid != p->uid) &&
   952		    !capable(CAP_SYS_NICE))
   953			goto out_unlock;
   954	
   955		retval = 0;
   956		p->policy = policy;
   957		p->rt_priority = lp.sched_priority;
   958		if (task_on_runqueue(p))
   959			move_first_runqueue(p);
   960	
   961		current->need_resched = 1;
   962	
   963	out_unlock:
   964		spin_unlock(&runqueue_lock);
   965		read_unlock_irq(&tasklist_lock);
   966	
   967	out_nounlock:
   968		return retval;
   969	}
   970	
   971	asmlinkage long sys_sched_setscheduler(pid_t pid, int policy, 
   972					      struct sched_param *param)
   973	{
   974		return setscheduler(pid, policy, param);
   975	}
   976	
   977	asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param *param)
   978	{
   979		return setscheduler(pid, -1, param);
   980	}
   981	
   982	asmlinkage long sys_sched_getscheduler(pid_t pid)
   983	{
   984		struct task_struct *p;
   985		int retval;
   986	
   987		retval = -EINVAL;
   988		if (pid < 0)
   989			goto out_nounlock;
   990	
   991		retval = -ESRCH;
   992		read_lock(&tasklist_lock);
   993		p = find_process_by_pid(pid);
   994		if (p)
   995			retval = p->policy & ~SCHED_YIELD;
   996		read_unlock(&tasklist_lock);
   997	
   998	out_nounlock:
   999		return retval;
  1000	}
  1001	
  1002	asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param *param)
  1003	{
  1004		struct task_struct *p;
  1005		struct sched_param lp;
  1006		int retval;
  1007	
  1008		retval = -EINVAL;
  1009		if (!param || pid < 0)
  1010			goto out_nounlock;
  1011	
  1012		read_lock(&tasklist_lock);
  1013		p = find_process_by_pid(pid);
  1014		retval = -ESRCH;
  1015		if (!p)
  1016			goto out_unlock;
  1017		lp.sched_priority = p->rt_priority;
  1018		read_unlock(&tasklist_lock);
  1019	
  1020		/*
  1021		 * This one might sleep, we cannot do it with a spinlock held ...
  1022		 */
  1023		retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
  1024	
  1025	out_nounlock:
  1026		return retval;
  1027	
  1028	out_unlock:
  1029		read_unlock(&tasklist_lock);
  1030		return retval;
  1031	}
  1032	
  1033	asmlinkage long sys_sched_yield(void)
  1034	{
  1035		/*
  1036		 * Trick. sched_yield() first counts the number of truly 
  1037		 * 'pending' runnable processes, then returns if it's
  1038		 * only the current processes. (This test does not have
  1039		 * to be atomic.) In threaded applications this optimization
  1040		 * gets triggered quite often.
  1041		 */
  1042	
  1043		int nr_pending = nr_running;
  1044	
  1045	#if CONFIG_SMP
  1046		int i;
  1047	
  1048		// Subtract non-idle processes running on other CPUs.
  1049		for (i = 0; i < smp_num_cpus; i++) {
  1050			int cpu = cpu_logical_map(i);
  1051			if (aligned_data[cpu].schedule_data.curr != idle_task(cpu))
  1052				nr_pending--;
  1053		}
  1054	#else
  1055		// on UP this process is on the runqueue as well
  1056		nr_pending--;
  1057	#endif
  1058		if (nr_pending) {
  1059			/*
  1060			 * This process can only be rescheduled by us,
  1061			 * so this is safe without any locking.
  1062			 */
  1063			if (current->policy == SCHED_OTHER)
  1064				current->policy |= SCHED_YIELD;
  1065			current->need_resched = 1;
  1066	
  1067			spin_lock_irq(&runqueue_lock);
  1068			move_last_runqueue(current);
  1069			spin_unlock_irq(&runqueue_lock);
  1070		}
  1071		return 0;
  1072	}
  1073	
  1074	asmlinkage long sys_sched_get_priority_max(int policy)
  1075	{
  1076		int ret = -EINVAL;
  1077	
  1078		switch (policy) {
  1079		case SCHED_FIFO:
  1080		case SCHED_RR:
  1081			ret = 99;
  1082			break;
  1083		case SCHED_OTHER:
  1084			ret = 0;
  1085			break;
  1086		}
  1087		return ret;
  1088	}
  1089	
  1090	asmlinkage long sys_sched_get_priority_min(int policy)
  1091	{
  1092		int ret = -EINVAL;
  1093	
  1094		switch (policy) {
  1095		case SCHED_FIFO:
  1096		case SCHED_RR:
  1097			ret = 1;
  1098			break;
  1099		case SCHED_OTHER:
  1100			ret = 0;
  1101		}
  1102		return ret;
  1103	}
  1104	
  1105	asmlinkage long sys_sched_rr_get_interval(pid_t pid, struct timespec *interval)
  1106	{
  1107		struct timespec t;
  1108		struct task_struct *p;
  1109		int retval = -EINVAL;
  1110	
  1111		if (pid < 0)
  1112			goto out_nounlock;
  1113	
  1114		retval = -ESRCH;
  1115		read_lock(&tasklist_lock);
  1116		p = find_process_by_pid(pid);
  1117		if (p)
  1118			jiffies_to_timespec(p->policy & SCHED_FIFO ? 0 : NICE_TO_TICKS(p->nice),
  1119					    &t);
  1120		read_unlock(&tasklist_lock);
  1121		if (p)
  1122			retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
  1123	out_nounlock:
  1124		return retval;
  1125	}
  1126	
  1127	static void show_task(struct task_struct * p)
  1128	{
  1129		unsigned long free = 0;
  1130		int state;
  1131		static const char * stat_nam[] = { "R", "S", "D", "Z", "T", "W" };
  1132	
  1133		printk("%-13.13s ", p->comm);
  1134		state = p->state ? ffz(~p->state) + 1 : 0;
  1135		if (((unsigned) state) < sizeof(stat_nam)/sizeof(char *))
  1136			printk(stat_nam[state]);
  1137		else
  1138			printk(" ");
  1139	#if (BITS_PER_LONG == 32)
  1140		if (p == current)
  1141			printk(" current  ");
  1142		else
  1143			printk(" %08lX ", thread_saved_pc(&p->thread));
  1144	#else
  1145		if (p == current)
  1146			printk("   current task   ");
  1147		else
  1148			printk(" %016lx ", thread_saved_pc(&p->thread));
  1149	#endif
  1150		{
  1151			unsigned long * n = (unsigned long *) (p+1);
  1152			while (!*n)
  1153				n++;
  1154			free = (unsigned long) n - (unsigned long)(p+1);
  1155		}
  1156		printk("%5lu %5d %6d ", free, p->pid, p->p_pptr->pid);
  1157		if (p->p_cptr)
  1158			printk("%5d ", p->p_cptr->pid);
  1159		else
  1160			printk("      ");
  1161		if (p->p_ysptr)
  1162			printk("%7d", p->p_ysptr->pid);
  1163		else
  1164			printk("       ");
  1165		if (p->p_osptr)
  1166			printk(" %5d", p->p_osptr->pid);
  1167		else
  1168			printk("      ");
  1169		if (!p->mm)
  1170			printk(" (L-TLB)\n");
  1171		else
  1172			printk(" (NOTLB)\n");
  1173	
  1174		{
  1175			extern void show_trace_task(struct task_struct *tsk);
  1176			show_trace_task(p);
  1177		}
  1178	}
  1179	
  1180	char * render_sigset_t(sigset_t *set, char *buffer)
  1181	{
  1182		int i = _NSIG, x;
  1183		do {
  1184			i -= 4, x = 0;
  1185			if (sigismember(set, i+1)) x |= 1;
  1186			if (sigismember(set, i+2)) x |= 2;
  1187			if (sigismember(set, i+3)) x |= 4;
  1188			if (sigismember(set, i+4)) x |= 8;
  1189			*buffer++ = (x < 10 ? '0' : 'a' - 10) + x;
  1190		} while (i >= 4);
  1191		*buffer = 0;
  1192		return buffer;
  1193	}
  1194	
  1195	void show_state(void)
  1196	{
  1197		struct task_struct *p;
  1198	
  1199	#if (BITS_PER_LONG == 32)
  1200		printk("\n"
  1201		       "                         free                        sibling\n");
  1202		printk("  task             PC    stack   pid father child younger older\n");
  1203	#else
  1204		printk("\n"
  1205		       "                                 free                        sibling\n");
  1206		printk("  task                 PC        stack   pid father child younger older\n");
  1207	#endif
  1208		read_lock(&tasklist_lock);
  1209		for_each_task(p) {
  1210			/*
  1211			 * reset the NMI-timeout, listing all files on a slow
  1212			 * console might take alot of time:
  1213			 */
  1214			touch_nmi_watchdog();
  1215			show_task(p);
  1216		}
  1217		read_unlock(&tasklist_lock);
  1218	}
  1219	
  1220	/**
  1221	 * reparent_to_init() - Reparent the calling kernel thread to the init task.
  1222	 *
  1223	 * If a kernel thread is launched as a result of a system call, or if
  1224	 * it ever exits, it should generally reparent itself to init so that
  1225	 * it is correctly cleaned up on exit.
  1226	 *
  1227	 * The various task state such as scheduling policy and priority may have
  1228	 * been inherited fro a user process, so we reset them to sane values here.
  1229	 *
  1230	 * NOTE that reparent_to_init() gives the caller full capabilities.
  1231	 */
  1232	void reparent_to_init(void)
  1233	{
  1234		struct task_struct *this_task = current;
  1235	
  1236		write_lock_irq(&tasklist_lock);
  1237	
  1238		/* Reparent to init */
  1239		REMOVE_LINKS(this_task);
  1240		this_task->p_pptr = child_reaper;
  1241		this_task->p_opptr = child_reaper;
  1242		SET_LINKS(this_task);
  1243	
  1244		/* Set the exit signal to SIGCHLD so we signal init on exit */
  1245		this_task->exit_signal = SIGCHLD;
  1246	
  1247		/* We also take the runqueue_lock while altering task fields
  1248		 * which affect scheduling decisions */
  1249		spin_lock(&runqueue_lock);
  1250	
  1251		this_task->ptrace = 0;
  1252		this_task->nice = DEF_NICE;
  1253		this_task->policy = SCHED_OTHER;
  1254		/* cpus_allowed? */
  1255		/* rt_priority? */
  1256		/* signals? */
  1257		this_task->cap_effective = CAP_INIT_EFF_SET;
  1258		this_task->cap_inheritable = CAP_INIT_INH_SET;
  1259		this_task->cap_permitted = CAP_FULL_SET;
  1260		this_task->keep_capabilities = 0;
  1261		memcpy(this_task->rlim, init_task.rlim, sizeof(*(this_task->rlim)));
  1262		this_task->user = INIT_USER;
  1263	
  1264		spin_unlock(&runqueue_lock);
  1265		write_unlock_irq(&tasklist_lock);
  1266	}
  1267	
  1268	/*
  1269	 *	Put all the gunge required to become a kernel thread without
  1270	 *	attached user resources in one place where it belongs.
  1271	 */
  1272	
  1273	void daemonize(void)
  1274	{
  1275		struct fs_struct *fs;
  1276	
  1277	
  1278		/*
  1279		 * If we were started as result of loading a module, close all of the
  1280		 * user space pages.  We don't need them, and if we didn't close them
  1281		 * they would be locked into memory.
  1282		 */
  1283		exit_mm(current);
  1284	
  1285		current->session = 1;
  1286		current->pgrp = 1;
  1287		current->tty = NULL;
  1288	
  1289		/* Become as one with the init task */
  1290	
  1291		exit_fs(current);	/* current->fs->count--; */
  1292		fs = init_task.fs;
  1293		current->fs = fs;
  1294		atomic_inc(&fs->count);
  1295	 	exit_files(current);
  1296		current->files = init_task.files;
  1297		atomic_inc(&current->files->count);
  1298	}
  1299	
  1300	extern unsigned long wait_init_idle;
  1301	
  1302	void __init init_idle(void)
  1303	{
  1304		struct schedule_data * sched_data;
  1305		sched_data = &aligned_data[smp_processor_id()].schedule_data;
  1306	
  1307		if (current != &init_task && task_on_runqueue(current)) {
  1308			printk("UGH! (%d:%d) was on the runqueue, removing.\n",
  1309				smp_processor_id(), current->pid);
  1310			del_from_runqueue(current);
  1311		}
  1312		sched_data->curr = current;
  1313		sched_data->last_schedule = get_cycles();
  1314		clear_bit(current->processor, &wait_init_idle);
  1315	}
  1316	
  1317	extern void init_timervecs (void);
  1318	
  1319	void __init sched_init(void)
  1320	{
  1321		/*
  1322		 * We have to do a little magic to get the first
  1323		 * process right in SMP mode.
  1324		 */
  1325		int cpu = smp_processor_id();
  1326		int nr;
  1327	
  1328		init_task.processor = cpu;
  1329	
  1330		for(nr = 0; nr < PIDHASH_SZ; nr++)
  1331			pidhash[nr] = NULL;
  1332	
  1333		init_timervecs();
  1334	
  1335		init_bh(TIMER_BH, timer_bh);
  1336		init_bh(TQUEUE_BH, tqueue_bh);
  1337		init_bh(IMMEDIATE_BH, immediate_bh);
  1338	
  1339		/*
  1340		 * The boot idle thread does lazy MMU switching as well:
  1341		 */
  1342		atomic_inc(&init_mm.mm_count);
  1343		enter_lazy_tlb(&init_mm, current, cpu);
  1344	}
