Skip to contentSkip to conversation

Fix itimer/many thread hang.

PATCH In review Frank Mayhar 4 participants 11 messages Sep 8, 2008 – Sep 10, 2008

Subsystems (7)
lore
Share & tools
lore
#0 lore raw

PATCH 1/1 Fix itimer/many thread hang.

Overview

This patch reworks the handling of POSIX CPU timers, including the ITIMER_PROF, ITIMER_VIRT timers and rlimit handling. It was put together with the help of Roland McGrath, the owner and original writer of this code.

The problem we ran into, and the reason for this rework, has to do with using a profiling timer in a process with a large number of threads. It appears that the performance of the old implementation of run_posix_cpu_timers() was at least O(n*3) (where "n" is the number of threads in a process) or worse. Everything is fine with an increasing number of threads until the time taken for that routine to run becomes the same as or greater than the tick time, at which point things degrade rather quickly.

This patch fixes bug 9906, "Weird hang with NPTL and SIGPROF." And thanks very much to Roland McGrath, without whom this patch wouldn't exist in this form.

Code Changes

This rework corrects the implementation of run_posix_cpu_timers() to make it run in constant time for a particular machine. (Performance may vary between one machine and another depending upon whether the kernel is built as single- or multiprocessor and, in the latter case, depending upon the number of running processors.) To do this, at each tick we now update fields in signal_struct as well as task_struct. The run_posix_cpu_timers() function uses those fields to make its decisions.

We define a new structure, "task_cputime," to contain user, system and scheduler times and use these in appropriate places:

struct task_cputime {
	cputime_t utime;
	cputime_t stime;
	unsigned long long sum_exec_runtime;
};

This is included in the structure "thread_group_cputime," which is a new substructure of signal_struct and which varies for uniprocessor versus multiprocessor kernels. For uniprocessor kernels, it uses "task_cputime" as a simple substructure, while for multiprocessor kernels it is a pointer:

struct thread_group_cputime {
	struct task_cputime totals;
};
struct thread_group_cputime {
	struct task_cputime *totals;
};

We also add a new task_cputime substructure directly to signal_struct, to cache the earliest expiration of process-wide timers, and task_cputime also replaces the it_*_expires fields of task_struct (used for earliest expiration of thread timers). The "thread_group_cputime" structure contains process-wide timers that are updated via account_user_time() and friends. In the non-SMP case the structure is a simple aggregator; unfortunately in the SMP case that simplicity was not achievable due to cache-line contention between CPUs (in one measured case performance was actually _worse_ on a 16-cpu system than the same test on a 4-cpu system, due to this contention). For SMP, the thread_group_cputime counters are maintained as a per-cpu structure allocated using alloc_percpu(). The timer functions update only the timer field in the structure corresponding to the running CPU, obtained using per_cpu_ptr().

We define a set of inline functions in sched.h that we use to maintain the thread_group_cputime structure and hide the differences between UP and SMP implementations from the rest of the kernel. The thread_group_cputime_init() function initializes the thread_group_cputime structure for the given task. The thread_group_cputime_alloc() is a no-op for UP; for SMP it calls the out-of-line function thread_group_cputime_alloc_smp() to allocate and fill in the per-cpu structures and fields. The thread_group_cputime_free() function, also a no-op for UP, in SMP frees the per-cpu structures. The thread_group_cputime_clone_thread() function (also a UP no-op) for SMP calls thread_group_cputime_alloc() if the per-cpu structures haven't yet been allocated. The thread_group_cputime() function fills the task_cputime structure it is passed with the contents of the thread_group_cputime fields; in UP it's that simple but in SMP it must also safely check that tsk->signal is non-NULL (if it is it just uses the appropriate fields of task_struct) and, if so, sums the per-cpu values for each online CPU. Finally, the three functions account_group_user_time(), account_group_system_time() and account_group_exec_runtime() are used by timer functions to update the respective fields of the thread_group_cputime structure.

Non-SMP operation is trivial and will not be mentioned further.

The per-cpu structure is always allocated when a task creates its first new thread, via a call to thread_group_cputime_clone_thread() from copy_signal(). It is freed at process exit via a call to thread_group_cputime_free() from cleanup_signal().

All functions that formerly summed utime/stime/sum_sched_runtime values from from all threads in the thread group now use thread_group_cputime() to snapshot the values in the thread_group_cputime structure or the values in the task structure itself if the per-cpu structure hasn't been allocated.

Finally, the code in kernel/posix-cpu-timers.c has changed quite a bit. The run_posix_cpu_timers() function has been split into a fast path and a slow path; the former safely checks whether there are any expired thread timers and, if not, just returns, while the slow path does the heavy lifting. With the dedicated thread group fields, timers are no longer "rebalanced" and the process_timer_rebalance() function and related code has gone away. All summing loops are gone and all code that used them now uses the thread_group_cputime() inline. When process-wide timers are set, the new task_cputime structure in signal_struct is used to cache the earliest expiration; this is checked in the fast path.

Performance

