Merge to Fedora kernel-2.6.18-1.2224_FC5-vs2.0.2.2-rc4 patched with stable patch...
[linux-2.6.git] / mm / oom_kill.c
1 /*
2  *  linux/mm/oom_kill.c
3  * 
4  *  Copyright (C)  1998,2000  Rik van Riel
5  *      Thanks go out to Claus Fischer for some serious inspiration and
6  *      for goading me into coding this file...
7  *
8  *  The routines in this file are used to kill a process when
9  *  we're seriously out of memory. This gets called from __alloc_pages()
10  *  in mm/page_alloc.c when we really run out of memory.
11  *
12  *  Since we won't call these routines often (on a well-configured
13  *  machine) this file will double as a 'coding guide' and a signpost
14  *  for newbie kernel hackers. It features several pointers to major
15  *  kernel subsystems and hints as to where to find out what things do.
16  */
17
18 #include <linux/config.h>
19 #include <linux/mm.h>
20 #include <linux/sched.h>
21 #include <linux/swap.h>
22 #include <linux/timex.h>
23 #include <linux/jiffies.h>
24 #include <linux/cpuset.h>
25
26 int sysctl_panic_on_oom;
27 /* #define DEBUG */
28
29 /**
30  * badness - calculate a numeric value for how bad this task has been
31  * @p: task struct of which task we should calculate
32  * @uptime: current uptime in seconds
33  *
34  * The formula used is relatively simple and documented inline in the
35  * function. The main rationale is that we want to select a good task
36  * to kill when we run out of memory.
37  *
38  * Good in this context means that:
39  * 1) we lose the minimum amount of work done
40  * 2) we recover a large amount of memory
41  * 3) we don't kill anything innocent of eating tons of memory
42  * 4) we want to kill the minimum amount of processes (one)
43  * 5) we try to kill the process the user expects us to kill, this
44  *    algorithm has been meticulously tuned to meet the principle
45  *    of least surprise ... (be careful when you change it)
46  */
47
48 unsigned long badness(struct task_struct *p, unsigned long uptime)
49 {
50         unsigned long points, cpu_time, run_time, s;
51         struct mm_struct *mm;
52         struct task_struct *child;
53
54         task_lock(p);
55         mm = p->mm;
56         if (!mm) {
57                 task_unlock(p);
58                 return 0;
59         }
60
61         /*
62          * swapoff can easily use up all memory, so kill those first.
63          */
64         if (p->flags & PF_SWAPOFF)
65                 return ULONG_MAX;
66
67         /*
68          * The memory size of the process is the basis for the badness.
69          */
70         points = mm->total_vm;
71
72         /*
73          * After this unlock we can no longer dereference local variable `mm'
74          */
75         task_unlock(p);
76
77         /* FIXME: add vserver badness ;) */
78
79         /*
80          * Processes which fork a lot of child processes are likely
81          * a good choice. We add half the vmsize of the children if they
82          * have an own mm. This prevents forking servers to flood the
83          * machine with an endless amount of children. In case a single
84          * child is eating the vast majority of memory, adding only half
85          * to the parents will make the child our kill candidate of choice.
86          */
87         list_for_each_entry(child, &p->children, sibling) {
88                 task_lock(child);
89                 if (child->mm != mm && child->mm)
90                         points += child->mm->total_vm/2 + 1;
91                 task_unlock(child);
92         }
93
94         /*
95          * CPU time is in tens of seconds and run time is in thousands
96          * of seconds. There is no particular reason for this other than
97          * that it turned out to work very well in practice.
98          */
99         cpu_time = (cputime_to_jiffies(p->utime) + cputime_to_jiffies(p->stime))
100                 >> (SHIFT_HZ + 3);
101
102         if (uptime >= p->start_time.tv_sec)
103                 run_time = (uptime - p->start_time.tv_sec) >> 10;
104         else
105                 run_time = 0;
106
107         s = int_sqrt(cpu_time);
108         if (s)
109                 points /= s;
110         s = int_sqrt(int_sqrt(run_time));
111         if (s)
112                 points /= s;
113
114         /*
115          * Niced processes are most likely less important, so double
116          * their badness points.
117          */
118         if (task_nice(p) > 0)
119                 points *= 2;
120
121         /*
122          * Superuser processes are usually more important, so we make it
123          * less likely that we kill those.
124          */
125         if (cap_t(p->cap_effective) & CAP_TO_MASK(CAP_SYS_ADMIN) ||
126                                 p->uid == 0 || p->euid == 0)
127                 points /= 4;
128
129         /*
130          * We don't want to kill a process with direct hardware access.
131          * Not only could that mess up the hardware, but usually users
132          * tend to only have this flag set on applications they think
133          * of as important.
134          */
135         if (cap_t(p->cap_effective) & CAP_TO_MASK(CAP_SYS_RAWIO))
136                 points /= 4;
137
138         /*
139          * If p's nodes don't overlap ours, it may still help to kill p
140          * because p may have allocated or otherwise mapped memory on
141          * this node before. However it will be less likely.
142          */
143         if (!cpuset_excl_nodes_overlap(p))
144                 points /= 8;
145
146         /*
147          * Adjust the score by oomkilladj.
148          */
149         if (p->oomkilladj) {
150                 if (p->oomkilladj > 0)
151                         points <<= p->oomkilladj;
152                 else
153                         points >>= -(p->oomkilladj);
154         }
155
156 #ifdef DEBUG
157         printk(KERN_DEBUG "OOMkill: task %d (%s) got %d points\n",
158         p->pid, p->comm, points);
159 #endif
160         return points;
161 }
162
163 #if defined(CONFIG_OOM_PANIC) && defined(CONFIG_OOM_KILLER)
164 #warning Only define OOM_PANIC or OOM_KILLER; not both
165 #endif
166
167 #ifdef CONFIG_OOM_KILLER
168 /*
169  * Types of limitations to the nodes from which allocations may occur
170  */
171 #define CONSTRAINT_NONE 1
172 #define CONSTRAINT_MEMORY_POLICY 2
173 #define CONSTRAINT_CPUSET 3
174
175 /*
176  * Determine the type of allocation constraint.
177  */
178 static inline int constrained_alloc(struct zonelist *zonelist, gfp_t gfp_mask)
179 {
180 #ifdef CONFIG_NUMA
181         struct zone **z;
182         nodemask_t nodes = node_online_map;
183
184         for (z = zonelist->zones; *z; z++)
185                 if (cpuset_zone_allowed(*z, gfp_mask))
186                         node_clear((*z)->zone_pgdat->node_id,
187                                         nodes);
188                 else
189                         return CONSTRAINT_CPUSET;
190
191         if (!nodes_empty(nodes))
192                 return CONSTRAINT_MEMORY_POLICY;
193 #endif
194
195         return CONSTRAINT_NONE;
196 }
197
198 /*
199  * Simple selection loop. We chose the process with the highest
200  * number of 'points'. We expect the caller will lock the tasklist.
201  *
202  * (not docbooked, we don't want this one cluttering up the manual)
203  */
204 static struct task_struct *select_bad_process(unsigned long *ppoints)
205 {
206         struct task_struct *g, *p;
207         struct task_struct *chosen = NULL;
208         struct timespec uptime;
209         *ppoints = 0;
210
211         do_posix_clock_monotonic_gettime(&uptime);
212         do_each_thread(g, p) {
213                 unsigned long points;
214                 int releasing;
215
216                 /* skip kernel threads */
217                 if (!p->mm)
218                         continue;
219
220                 /* skip the init task with pid == 1 */
221                 if (p->pid == 1)
222                         continue;
223                 /*
224                  * This is in the process of releasing memory so wait for it
225                  * to finish before killing some other task by mistake.
226                  *
227                  * However, if p is the current task, we allow the 'kill' to
228                  * go ahead if it is exiting: this will simply set TIF_MEMDIE,
229                  * which will allow it to gain access to memory reserves in
230                  * the process of exiting and releasing its resources.
231                  * Otherwise we could get an OOM deadlock.
232                  */
233                 releasing = test_tsk_thread_flag(p, TIF_MEMDIE) ||
234                                                 p->flags & PF_EXITING;
235                 if (releasing) {
236                         /* PF_DEAD tasks have already released their mm */
237                         if (p->flags & PF_DEAD)
238                                 continue;
239                         if (p->flags & PF_EXITING && p == current) {
240                                 chosen = p;
241                                 *ppoints = ULONG_MAX;
242                                 break;
243                         }
244                         return ERR_PTR(-1UL);
245                 }
246                 if (p->oomkilladj == OOM_DISABLE)
247                         continue;
248
249                 points = badness(p, uptime.tv_sec);
250                 if (points > *ppoints || !chosen) {
251                         chosen = p;
252                         *ppoints = points;
253                 }
254         } while_each_thread(g, p);
255         return chosen;
256 }
257
258 /**
259  * We must be careful though to never send SIGKILL a process with
260  * CAP_SYS_RAW_IO set, send SIGTERM instead (but it's unlikely that
261  * we select a process with CAP_SYS_RAW_IO set).
262  */
263 static void __oom_kill_task(struct task_struct *p, const char *message)
264 {
265         if (p->pid == 1) {
266                 WARN_ON(1);
267                 printk(KERN_WARNING "tried to kill init!\n");
268                 return;
269         }
270
271         task_lock(p);
272         if (!p->mm || p->mm == &init_mm) {
273                 WARN_ON(1);
274                 printk(KERN_WARNING "tried to kill an mm-less task!\n");
275                 task_unlock(p);
276                 return;
277         }
278         task_unlock(p);
279         if (message) 
280                 printk(KERN_ERR "%s: Killed process %d (%s).\n",
281                                 message, p->pid, p->comm);
282
283         /*
284          * We give our sacrificial lamb high priority and access to
285          * all the memory it needs. That way it should be able to
286          * exit() and clear out its resources quickly...
287          */
288         p->time_slice = HZ;
289         set_tsk_thread_flag(p, TIF_MEMDIE);
290
291         force_sig(SIGKILL, p);
292 }
293
294 static int oom_kill_task(struct task_struct *p, const char *message)
295 {
296         struct mm_struct *mm;
297         struct task_struct *g, *q;
298
299         mm = p->mm;
300
301         /* WARNING: mm may not be dereferenced since we did not obtain its
302          * value from get_task_mm(p).  This is OK since all we need to do is
303          * compare mm to q->mm below.
304          *
305          * Furthermore, even if mm contains a non-NULL value, p->mm may
306          * change to NULL at any time since we do not hold task_lock(p).
307          * However, this is of no concern to us.
308          */
309
310         if (mm == NULL || mm == &init_mm)
311                 return 1;
312
313         __oom_kill_task(p, message);
314         /*
315          * kill all processes that share the ->mm (i.e. all threads),
316          * but are in a different thread group
317          */
318         do_each_thread(g, q)
319                 if (q->mm == mm && q->tgid != p->tgid)
320                         __oom_kill_task(q, message);
321         while_each_thread(g, q);
322
323         return 0;
324 }
325
326 static int oom_kill_process(struct task_struct *p, unsigned long points,
327                 const char *message)
328 {
329         struct task_struct *c;
330         struct list_head *tsk;
331
332         /*
333          * If the task is already exiting, don't alarm the sysadmin or kill
334          * its children or threads, just set TIF_MEMDIE so it can die quickly
335          */
336         if (p->flags & PF_EXITING) {
337                 __oom_kill_task(p, NULL);
338                 return 0;
339         }
340
341         /* Try to kill a child first */
342         list_for_each(tsk, &p->children) {
343                 c = list_entry(tsk, struct task_struct, sibling);
344                 if (c->mm == p->mm)
345                         continue;
346                 if (!oom_kill_task(c, message))
347                         return 0;
348         }
349         return oom_kill_task(p, message);
350 }
351
352 int should_oom_kill(void)
353 {
354         static spinlock_t oom_lock = SPIN_LOCK_UNLOCKED;
355         static unsigned long first, last, count, lastkill;
356         unsigned long now, since;
357         int ret = 0;
358
359         spin_lock(&oom_lock);
360         now = jiffies;
361         since = now - last;
362         last = now;
363
364         /*
365          * If it's been a long time since last failure,
366          * we're not oom.
367          */
368         if (since > 5*HZ)
369                 goto reset;
370
371         /*
372          * If we haven't tried for at least one second,
373          * we're not really oom.
374          */
375         since = now - first;
376         if (since < HZ)
377                 goto out_unlock;
378
379         /*
380          * If we have gotten only a few failures,
381          * we're not really oom.
382          */
383         if (++count < 10)
384                 goto out_unlock;
385
386         /*
387          * If we just killed a process, wait a while
388          * to give that task a chance to exit. This
389          * avoids killing multiple processes needlessly.
390          */
391         since = now - lastkill;
392         if (since < HZ*5)
393                 goto out_unlock;
394
395         /*
396          * Ok, really out of memory. Kill something.
397          */
398         lastkill = now;
399         ret = 1;
400
401 reset:
402 /*
403  * We dropped the lock above, so check to be sure the variable
404  * first only ever increases to prevent false OOM's.
405  */
406         if (time_after(now, first))
407                 first = now;
408         count = 0;
409
410 out_unlock:
411         spin_unlock(&oom_lock);
412         return ret;
413 }
414
415 /**
416  * out_of_memory - kill the "best" process when we run out of memory
417  *
418  * If we run out of memory, we have the choice between either
419  * killing a random task (bad), letting the system crash (worse)
420  * OR try to be smart about which process to kill. Note that we
421  * don't have to be perfect here, we just have to be good.
422  */
423 void out_of_memory(struct zonelist *zonelist, gfp_t gfp_mask, int order)
424 {
425         struct task_struct *p;
426         unsigned long points = 0;
427
428         if (printk_ratelimit()) {
429                 printk(KERN_WARNING "%s invoked oom-killer: "
430                 "gfp_mask=0x%x, order=%d, oomkilladj=%d\n",
431                 current->comm, gfp_mask, order, current->oomkilladj);
432                 dump_stack();
433                 show_mem();
434         }
435
436         if (!should_oom_kill())
437                 return;
438
439         cpuset_lock();
440         read_lock(&tasklist_lock);
441
442         /*
443          * Check if there were limitations on the allocation (only relevant for
444          * NUMA) that may require different handling.
445          */
446         switch (constrained_alloc(zonelist, gfp_mask)) {
447         case CONSTRAINT_MEMORY_POLICY:
448                 oom_kill_process(current, points,
449                                 "No available memory (MPOL_BIND)");
450                 break;
451
452         case CONSTRAINT_CPUSET:
453                 oom_kill_process(current, points,
454                                 "No available memory in cpuset");
455                 break;
456
457         case CONSTRAINT_NONE:
458                 if (sysctl_panic_on_oom)
459                         panic("out of memory. panic_on_oom is selected\n");
460 retry:
461                 /*
462                  * Rambo mode: Shoot down a process and hope it solves whatever
463                  * issues we may have.
464                  */
465                 p = select_bad_process(&points);
466
467                 if (PTR_ERR(p) == -1UL)
468                         goto out;
469
470                 /* Found nothing?!?! Either we hang forever, or we panic. */
471                 if (!p) {
472                         read_unlock(&tasklist_lock);
473                         cpuset_unlock();
474                         panic("Out of memory and no killable processes...\n");
475                 }
476
477                 if (oom_kill_process(p, points, "Out of memory"))
478                         goto retry;
479
480                 break;
481         }
482
483 out:
484         read_unlock(&tasklist_lock);
485         cpuset_unlock();
486
487         /*
488          * Give "p" a good chance of killing itself before we
489          * retry to allocate memory unless "p" is current
490          */
491         if (!test_thread_flag(TIF_MEMDIE))
492                 schedule_timeout_uninterruptible(1);
493 }
494 #endif /* CONFIG_OOM_KILLER */
495
496 #ifdef CONFIG_OOM_PANIC
497 /**
498  * out_of_memory - panic if the system out of memory?
499  */
500 void out_of_memory(struct zonelist *zonelist, gfp_t gfp_mask, int order)
501 {
502         /*
503          * oom_lock protects out_of_memory()'s static variables.
504          * It's a global lock; this is not performance-critical.
505          */
506         static spinlock_t oom_lock = SPIN_LOCK_UNLOCKED;
507         static unsigned long count;
508
509         spin_lock(&oom_lock);
510
511         /*
512          * If we have gotten only a few failures,
513          * we're not really oom. 
514          */
515         if (++count >= 10) {
516                 /*
517                  * Ok, really out of memory. Panic.
518                  */
519
520                 printk("oom-killer: gfp_mask=0x%x\n", gfp_mask);
521                 show_free_areas();
522
523                 panic("Out Of Memory");
524         }
525         spin_unlock(&oom_lock);
526 }
527 #endif /*  CONFIG_OOM_PANIC */