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