The fix appears not to add significant overhead to existing operations. It generally performs the same as the current code except in two cases, one in which it performs slightly worse (Case 5 below) and one in which it performs very significantly better (Case 2 below). Overall it's a wash except in those two cases.

I've since done somewhat more involved testing on a dual-core Opteron system.

Case 1: With no itimer running, for a test with 100,000 threads, the fixed
kernel took 1428.5 seconds, 513 seconds more than the unfixed system, all of which was spent in the system. There were twice as many voluntary context switches with the fix as without it.

Case 2: With an itimer running at .01 second ticks and 4000 threads (the most
an unmodified kernel can handle), the fixed kernel ran the test in eight percent of the time (5.8 seconds as opposed to 70 seconds) and had better tick accuracy (.012 seconds per tick as opposed to .023 seconds per tick).

Case 3: A 4000-thread test with an initial timer tick of .01 second and an
interval of 10,000 seconds (i.e. a timer that ticks only once) had very nearly the same performance in both cases: 6.3 seconds elapsed for the fixed kernel versus 5.5 seconds for the unfixed kernel.

With fewer threads (eight in these tests), the Case 1 test ran in essentially the same time on both the modified and unmodified kernels (5.2 seconds versus 5.8 seconds). The Case 2 test ran in about the same time as well, 5.9 seconds versus 5.4 seconds but again with much better tick accuracy, .013 seconds per tick versus .025 seconds per tick for the unmodified kernel.

Since the fix affected the rlimit code, I also tested soft and hard CPU limits.

Case 4: With a hard CPU limit of 20 seconds and eight threads (and an itimer
running), the modified kernel was very slightly favored in that while it killed the process in 19.997 seconds of CPU time (5.002 seconds of wall time), only .003 seconds of that was system time, the rest was user time. The unmodified kernel killed the process in 20.001 seconds of CPU (5.014 seconds of wall time) of which .016 seconds was system time. Really, though, the results were too close to call. The results were essentially the same with no itimer running.

Case 5: With a soft limit of 20 seconds and a hard limit of 2000 seconds
(where the hard limit would never be reached) and an itimer running, the modified kernel exhibited worse tick accuracy than the unmodified
kernel: .050 seconds/tick versus .028 seconds/tick. Otherwise, performance was almost indistinguishable. With no itimer running this test exhibited virtually identical behavior and times in both cases.

In times past I did some limited performance testing. those results are below.

On a four-cpu Opteron system without this fix, a sixteen-thread test executed in 3569.991 seconds, of which user was 3568.435s and system was 1.556s. On the same system with the fix, user and elapsed time were about the same, but system time dropped to 0.007 seconds. Performance with eight, four and one thread were comparable. Interestingly, the timer ticks with the fix seemed more accurate: The sixteen-thread test with the fix received 149543 ticks for 0.024 seconds per tick, while the same test without the fix received 58720 for 0.061 seconds per tick. Both cases were configured for an interval of 0.01 seconds. Again, the other tests were comparable. Each thread in this test computed the primes up to 25,000,000.

I also did a test with a large number of threads, 100,000 threads, which is impossible without the fix. In this case each thread computed the primes only up to 10,000 (to make the runtime manageable). System time dominated, at 1546.968 seconds out of a total 2176.906 seconds (giving a user time of 629.938s). It received 147651 ticks for 0.015 seconds per tick, still quite accurate. There is obviously no comparable test without the fix.

 fs/binfmt_elf.c              |   19 +--
 fs/proc/array.c              |    8 +-
 include/linux/posix-timers.h |    2 +
 include/linux/sched.h        |  286 +++++++++++++++++++++++++++--
 include/linux/time.h         |    3 +
 kernel/compat.c              |   53 ++----
 kernel/exit.c                |   19 +-
 kernel/fork.c                |   88 +++++----
 kernel/itimer.c              |   33 +---
 kernel/posix-cpu-timers.c    |  418 ++++++++++++++++++++----------------------
 kernel/sched.c               |   53 +++++-
 kernel/sched_fair.c          |    1 +
 kernel/sched_rt.c            |    4 +-
 kernel/signal.c              |    8 +-
 kernel/sys.c                 |   75 +++-----
 security/selinux/hooks.c     |    9 +-
 16 files changed, 653 insertions(+), 426 deletions(-)
fs/binfmt_elf.c +7 -12
index 655ed8d..a8635f6 100644
@@ -1333,20 +1333,15 @@ static void fill_prstatus(struct elf_prstatus *prstatus,
 	prstatus->pr_pgrp = task_pgrp_vnr(p);
 	prstatus->pr_sid = task_session_vnr(p);
 	if (thread_group_leader(p)) {
+		struct task_cputime cputime;
+
 		/*
-		 * This is the record for the group leader.  Add in the
-		 * cumulative times of previous dead threads.  This total
-		 * won't include the time of each live thread whose state
-		 * is included in the core dump.  The final total reported
-		 * to our parent process when it calls wait4 will include
-		 * those sums as well as the little bit more time it takes
-		 * this and each other thread to finish dying after the
-		 * core dump synchronization phase.
+		 * This is the record for the group leader.  It shows the
+		 * group-wide total, not its individual thread total.
 		 */
-		cputime_to_timeval(cputime_add(p->utime, p->signal->utime),
-				   &prstatus->pr_utime);
-		cputime_to_timeval(cputime_add(p->stime, p->signal->stime),
-				   &prstatus->pr_stime);
+		thread_group_cputime(p, &cputime);
+		cputime_to_timeval(cputime.utime, &prstatus->pr_utime);
+		cputime_to_timeval(cputime.stime, &prstatus->pr_stime);
 	} else {
 		cputime_to_timeval(p->utime, &prstatus->pr_utime);
 		cputime_to_timeval(p->stime, &prstatus->pr_stime);
fs/proc/array.c +4 -4
index 71c9be5..933953c 100644
@@ -395,20 +395,20 @@ static int do_task_stat(struct seq_file *m, struct pid_namespace *ns,
 
 		/* add up live thread stats at the group level */
 		if (whole) {
+			struct task_cputime cputime;
 			struct task_struct *t = task;
 			do {
 				min_flt += t->min_flt;
 				maj_flt += t->maj_flt;
-				utime = cputime_add(utime, task_utime(t));
-				stime = cputime_add(stime, task_stime(t));
 				gtime = cputime_add(gtime, task_gtime(t));
 				t = next_thread(t);
 			} while (t != task);
 
 			min_flt += sig->min_flt;
 			maj_flt += sig->maj_flt;
-			utime = cputime_add(utime, sig->utime);
-			stime = cputime_add(stime, sig->stime);
+			thread_group_cputime(task, &cputime);
+			utime = cputime.utime;
+			stime = cputime.stime;
 			gtime = cputime_add(gtime, sig->gtime);
 		}
 
include/linux/posix-timers.h +2 -0
index a7dd38f..f9d8e9e 100644
@@ -115,4 +115,6 @@ void set_process_cpu_timer(struct task_struct *task, unsigned int clock_idx,
 
 long clock_nanosleep_restart(struct restart_block *restart_block);
 
+void update_rlimit_cpu(unsigned long rlim_new);
+
 #endif
include/linux/sched.h +273 -13

334 lines not on this page · raw message

include/linux/time.h +3 -0
index e15206a..1b70b3c 100644
@@ -125,6 +125,9 @@ extern int timekeeping_valid_for_hres(void);
 extern void update_wall_time(void);
 extern void update_xtime_cache(u64 nsec);
 
+struct tms;
+extern void do_sys_times(struct tms *);
+
 /**
  * timespec_to_ns - Convert timespec to nanoseconds
  * @ts:		pointer to the timespec variable to be converted
kernel/compat.c +14 -39

69 lines not on this page · raw message

kernel/exit.c +10 -9
index 1639564..40036ac 100644
@@ -112,8 +112,6 @@ static void __exit_signal(struct task_struct *tsk)
 		 * We won't ever get here for the group leader, since it
 		 * will have been the last reference on the signal_struct.
 		 */
-		sig->utime = cputime_add(sig->utime, task_utime(tsk));
-		sig->stime = cputime_add(sig->stime, task_stime(tsk));
 		sig->gtime = cputime_add(sig->gtime, task_gtime(tsk));
 		sig->min_flt += tsk->min_flt;
 		sig->maj_flt += tsk->maj_flt;
@@ -122,7 +120,6 @@ static void __exit_signal(struct task_struct *tsk)
 		sig->inblock += task_io_get_inblock(tsk);
 		sig->oublock += task_io_get_oublock(tsk);
 		task_io_accounting_add(&sig->ioac, &tsk->ioac);
-		sig->sum_sched_runtime += tsk->se.sum_exec_runtime;
 		sig = NULL; /* Marker for below. */
 	}
 
@@ -1294,6 +1291,7 @@ static int wait_task_zombie(struct task_struct *p, int options,
 	if (likely(!traced)) {
 		struct signal_struct *psig;
 		struct signal_struct *sig;
+		struct task_cputime cputime;
 
 		/*
 		 * The resource counters for the group leader are in its
@@ -1309,20 +1307,23 @@ static int wait_task_zombie(struct task_struct *p, int options,
 		 * need to protect the access to p->parent->signal fields,
 		 * as other threads in the parent group can be right
 		 * here reaping other children at the same time.
+		 *
+		 * We use thread_group_cputime() to get times for the thread
+		 * group, which consolidates times for all threads in the
+		 * group including the group leader.
 		 */
 		spin_lock_irq(&p->parent->sighand->siglock);
 		psig = p->parent->signal;
 		sig = p->signal;
+		thread_group_cputime(p, &cputime);
 		psig->cutime =
 			cputime_add(psig->cutime,
-			cputime_add(p->utime,
-			cputime_add(sig->utime,
-				    sig->cutime)));
+			cputime_add(cputime.utime,
+				    sig->cutime));
 		psig->cstime =
 			cputime_add(psig->cstime,
-			cputime_add(p->stime,
-			cputime_add(sig->stime,
-				    sig->cstime)));
+			cputime_add(cputime.stime,
+				    sig->cstime));
 		psig->cgtime =
 			cputime_add(psig->cgtime,
 			cputime_add(p->gtime,
kernel/fork.c +50 -38

139 lines not on this page · raw message

kernel/itimer.c +10 -23
index ab98274..db7c358 100644
@@ -55,17 +55,15 @@ int do_getitimer(int which, struct itimerval *value)
 		spin_unlock_irq(&tsk->sighand->siglock);
 		break;
 	case ITIMER_VIRTUAL:
-		read_lock(&tasklist_lock);
 		spin_lock_irq(&tsk->sighand->siglock);
 		cval = tsk->signal->it_virt_expires;
 		cinterval = tsk->signal->it_virt_incr;
 		if (!cputime_eq(cval, cputime_zero)) {
-			struct task_struct *t = tsk;
-			cputime_t utime = tsk->signal->utime;
-			do {
-				utime = cputime_add(utime, t->utime);
-				t = next_thread(t);
-			} while (t != tsk);
+			struct task_cputime cputime;
+			cputime_t utime;
+
+			thread_group_cputime(tsk, &cputime);
+			utime = cputime.utime;
 			if (cputime_le(cval, utime)) { /* about to fire */
 				cval = jiffies_to_cputime(1);
 			} else {
@@ -73,25 +71,19 @@ int do_getitimer(int which, struct itimerval *value)
 			}
 		}
 		spin_unlock_irq(&tsk->sighand->siglock);
-		read_unlock(&tasklist_lock);
 		cputime_to_timeval(cval, &value->it_value);
 		cputime_to_timeval(cinterval, &value->it_interval);
 		break;
 	case ITIMER_PROF:
-		read_lock(&tasklist_lock);
 		spin_lock_irq(&tsk->sighand->siglock);
 		cval = tsk->signal->it_prof_expires;
 		cinterval = tsk->signal->it_prof_incr;
 		if (!cputime_eq(cval, cputime_zero)) {
-			struct task_struct *t = tsk;
-			cputime_t ptime = cputime_add(tsk->signal->utime,
-						      tsk->signal->stime);
-			do {
-				ptime = cputime_add(ptime,
-						    cputime_add(t->utime,
-								t->stime));
-				t = next_thread(t);
-			} while (t != tsk);
+			struct task_cputime times;
+			cputime_t ptime;
+
+			thread_group_cputime(tsk, &times);
+			ptime = cputime_add(times.utime, times.stime);
 			if (cputime_le(cval, ptime)) { /* about to fire */
 				cval = jiffies_to_cputime(1);
 			} else {
@@ -99,7 +91,6 @@ int do_getitimer(int which, struct itimerval *value)
 			}
 		}
 		spin_unlock_irq(&tsk->sighand->siglock);
-		read_unlock(&tasklist_lock);
 		cputime_to_timeval(cval, &value->it_value);
 		cputime_to_timeval(cinterval, &value->it_interval);
 		break;
@@ -185,7 +176,6 @@ again:
 	case ITIMER_VIRTUAL:
 		nval = timeval_to_cputime(&value->it_value);
 		ninterval = timeval_to_cputime(&value->it_interval);
-		read_lock(&tasklist_lock);
 		spin_lock_irq(&tsk->sighand->siglock);
 		cval = tsk->signal->it_virt_expires;
 		cinterval = tsk->signal->it_virt_incr;
@@ -200,7 +190,6 @@ again:
 		tsk->signal->it_virt_expires = nval;
 		tsk->signal->it_virt_incr = ninterval;
 		spin_unlock_irq(&tsk->sighand->siglock);
-		read_unlock(&tasklist_lock);
 		if (ovalue) {
 			cputime_to_timeval(cval, &ovalue->it_value);
 			cputime_to_timeval(cinterval, &ovalue->it_interval);
@@ -209,7 +198,6 @@ again:
 	case ITIMER_PROF:
 		nval = timeval_to_cputime(&value->it_value);
 		ninterval = timeval_to_cputime(&value->it_interval);
-		read_lock(&tasklist_lock);
 		spin_lock_irq(&tsk->sighand->siglock);
 		cval = tsk->signal->it_prof_expires;
 		cinterval = tsk->signal->it_prof_incr;
@@ -224,7 +212,6 @@ again:
 		tsk->signal->it_prof_expires = nval;
 		tsk->signal->it_prof_incr = ninterval;
 		spin_unlock_irq(&tsk->sighand->siglock);
-		read_unlock(&tasklist_lock);
 		if (ovalue) {
 			cputime_to_timeval(cval, &ovalue->it_value);
 			cputime_to_timeval(cinterval, &ovalue->it_interval);
kernel/posix-cpu-timers.c +199 -219

577 lines not on this page · raw message

kernel/sched.c +45 -8

92 lines not on this page · raw message

kernel/sched_fair.c +1 -0
index fb8994c..99aa31a 100644
@@ -507,6 +507,7 @@ static void update_curr(struct cfs_rq *cfs_rq)
 		struct task_struct *curtask = task_of(curr);
 
 		cpuacct_charge(curtask, delta_exec);
+		account_group_exec_runtime(curtask, delta_exec);
 	}
 }
 
kernel/sched_rt.c +3 -1
index 5523107..8375e69 100644
@@ -483,6 +483,8 @@ static void update_curr_rt(struct rq *rq)
 	schedstat_set(curr->se.exec_max, max(curr->se.exec_max, delta_exec));
 
 	curr->se.sum_exec_runtime += delta_exec;
+	account_group_exec_runtime(curr, delta_exec);
+
 	curr->se.exec_start = rq->clock;
 	cpuacct_charge(curr, delta_exec);
 
@@ -1412,7 +1414,7 @@ static void watchdog(struct rq *rq, struct task_struct *p)
 		p->rt.timeout++;
 		next = DIV_ROUND_UP(min(soft, hard), USEC_PER_SEC/HZ);
 		if (p->rt.timeout > next)
-			p->it_sched_expires = p->se.sum_exec_runtime;
+			p->cputime_expires.sched_exp = p->se.sum_exec_runtime;
 	}
 }
 
kernel/signal.c +4 -4
index e661b01..6eea582 100644
@@ -1338,6 +1338,7 @@ int do_notify_parent(struct task_struct *tsk, int sig)
 	struct siginfo info;
 	unsigned long flags;
 	struct sighand_struct *psig;
+	struct task_cputime cputime;
 	int ret = sig;
 
 	BUG_ON(sig == -1);
@@ -1368,10 +1369,9 @@ int do_notify_parent(struct task_struct *tsk, int sig)
 
 	info.si_uid = tsk->uid;
 
-	info.si_utime = cputime_to_clock_t(cputime_add(tsk->utime,
-						       tsk->signal->utime));
-	info.si_stime = cputime_to_clock_t(cputime_add(tsk->stime,
-						       tsk->signal->stime));
+	thread_group_cputime(tsk, &cputime);
+	info.si_utime = cputime_to_jiffies(cputime.utime);
+	info.si_stime = cputime_to_jiffies(cputime.stime);
 
 	info.si_status = tsk->exit_code & 0x7f;
 	if (tsk->exit_code & 0x80)
kernel/sys.c +26 -49

127 lines not on this page · raw message

security/selinux/hooks.c +2 -7
index 03fc6a8..6964978 100644
@@ -75,6 +75,7 @@
 #include <linux/string.h>
 #include <linux/selinux.h>
 #include <linux/mutex.h>
+#include <linux/posix-timers.h>
 
 #include "avc.h"
 #include "objsec.h"
@@ -2321,13 +2322,7 @@ static void selinux_bprm_post_apply_creds(struct linux_binprm *bprm)
 			initrlim = init_task.signal->rlim+i;
 			rlim->rlim_cur = min(rlim->rlim_max, initrlim->rlim_cur);
 		}
-		if (current->signal->rlim[RLIMIT_CPU].rlim_cur != RLIM_INFINITY) {
-			/*
-			 * This will cause RLIMIT_CPU calculations
-			 * to be refigured.
-			 */
-			current->it_prof_expires = jiffies_to_cputime(1);
-		}
+		update_rlimit_cpu(rlim->rlim_cur);
 	}
 
 	/* Wake up the parent if it is waiting so that it can
Signature · 2 lines
Frank Mayhar <[email protected]>
Google, Inc.
#1 lore raw
Quoted 6 lines · Frank Mayhar

Overview

This patch reworks the handling of POSIX CPU timers, including the ITIMER_PROF, ITIMER_VIRT timers and rlimit handling. It was put together with the help of Roland McGrath, the owner and original writer of this code.

[ i've extended the Cc: line accordingly. ]

Ingo

#2 lore raw
Quoted 9 lines · Ingo Molnar
Quoted 6 lines · Frank Mayhar

Overview

This patch reworks the handling of POSIX CPU timers, including the ITIMER_PROF, ITIMER_VIRT timers and rlimit handling. It was put together with the help of Roland McGrath, the owner and original writer of this code.

I'll try to read this patch on weekend. A couple of naive questions right now.

Quoted 17 lines
include/linux/sched.h +17 -0
+static inline void thread_group_cputime(
+	struct task_struct *tsk,
+	struct task_cputime *times)
+{
+	struct signal_struct *sig;
+	int i;
+	struct task_cputime *tot;
+
+	rcu_read_lock();
+	sig = rcu_dereference(tsk->signal);
+	if (unlikely(!sig) || !sig->cputime.totals) {
+		times->utime = tsk->utime;
+		times->stime = tsk->stime;
+		times->sum_exec_runtime = tsk->se.sum_exec_runtime;
+		rcu_read_unlock();
+		return;
+	}

include/linux/sched.h static inline int spin_needbreak(spinlock_t *lock) · line 2184

Quoted 10 lines
include/linux/sched.h +10 -0
+	times->stime = times->utime = cputime_zero;
+	times->sum_exec_runtime = 0;
+	for_each_possible_cpu(i) {
+		tot = per_cpu_ptr(tsk->signal->cputime.totals, i);
+		times->utime = cputime_add(times->utime, tot->utime);
+		times->stime = cputime_add(times->stime, tot->stime);
+		times->sum_exec_runtime += tot->sum_exec_runtime;
+	}
+	rcu_read_unlock();
+}

The patch has a lot of

	rcu_read_lock();
	sig = rcu_dereference(tsk->signal);

This is bogus, task_struct->signal is not protected by RCU.

However, at first glance the code (this and other funcs) looks correct... Either tsk == current, or the code runs under ->siglock. Or we know that ->signal can't go away (wait_task_zombie).

As for this particular function, it seems to me that ->signal == NULL is not possible, no?

Please remove the false RCU stuff.

Btw, this function has a lot of callers, perhaps it is better to uninline it.

Quoted 4 lines

static int copy_signal(unsigned long clone_flags, struct task_struct *tsk) {

kernel/fork.c +0 -0
 	struct signal_struct *sig;
 	int ret;

kernel/fork.c void __cleanup_sighand(struct sighand_struct *sighand) · line 798

Quoted 10 lines
kernel/fork.c +5 -3
 
 	if (clone_flags & CLONE_THREAD) {
-		atomic_inc(&current->signal->count);
-		atomic_inc(&current->signal->live);
-		return 0;
+		ret = thread_group_cputime_clone_thread(current, tsk);
+		if (likely(!ret)) {
+			atomic_inc(&current->signal->count);
+			atomic_inc(&current->signal->live);
+		}

So, the first CLONE_THREAD creates ->cputime.totals. After that thread_group_cputime_account_xxx() start to use it even if the task doesn't have the attached cpu timers.

Stupid question: can't we allocate .totals in posix_cpu_timer_create() / set_process_cpu_timer() ?

Quoted 6 lines
kernel/posix-cpu-timers.c +6 -0
+int thread_group_cputime_alloc_smp(struct task_struct *tsk)
+{
+	struct signal_struct *sig = tsk->signal;
+	struct task_cputime *cputime;
+
+	/*

kernel/posix-cpu-timers.c line 33

Quoted 10 lines
kernel/posix-cpu-timers.c +10 -0
+	 * If we have multiple threads and we don't already have a
+	 * per-CPU task_cputime struct, allocate one and fill it in with
+	 * the times accumulated so far.
+	 */
+	if (sig->cputime.totals)
+		return 0;
+	cputime = alloc_percpu(struct task_cputime);
+	if (cputime == NULL)
+		return -ENOMEM;
+	read_lock(&tasklist_lock);

tasklist_lock is not needed,

kernel/posix-cpu-timers.c line 34

Quoted 1 line
kernel/posix-cpu-timers.c +1 -0
+	spin_lock_irq(&tsk->sighand->siglock);

->siglock is enough.

Quoted 58 lines
kernel/posix-cpu-timers.c +38 -12
+static inline int task_cputime_expired(const struct task_cputime *sample,
+					const struct task_cputime *expires)
+{
+	if (!cputime_eq(expires->utime, cputime_zero) &&
+	    cputime_ge(sample->utime, expires->utime))
+		return 1;
+	if (!cputime_eq(expires->stime, cputime_zero) &&
+	    cputime_ge(cputime_add(sample->utime, sample->stime),
+		       expires->stime))
+		return 1;
+	if (expires->sum_exec_runtime != 0 &&
+	    sample->sum_exec_runtime >= expires->sum_exec_runtime)
+		return 1;
+	return 0;
+}
+
+static inline int fastpath_timer_check(struct task_struct *tsk,
+					struct signal_struct *sig)
+{
+	struct task_cputime task_sample = {
+		.utime = tsk->utime,
+		.stime = tsk->stime,
+		.sum_exec_runtime = tsk->se.sum_exec_runtime
+	};
+	struct task_cputime group_sample;
+
+	if (task_cputime_expired(&task_sample, &tsk->cputime_expires))
+		return 1;
+	thread_group_cputime(tsk, &group_sample);
+	return task_cputime_expired(&group_sample, &sig->cputime_expires);
+}
+
@@ -1323,30 +1304,30 @@ void run_posix_cpu_timers(struct task_struct *tsk)
 {
 	LIST_HEAD(firing);
 	struct k_itimer *timer, *next;
+	struct signal_struct *sig;
+	struct sighand_struct *sighand;
+	unsigned long flags;
 
 	BUG_ON(!irqs_disabled());
 
-#define UNEXPIRED(clock) \
-		(cputime_eq(tsk->it_##clock##_expires, cputime_zero) || \
-		 cputime_lt(clock##_ticks(tsk), tsk->it_##clock##_expires))
-
-	if (UNEXPIRED(prof) && UNEXPIRED(virt) &&
-	    (tsk->it_sched_expires == 0 ||
-	     tsk->se.sum_exec_runtime < tsk->it_sched_expires))
-		return;
-
-#undef	UNEXPIRED
-
+	/* Safely pick up tsk->signal and make sure it's valid. */
+	rcu_read_lock();
+	sig = rcu_dereference(tsk->signal);
 	/*
-	 * Double-check with locks held.

kernel/posix-cpu-timers.c void run_posix_cpu_timers(struct task_struct *tsk) · line 1322

Quoted 10 lines
kernel/posix-cpu-timers.c +5 -4
+	 * The fast path checks that there are no expired thread or thread
+	 * group timers.  If that's so, just return.
 	 */
-	read_lock(&tasklist_lock);
-	if (likely(tsk->signal != NULL)) {
-		spin_lock(&tsk->sighand->siglock);
-
+	if (unlikely(!sig) || !fastpath_timer_check(tsk, sig)) {
+		rcu_read_unlock();
+		return;

Ugh. Probably I misunderstand the patch, but...

Let's suppose the task doesn't have cpu timers. Currently, in this case run_posix_cpu_timers() quickly checks UNEXPIRED() and returns. With this patch we call fastpath_timer_check(). The first task_cputime_expired() returns 0, so we are doing thread_group_cputime()->for_each_possible_cpu().

Not good, this code runs every timer tick. Perhaps it makes sense to add a fastpath check.

(again, rcu stuff is bogus)

Oleg.

#3 lore raw
Quoted 7 lines · Oleg Nesterov

So, the first CLONE_THREAD creates ->cputime.totals. After that thread_group_cputime_account_xxx() start to use it even if the task doesn't have the attached cpu timers.

Stupid question: can't we allocate .totals in posix_cpu_timer_create() / set_process_cpu_timer() ?

Just to clarify: yes I see, .totals is also used by do_task_stat()/etc, but they can iterate over sub-threads as before.

And my apologies if this was already discussed ;)

Oleg.

#4 lore raw
In reply to Oleg Nesterov
Quoted 6 lines · Oleg Nesterov

The patch has a lot of

	rcu_read_lock();
	sig = rcu_dereference(tsk->signal);

This is bogus, task_struct->signal is not protected by RCU.

Roland suggested this approach; I just want to snapshot the field atomically. I guess I can just do an atomic read...

Quoted 6 lines

However, at first glance the code (this and other funcs) looks correct... Either tsk == current, or the code runs under ->siglock. Or we know that ->signal can't go away (wait_task_zombie).

As for this particular function, it seems to me that ->signal == NULL is not possible, no?

That's not completely clear to me. I'm allowing for the possibility that it might be called during, say, process teardown. It's used in so many places that I'm uncomfortable leaving the == NULL check out.

Quoted 1 line

Please remove the false RCU stuff.

OK.

Quoted 2 lines

Btw, this function has a lot of callers, perhaps it is better to uninline it.

If that's the consensus I'll do so. I assumed that speed was more important than space in this case. Am I mistaken?

Quoted 19 lines
Quoted 4 lines

static int copy_signal(unsigned long clone_flags, struct task_struct *tsk) {

kernel/fork.c +0 -0
 	struct signal_struct *sig;
 	int ret;

kernel/fork.c void __cleanup_sighand(struct sighand_struct *sighand) · line 798

Quoted 10 lines
kernel/fork.c +5 -3
 
 	if (clone_flags & CLONE_THREAD) {
-		atomic_inc(&current->signal->count);
-		atomic_inc(&current->signal->live);
-		return 0;
+		ret = thread_group_cputime_clone_thread(current, tsk);
+		if (likely(!ret)) {
+			atomic_inc(&current->signal->count);
+			atomic_inc(&current->signal->live);
+		}

So, the first CLONE_THREAD creates ->cputime.totals. After that thread_group_cputime_account_xxx() start to use it even if the task doesn't have the attached cpu timers.

Quoted 2 lines

Stupid question: can't we allocate .totals in posix_cpu_timer_create() / set_process_cpu_timer() ?

That was the original plan but we (that is, Roland and I) decided to eliminate the separate storage for the dead-threads totals. It's now all kept in the totals field, for the whole thread group. Note that this doesn't affect single-threaded processes at all. Multithreaded processes, though, now keep their times in the new field, eliminating the old dead-thread fields from the signal structure, reducing the bloat this patch generates by just a bit.

Quoted 7 lines

Let's suppose the task doesn't have cpu timers. Currently, in this case run_posix_cpu_timers() quickly checks UNEXPIRED() and returns. With this patch we call fastpath_timer_check(). The first task_cputime_expired() returns 0, so we are doing thread_group_cputime()->for_each_possible_cpu().

Not good, this code runs every timer tick. Perhaps it makes sense to add a fastpath check.

After looking at the code again, you're right. I paid so much attention to fast-pathing the unexpired timer case that I forgot to handle the _no_-timer case. I've added code to fastpath_timer_check() to handle that case.

I'll be addressing the rest of your comments (particularly the RCU stuff) and producing a new patch fairly shortly.

Signature · 2 lines
Frank Mayhar <[email protected]>
Google, Inc.
#5 lore raw
Quoted 9 lines · Frank Mayhar
Quoted 2 lines · Oleg Nesterov

As for this particular function, it seems to me that ->signal == NULL is not possible, no?

That's not completely clear to me. I'm allowing for the possibility that it might be called during, say, process teardown. It's used in so many places that I'm uncomfortable leaving the == NULL check out.

Please see my reply to Roland.

Quoted 5 lines
Quoted 2 lines

Btw, this function has a lot of callers, perhaps it is better to uninline it.

If that's the consensus I'll do so. I assumed that speed was more important than space in this case. Am I mistaken?

Are you sure inline will be faster? It has a lot of calllers, think about i-cache. And the function call is not that expensive.

But I am not expert.

Quoted 10 lines
Quoted 6 lines

So, the first CLONE_THREAD creates ->cputime.totals. After that thread_group_cputime_account_xxx() start to use it even if the task doesn't have the attached cpu timers.

Stupid question: can't we allocate .totals in posix_cpu_timer_create() / set_process_cpu_timer() ?

That was the original plan but we (that is, Roland and I) decided to eliminate the separate storage for the dead-threads totals. It's now all kept in the totals field, for the whole thread group.

I see, thanks.

Oleg.

#6 lore raw
Quoted 4 lines · Oleg Nesterov
Quoted 3 lines · Frank Mayhar

On Tue, 2008-09-09 at 20:01 +0400, Oleg Nesterov wrote:

Quoted 8 lines
Quoted 6 lines
Quoted 2 lines

As for this particular function, it seems to me that ->signal == NULL is not possible, no?

That's not completely clear to me. I'm allowing for the possibility that it might be called during, say, process teardown. It's used in so many places that I'm uncomfortable leaving the == NULL check out.

Please see my reply to Roland.

I saw it. I dunno, I'm more of the "belt-and-suspenders" mindset. I'll add a comment, thought, that this is probably a "can't happen" but we check it anyway.

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

Btw, this function has a lot of callers, perhaps it is better to uninline it.

If that's the consensus I'll do so. I assumed that speed was more important than space in this case. Am I mistaken?

Are you sure inline will be faster? It has a lot of calllers, think about i-cache. And the function call is not that expensive.

Hmm. It just seems to me that making it inline enables the optimizer to do smarter things with the flow of control. The routine isn't all that long, disassembling the posix_cpu_timers_exit_group() routine gives a good view of it and it appears to be around 120 bytes. Certainly less than 200 bytes (all of posix_cpu_timers_exit_group() is only 201 bytes). That doesn't seem like a cache buster but I defer to those who are more familiar with this stuff.

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

So, the first CLONE_THREAD creates ->cputime.totals. After that thread_group_cputime_account_xxx() start to use it even if the task doesn't have the attached cpu timers.

Quoted 8 lines
Quoted 6 lines
Quoted 2 lines

Stupid question: can't we allocate .totals in posix_cpu_timer_create() / set_process_cpu_timer() ?

That was the original plan but we (that is, Roland and I) decided to eliminate the separate storage for the dead-threads totals. It's now all kept in the totals field, for the whole thread group.

I see, thanks.

You're welcome. I actually like the new method of keeping track of this stuff; it seems cleaner and certainly removes the requirement of walking the thread group to add it up. Should help some microbenchmarks, at least. :-)

Signature · 2 lines
Frank Mayhar <[email protected]>
Google, Inc.
#7 lore raw
In reply to Frank Mayhar
Quoted 11 lines · Frank Mayhar
Quoted 6 lines · Oleg Nesterov

The patch has a lot of

	rcu_read_lock();
	sig = rcu_dereference(tsk->signal);

This is bogus, task_struct->signal is not protected by RCU.

I just want to snapshot the field atomically. I guess I can just do an atomic read...

Missed this part...

No, no, you don't need an atomic read. Just do

	sig = tsk->signal;
	if (sig)
		use(sig);

->signal must be stable, or the code is buggy anyway. (and the task never changes its ->signal, it becomes NULL when the task dies).

BTW, thanks for doing this!

Oleg.

#8 lore raw
In reply to Oleg Nesterov
Quoted 2 lines

As for this particular function, it seems to me that ->signal == NULL is not possible, no?

The concern is to make sure that the timer tick path is always safe for a tick that hits during release_task(current) in exit_notify(). A timer tick there can come with current->signal == NULL. We just need to make sure one way or another that this is safe.

Thanks,
Roland

#9 lore raw
Quoted 8 lines · Roland McGrath
Quoted 3 lines

As for this particular function, it seems to me that ->signal == NULL is not possible, no?

The concern is to make sure that the timer tick path is always safe for a tick that hits during release_task(current) in exit_notify(). A timer tick there can come with current->signal == NULL. We just need to make sure one way or another that this is safe.

run_posix_cpu_timers() must check ->signal != NULL anyway. (The same for other functions like account_group_user_time() which are called by the timer tick).

Apart from the timer tick, "current" should not use this function after exit_notify().

And, if tsk != current, ->signal must be pinned, this means it can't be NULL.

Perhaps I missed something, but imho this check is confusing and misleading. However, this is just a minor detail even if I am right.

Oleg.

#10 lore raw
In reply to Frank Mayhar

Thanks, Frank! I won't have time to do a thorough fresh review of this until after next week. But from my recollection of the state of your patch the last time we batted it around, I think it was getting close to right. Oleg has a keen eye for this stuff. I'm sure the next patch after incorporating his review will be even closer.

Thanks,
Roland