From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:26:18
My intention is to make it easier to manipulate and maintain kthreads.
Especially, I want to replace all the custom main cycles with a
generic one. Also I want to make the kthreads sleep in a consistent
state in a common place when there is no work.
My first attempt was with a brand new API (iterant kthread), see
http://thread.gmane.org/gmane.linux.kernel.api/11892 . But I was
directed to improve the existing kthread worker API. This is
the 3rd iteration of the new direction.
1st patch: add support to check if a timer callback is being called
2nd..12th patches: improve the existing kthread worker API
13th..18th, 20th, 22nd patches: convert several kthreads into
the kthread worker API, namely: khugepaged, ring buffer
benchmark, hung_task, kmemleak, ipmi, IB/fmr_pool,
memstick/r592, intel_powerclamp
21st, 23rd patches: do some preparation steps; they usually do
some clean up that makes sense even without the conversion.
Changes against v2:
+ used worker->lock to synchronize the operations with the work
instead of the PENDING bit as suggested by Tejun Heo; it simplified
the implementation in several ways
+ added timer_active(); used it together with del_timer_sync()
to cancel the work a less tricky way
+ removed the controversial conversion of the RCU kthreads
+ added several other examples: hung_task, kmemleak, ipmi,
IB/fmr_pool, memstick/r592, intel_powerclamp
+ the helper fixes for the ring buffer benchmark has been improved
as suggested by Steven; they already are in the Linus tree now
+ fixed a possible race between the check for existing khugepaged
worker and queuing the work
Changes against v1:
+ remove wrappers to manipulate the scheduling policy and priority
+ remove questionable wakeup_and_destroy_kthread_worker() variant
+ do not check for chained work when draining the queue
+ allocate struct kthread worker in create_kthread_work() and
use more simple checks for running worker
+ add support for delayed kthread works and use them instead
of waiting inside the works
+ rework the "unrelated" fixes for the ring buffer benchmark
as discussed in the 1st RFC; also sent separately
+ convert also the consumer in the ring buffer benchmark
I have tested this patch set against the stable Linus tree
for 4.4-rc1.
Petr Mladek (22):
timer: Allow to check when the timer callback has not finished yet
kthread/smpboot: Do not park in kthread_create_on_cpu()
kthread: Allow to call __kthread_create_on_node() with va_list args
kthread: Add create_kthread_worker*()
kthread: Add drain_kthread_worker()
kthread: Add destroy_kthread_worker()
kthread: Detect when a kthread work is used by more workers
kthread: Initial support for delayed kthread work
kthread: Allow to cancel kthread work
kthread: Allow to modify delayed kthread work
kthread: Better support freezable kthread workers
kthread: Use try_lock_kthread_work() in flush_kthread_work()
mm/huge_page: Convert khugepaged() into kthread worker API
ring_buffer: Convert benchmark kthreads into kthread worker API
hung_task: Convert hungtaskd into kthread worker API
kmemleak: Convert kmemleak kthread into kthread worker API
ipmi: Convert kipmi kthread into kthread worker API
IB/fmr_pool: Convert the cleanup thread into kthread worker API
memstick/r592: Better synchronize debug messages in r592_io kthread
memstick/r592: convert r592_io kthread into kthread worker API
thermal/intel_powerclamp: Remove duplicated code that starts the
kthread
thermal/intel_powerclamp: Convert the kthread to kthread worker API
drivers/char/ipmi/ipmi_si_intf.c | 116 ++++---
drivers/infiniband/core/fmr_pool.c | 54 ++-
drivers/memstick/host/r592.c | 61 ++--
drivers/memstick/host/r592.h | 5 +-
drivers/thermal/intel_powerclamp.c | 302 +++++++++--------
include/linux/kthread.h | 56 ++++
include/linux/timer.h | 2 +
kernel/hung_task.c | 41 ++-
kernel/kthread.c | 618 +++++++++++++++++++++++++++++++----
kernel/smpboot.c | 5 +
kernel/time/timer.c | 24 ++
kernel/trace/ring_buffer_benchmark.c | 133 ++++----
mm/huge_memory.c | 134 ++++----
mm/kmemleak.c | 86 +++--
14 files changed, 1142 insertions(+), 495 deletions(-)
CC: Catalin Marinas <catalin.marinas@arm.com>
CC: linux-watchdog@vger.kernel.org
CC: Corey Minyard <redacted>
CC: openipmi-developer@lists.sourceforge.net
CC: Doug Ledford <redacted>
CC: Sean Hefty <redacted>
CC: Hal Rosenstock <redacted>
CC: linux-rdma@vger.kernel.org
CC: Maxim Levitsky <maximlevitsky@gmail.com>
CC: Zhang Rui <rui.zhang@intel.com>
CC: Eduardo Valentin <edubezval@gmail.com>
CC: Jacob Pan <redacted>
CC: linux-pm@vger.kernel.org
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:26:23
timer_pending() checks whether the list of callbacks is empty.
Each callback is removed from the list before it is called,
see call_timer_fn() in __run_timers().
Sometimes we need to make sure that the callback has finished.
For example, if we want to free some resources that are accessed
by the callback.
For this purpose, this patch adds timer_active(). It checks both
the list of callbacks and the running_timer. It takes the base_lock
to see a consistent state.
I plan to use it to implement delayed works in kthread worker.
But I guess that it will have wider use. In fact, I wonder if
timer_pending() is misused in some situations.
Signed-off-by: Petr Mladek <pmladek@suse.com>
---
include/linux/timer.h | 2 ++
kernel/time/timer.c | 24 ++++++++++++++++++++++++
2 files changed, 26 insertions(+)
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Thomas Gleixner <hidden> Date: 2015-11-18 22:33:35
On Wed, 18 Nov 2015, Petr Mladek wrote:
timer_pending() checks whether the list of callbacks is empty.
Each callback is removed from the list before it is called,
see call_timer_fn() in __run_timers().
Sometimes we need to make sure that the callback has finished.
For example, if we want to free some resources that are accessed
by the callback.
For this purpose, this patch adds timer_active(). It checks both
the list of callbacks and the running_timer. It takes the base_lock
to see a consistent state.
I plan to use it to implement delayed works in kthread worker.
But I guess that it will have wider use. In fact, I wonder if
timer_pending() is misused in some situations.
Well. That's nice and good. But how will that new function solve
anything? After you drop the lock the state is not longer valid.
Thanks,
tglx
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-19 12:43:54
On Wed 2015-11-18 23:32:28, Thomas Gleixner wrote:
On Wed, 18 Nov 2015, Petr Mladek wrote:
quoted
timer_pending() checks whether the list of callbacks is empty.
Each callback is removed from the list before it is called,
see call_timer_fn() in __run_timers().
Sometimes we need to make sure that the callback has finished.
For example, if we want to free some resources that are accessed
by the callback.
For this purpose, this patch adds timer_active(). It checks both
the list of callbacks and the running_timer. It takes the base_lock
to see a consistent state.
I plan to use it to implement delayed works in kthread worker.
But I guess that it will have wider use. In fact, I wonder if
timer_pending() is misused in some situations.
Well. That's nice and good. But how will that new function solve
anything? After you drop the lock the state is not longer valid.
If we prevent anyone from setting up the timer and timer_pending()
returns false, we are sure that the timer will stay as is.
For example, I use it in the function try_to_cancel_kthread_work().
Any manipulation with the timer is protected by worker->lock.
If the timer is not pending but still active, I have to drop
the lock and busy wait for the timer callback. See
http://thread.gmane.org/gmane.linux.kernel.mm/141493/focus=141501
Also I wonder if the following usage in
drivers/infiniband/hw/nes/nes_cm.c is safe:
static int mini_cm_dealloc_core(struct nes_cm_core *cm_core)
{
nes_debug(NES_DBG_CM, "De-Alloc CM Core (%p)\n", cm_core);
if (!cm_core)
return -EINVAL;
barrier();
if (timer_pending(&cm_core->tcp_timer))
del_timer(&cm_core->tcp_timer);
destroy_workqueue(cm_core->event_wq);
destroy_workqueue(cm_core->disconn_wq);
We destroy the workqueue but the timer callback might still
be in progress and queue new work.
There are many more locations where I see the pattern:
if (timer_pending())
del_timer();
clean_up_stuff();
IMHO, we should use:
if (timer_active())
del_timer_sync();
/* really safe to free stuff */
clean_up_stuff();
or just
del_timer_sync();
clean_up_stuff();
I wonder if timer_pending() is used in more racy scenarios. Or maybe,
I just miss something that makes it all safe.
Thanks,
Petr
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:26:28
kthread_create_on_cpu() was added by the commit 2a1d446019f9a5983e
("kthread: Implement park/unpark facility"). It is currently used
only when enabling new CPU. For this purpose, the newly created
kthread has to be parked.
The CPU binding is a bit tricky. The kthread is parked when the CPU
has not been allowed yet. And the CPU is bound when the kthread
is unparked.
The function would be useful for more per-CPU kthreads, e.g.
bnx2fc_thread, fcoethread. For this purpose, the newly created
kthread should stay in the uninterruptible state.
This patch moves the parking into smpboot. It binds the thread
already when created. Then the function might be used universally.
Also the behavior is consistent with kthread_create() and
kthread_create_on_node().
Signed-off-by: Petr Mladek <pmladek@suse.com>
---
kernel/kthread.c | 8 ++++++--
kernel/smpboot.c | 5 +++++
2 files changed, 11 insertions(+), 2 deletions(-)
@@ -390,10 +390,10 @@ struct task_struct *kthread_create_on_cpu(int (*threadfn)(void *data),cpu);if(IS_ERR(p))returnp;+kthread_bind(p,cpu);+/* CPU hotplug need to bind once again when unparking the thread. */set_bit(KTHREAD_IS_PER_CPU,&to_kthread(p)->flags);to_kthread(p)->cpu=cpu;-/* Park the thread to get it out of TASK_UNINTERRUPTIBLE state */-kthread_park(p);returnp;}
@@ -186,6 +186,11 @@ __smpboot_create_thread(struct smp_hotplug_thread *ht, unsigned int cpu)kfree(td);returnPTR_ERR(tsk);}+/*+*ParkthethreadsothatitcouldstartrightontheCPU+*whenitisavailable.+*/+kthread_park(tsk);get_task_struct(tsk);*per_cpu_ptr(ht->store,cpu)=tsk;if(ht->create){
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Thomas Gleixner <hidden> Date: 2015-11-25 21:17:22
On Wed, 18 Nov 2015, Petr Mladek wrote:
kthread_create_on_cpu() was added by the commit 2a1d446019f9a5983e
("kthread: Implement park/unpark facility"). It is currently used
only when enabling new CPU. For this purpose, the newly created
kthread has to be parked.
The CPU binding is a bit tricky. The kthread is parked when the CPU
has not been allowed yet. And the CPU is bound when the kthread
is unparked.
The function would be useful for more per-CPU kthreads, e.g.
bnx2fc_thread, fcoethread. For this purpose, the newly created
kthread should stay in the uninterruptible state.
This patch moves the parking into smpboot. It binds the thread
already when created. Then the function might be used universally.
Also the behavior is consistent with kthread_create() and
kthread_create_on_node().
Signed-off-by: Petr Mladek <pmladek-IBi9RG/b67k@public.gmane.org>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:26:36
Kthread workers are currently created using the classic kthread API,
namely kthread_run(). kthread_worker_fn() is passed as the @threadfn
parameter.
This patch defines create_kthread_worker() and
create_kthread_worker_on_cpu() functions that hide implementation details.
They enforce using kthread_worker_fn() for the main thread. But I doubt
that there are any plans to create any alternative. In fact, I think
that we do not want any alternative main thread because it would be
hard to support consistency with the rest of the kthread worker API.
The naming and function is inspired by the workqueues API like the rest
of the kthread worker API.
Note that we need to bind per-CPU kthread workers already when they are
created. It makes the life easier. kthread_bind() could not be used later
for an already running worker.
This patch does _not_ convert existing kthread workers. The kthread worker
API need more improvements first, e.g. a function to destroy the worker.
Signed-off-by: Petr Mladek <pmladek@suse.com>
---
include/linux/kthread.h | 7 ++++
kernel/kthread.c | 99 ++++++++++++++++++++++++++++++++++++++++++++-----
2 files changed, 96 insertions(+), 10 deletions(-)
@@ -617,6 +618,84 @@ repeat:}EXPORT_SYMBOL_GPL(kthread_worker_fn);+staticstructkthread_worker*+__create_kthread_worker(intcpu,constcharnamefmt[],va_listargs)+{+structkthread_worker*worker;+structtask_struct*task;++worker=kzalloc(sizeof(*worker),GFP_KERNEL);+if(!worker)+returnERR_PTR(-ENOMEM);++init_kthread_worker(worker);++if(cpu>=0)+task=kthread_create_on_cpu(kthread_worker_fn,worker,+cpu,namefmt);+else+task=__kthread_create_on_node(kthread_worker_fn,worker,+-1,namefmt,args);+if(IS_ERR(task))+gotofail_task;++worker->task=task;+wake_up_process(task);+returnworker;++fail_task:+kfree(worker);+returnERR_CAST(task);+}++/**+*create_kthread_worker-createakthreadworker+*@namefmt:printf-stylenameforthekthreadworker(task).+*+*Returnspointertoanallocatedworkeronsuccess,ERR_PTR(-ENOMEM)when+*theneededstructurescouldnotgetallocated,andERR_PTR(-EINTR)when+*theworkerwasSIGKILLed.+*/+structkthread_worker*+create_kthread_worker(constcharnamefmt[],...)+{+structkthread_worker*worker;+va_listargs;++va_start(args,namefmt);+worker=__create_kthread_worker(-1,namefmt,args);+va_end(args);++returnworker;+}+EXPORT_SYMBOL(create_kthread_worker);++/**+*create_kthread_worker_on_cpu-createakthreadworkerandbindit+*ittoagivenCPUandtheassociatedNUMAnode.+*@cpu:CPUnumber+*@namefmt:printf-stylenameforthekthreadworker(task).+*+*UseavalidCPUnumberifyouwanttobindthekthreadworker+*tothegivenCPUandtheassociatedNUMAnode.+*+*@namefmtmightincludeone"%d"thatwillgetreplacedbyCPUnumber.+*+*Returnspointertoallocatedworkeronsuccess,ERR_PTRwhentheCPU+*numberisnotvalid,ERR_PTR(-ENOMEM)whentheneededstructurescould+*notgetallocated,ERR_PTR(-EINTR)whentheworkerwasSIGKILLed,and+*ERR_PTR(-EINVAL)oninvalid@cpu.+*/+structkthread_worker*+create_kthread_worker_on_cpu(intcpu,constcharnamefmt[])+{+if(cpu<0||cpu>num_possible_cpus())+returnERR_PTR(-EINVAL);++return__create_kthread_worker(cpu,namefmt,NULL);+}+EXPORT_SYMBOL(create_kthread_worker_on_cpu);+/* insert @work before @pos in @worker */staticvoidinsert_kthread_work(structkthread_worker*worker,structkthread_work*work,
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:26:38
kthread_create_on_node() implements a bunch of logic to create
the kthread. It is already called by kthread_create_on_cpu().
We are going to extend the kthread worker API and will
need to call kthread_create_on_node() with va_list args there.
This patch does only a refactoring and does not modify the existing
behavior.
Signed-off-by: Petr Mladek <pmladek@suse.com>
---
kernel/kthread.c | 72 +++++++++++++++++++++++++++++++++-----------------------
1 file changed, 42 insertions(+), 30 deletions(-)
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:26:43
The current kthread worker users call flush() and stop() explicitly.
This function drains the worker, stops it, and frees the kthread_worker
struct in one call.
It is supposed to be used together with create_kthread_worker*() that
allocates struct kthread_worker.
Also note that drain() correctly handles self-queuing works in compare
with flush().
Signed-off-by: Petr Mladek <pmladek@suse.com>
---
include/linux/kthread.h | 2 ++
kernel/kthread.c | 21 +++++++++++++++++++++
2 files changed, 23 insertions(+)
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:26:49
Nothing currently prevents a work from queuing for a kthread worker
when it is already running on another one. This means that the work
might run in parallel on more workers. Also some operations, e.g.
flush or drain are not reliable.
This problem will be even more visible after we add cancel_kthread_work()
function. It will only have "work" as the parameter and will use
worker->lock to synchronize with others.
Well, normally this is not a problem because the API users are sane.
But bugs might happen and users also might be crazy.
This patch adds a warning when we try to insert the work for another
worker. It does not fully prevent the misuse because it would make the
code much more complicated without a big benefit.
Note that we need to clear the information about the current worker
when the work is not longer used. It is important when the worker
is destroyed and later created again. For example, this is
useful when a service might get disabled and enabled via sysfs.
Also note that kthread_work_pending() function will get more
complicated once we add support for a delayed kthread work and
allow to cancel works.
Just for completeness, the patch adds a check for disabled interrupts
and an empty queue.
The patch also puts all the checks into a separate function. It will
be reused when implementing delayed works.
Signed-off-by: Petr Mladek <pmladek@suse.com>
---
kernel/kthread.c | 45 +++++++++++++++++++++++++++++++++++++++++----
1 file changed, 41 insertions(+), 4 deletions(-)
@@ -610,6 +625,12 @@ repeat:if(work){__set_current_state(TASK_RUNNING);work->func(work);++spin_lock_irq(&worker->lock);+/* Allow to queue the work into another worker */+if(!kthread_work_pending(work))+work->worker=NULL;+spin_unlock_irq(&worker->lock);}elseif(!freezing(current))schedule();
@@ -696,12 +717,22 @@ create_kthread_worker_on_cpu(int cpu, const char namefmt[])}EXPORT_SYMBOL(create_kthread_worker_on_cpu);+staticvoidinsert_kthread_work_sanity_check(structkthread_worker*worker,+structkthread_work*work)+{+lockdep_assert_held(&worker->lock);+WARN_ON_ONCE(!irqs_disabled());+WARN_ON_ONCE(!list_empty(&work->node));+/* Do not use a work with more workers, see queue_kthread_work() */+WARN_ON_ONCE(work->worker&&work->worker!=worker);+}+/* insert @work before @pos in @worker */staticvoidinsert_kthread_work(structkthread_worker*worker,-structkthread_work*work,-structlist_head*pos)+structkthread_work*work,+structlist_head*pos){-lockdep_assert_held(&worker->lock);+insert_kthread_work_sanity_check(worker,work);list_add_tail(&work->node,pos);work->worker=worker;
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
Hello,
On Wed, Nov 18, 2015 at 02:25:12PM +0100, Petr Mladek wrote:
quoted hunk
@@ -610,6 +625,12 @@ repeat: if (work) { __set_current_state(TASK_RUNNING); work->func(work);++ spin_lock_irq(&worker->lock);+ /* Allow to queue the work into another worker */+ if (!kthread_work_pending(work))+ work->worker = NULL;+ spin_unlock_irq(&worker->lock);
Doesn't this mean that the work item can't be freed from its callback?
That pattern tends to happen regularly.
Thanks.
--
tejun
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-24 10:06:56
On Mon 2015-11-23 17:27:03, Tejun Heo wrote:
Hello,
On Wed, Nov 18, 2015 at 02:25:12PM +0100, Petr Mladek wrote:
quoted
@@ -610,6 +625,12 @@ repeat: if (work) { __set_current_state(TASK_RUNNING); work->func(work);++ spin_lock_irq(&worker->lock);+ /* Allow to queue the work into another worker */+ if (!kthread_work_pending(work))+ work->worker = NULL;+ spin_unlock_irq(&worker->lock);
Doesn't this mean that the work item can't be freed from its callback?
That pattern tends to happen regularly.
I am not sure if I understand your question. Do you mean switching
work->func during the life time of the struct kthread_work? This
should not be affected by the above code.
The above code allows to queue an _unused_ kthread_work into any
kthread_worker. For example, it is needed for khugepaged,
see http://marc.info/?l=linux-kernel&m=144785344924871&w=2
The work is static but the worker can be started/stopped
(allocated/freed) repeatedly. It means that the work need
to be usable with many workers. But it is associated only
with one worker when being used.
If the work is in use (pending or being proceed), we must not
touch work->worker. Otherwise there might be a race. Because
all the operations with the work are synchronized using
work->worker->lock.
I hope that it makes sense.
Thanks a lot for feedback,
Petr
Hello, Petr.
On Tue, Nov 24, 2015 at 11:06:50AM +0100, Petr Mladek wrote:
quoted
quoted
@@ -610,6 +625,12 @@ repeat: if (work) { __set_current_state(TASK_RUNNING); work->func(work);++ spin_lock_irq(&worker->lock);+ /* Allow to queue the work into another worker */+ if (!kthread_work_pending(work))+ work->worker = NULL;+ spin_unlock_irq(&worker->lock);
Doesn't this mean that the work item can't be freed from its callback?
That pattern tends to happen regularly.
I am not sure if I understand your question. Do you mean switching
work->func during the life time of the struct kthread_work? This
should not be affected by the above code.
So, something like the following.
void my_work_fn(work)
{
struct my_struct *s = container_of(work, ...);
do something with s;
kfree(s);
}
and the queuer does
struct my_struct *s = kmalloc(sizeof(*s));
init s and s->work;
queue(&s->work);
expecting s to be freed on completion. IOW, you can't expect the work
item to remain accessible once the work function starts executing.
The above code allows to queue an _unused_ kthread_work into any
kthread_worker. For example, it is needed for khugepaged,
see http://marc.info/?l=linux-kernel&m=144785344924871&w=2
The work is static but the worker can be started/stopped
(allocated/freed) repeatedly. It means that the work need
to be usable with many workers. But it is associated only
with one worker when being used.
It can just re-init work items when it restarts workers, right?
Thanks.
--
tejun
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-24 16:29:04
On Tue 2015-11-24 09:49:42, Tejun Heo wrote:
Hello, Petr.
On Tue, Nov 24, 2015 at 11:06:50AM +0100, Petr Mladek wrote:
quoted
quoted
quoted
@@ -610,6 +625,12 @@ repeat: if (work) { __set_current_state(TASK_RUNNING); work->func(work);++ spin_lock_irq(&worker->lock);+ /* Allow to queue the work into another worker */+ if (!kthread_work_pending(work))+ work->worker = NULL;+ spin_unlock_irq(&worker->lock);
Doesn't this mean that the work item can't be freed from its callback?
That pattern tends to happen regularly.
I am not sure if I understand your question. Do you mean switching
work->func during the life time of the struct kthread_work? This
should not be affected by the above code.
IOW, you can't expect the work
item to remain accessible once the work function starts executing.
I see, I was not aware of this pattern.
quoted
The above code allows to queue an _unused_ kthread_work into any
kthread_worker. For example, it is needed for khugepaged,
see http://marc.info/?l=linux-kernel&m=144785344924871&w=2
The work is static but the worker can be started/stopped
(allocated/freed) repeatedly. It means that the work need
to be usable with many workers. But it is associated only
with one worker when being used.
It can just re-init work items when it restarts workers, right?
Yes, this would work. It might be slightly inconvenient but
it looks like a good compromise. It helps to keep the API
implementation rather simple and rather secure.
Alternatively, we could allow to queue the work on another worker
if it is not pending. But then we would need to check the pending
status without the worker->lock because work->worker might point
to an already freed worker. We need to check the pending
status in many situations. It might open a can of worms that
I probably do not want to catch.
Thank you and PeterZ for explanation,
Petr
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Peter Zijlstra <peterz@infradead.org> Date: 2015-11-24 14:56:54
On Tue, Nov 24, 2015 at 11:06:50AM +0100, Petr Mladek wrote:
On Mon 2015-11-23 17:27:03, Tejun Heo wrote:
quoted
Hello,
On Wed, Nov 18, 2015 at 02:25:12PM +0100, Petr Mladek wrote:
quoted
@@ -610,6 +625,12 @@ repeat: if (work) { __set_current_state(TASK_RUNNING); work->func(work);++ spin_lock_irq(&worker->lock);+ /* Allow to queue the work into another worker */+ if (!kthread_work_pending(work))+ work->worker = NULL;+ spin_unlock_irq(&worker->lock);
Doesn't this mean that the work item can't be freed from its callback?
That pattern tends to happen regularly.
I am not sure if I understand your question. Do you mean switching
work->func during the life time of the struct kthread_work? This
should not be affected by the above code.
No, work->func(work) doing: kfree(work).
That is indeed something quite frequently done, and since you now have
references to work after calling func, things would go *boom* rather
quickly.
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:26:52
We are going to use kthread workers more widely and sometimes we will need
to make sure that the work is neither pending nor running.
This patch implements cancel_*_sync() operations as inspired by
workqueues. Well, we are synchronized against the other operations
via the worker lock, we use del_timer_sync() and a counter to count
parallel cancel operations. Therefore the implementation might be easier.
First, we try to lock the work. If it does not work, it means that
no worker is assigned and that we are done.
Second, we try to cancel the timer when it exists. A problem is when
the timer callback is running at the same time. In this case, we need
to release the lock to avoid a deadlock and start from the beginning.
Third, we try to remove the work from the worker list.
Fourth, if the work is running, we call flush_kthread_work(). It might
take an arbitrary time. In the meantime, queuing of the work is blocked
by the new canceling counter.
As already mentioned, the check for a pending kthread work is done under
a lock. In compare with workqueues, we do not need to fight for a single
PENDING bit to block other operations. Therefore do not suffer from
the thundering storm problem and all parallel canceling jobs might use
kthread_work_flush(). Any queuing is blocked until the counter is zero.
Signed-off-by: Petr Mladek <pmladek@suse.com>
---
include/linux/kthread.h | 4 ++
kernel/kthread.c | 142 ++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 146 insertions(+)
@@ -950,6 +952,146 @@ retry:EXPORT_SYMBOL_GPL(flush_kthread_work);/**+*try_to_cancel_kthread_work-Trytocancelkthreadwork.+*@work:workitemtocancel+*@lock:lockusedtoprotectthework+*@flags:flagsstoredwhenthelockwastaken+*+*Thisfunctiontriestocancelthegivenkthreadworkbydeleting+*thetimerandbyremovingtheworkfromthequeue.+*+*Ifthetimercallbackisinprogress,itwaitsuntilitfinishes+*butithastodropthelocktoavoidadeadlock.+*+*Return:+*1if@workwaspendingandsuccessfullycanceled+*0if@workwasnotpending+*-EAGAINifthelockwasdropped.Thecallerissupposedto+*takethelockagainandrepeattheoperation.+*/+staticint+try_to_cancel_kthread_work(structkthread_work*work,+spinlock_t*lock,+unsignedlong*flags)+{+intret=0;++if(work->timer){+/* Try to cancel the timer if pending. */+if(del_timer(work->timer)){+ret=1;+gotoout;+}++/* Are we racing with the timer callback? */+if(timer_active(work->timer)){+/* Bad luck, need to avoid a deadlock. */+spin_unlock_irqrestore(lock,*flags);+del_timer_sync(work->timer);+ret=-EAGAIN;+gotoout;+}+}++/* Try to remove queued work before it is being executed. */+if(!list_empty(&work->node)){+list_del_init(&work->node);+ret=1;+}++out:+returnret;+}++staticbool__cancel_kthread_work_sync(structkthread_work*work)+{+structkthread_worker*worker;+unsignedlongflags;+intret;++try_again:+local_irq_save(flags);+if(!try_lock_kthread_work(work)){+local_irq_restore(flags);+ret=0;+gotoout;+}+worker=work->worker;++ret=try_to_cancel_kthread_work(work,&worker->lock,&flags);+if(ret==-EAGAIN)+gototry_again;++if(worker->current_work!=work)+gotoout_fast;++/*+*Needtowaituntiltheworkfinished.Blockqueueing+*inthemeantime.+*/+work->canceling++;+spin_unlock_irqrestore(&worker->lock,flags);+flush_kthread_work(work);+/*+*Nobodyisallowedtoswitchtheworkerorqueuethework+*when.cancelingisset+*/+spin_lock_irqsave(&worker->lock,flags);+work->canceling--;++out_fast:+/*+*Allowtoqueuetheworkintoanotherworkerifthereisnoother+*pendingoperation.+*/+if(!work->canceling)+work->worker=NULL;+spin_unlock_irqrestore(&worker->lock,flags);++out:+returnret;+}++/**+*cancel_kthread_work_sync-cancelakthreadworkandwaitforittofinish+*@work:thekthreadworktocancel+*+*Cancel@workandwaitforitsexecutiontofinish.Thisfunction+*canbeusedeveniftheworkre-queuesitself.Onreturnfromthis+*function,@workisguaranteedtobenotpendingorexecutingonanyCPU.+*+*Thecallermustensurethattheworkeronwhich@workwaslast+*queuedcan'tbedestroyedbeforethisfunctionreturns.+*+*Return:+*%trueif@workwaspending,%falseotherwise.+*/+boolcancel_kthread_work_sync(structkthread_work*work)+{+/* Rather use cancel_delayed_kthread_work() for delayed works. */+WARN_ON_ONCE(work->timer);++return__cancel_kthread_work_sync(work);+}+EXPORT_SYMBOL_GPL(cancel_kthread_work_sync);++/**+*cancel_delayed_kthread_work_sync-canceladelayedkthreadworkand+*waitforittofinish.+*@dwork:thedelayedkthreadworktocancel+*+*Thisiscancel_kthread_work_sync()fordelayedworks.+*+*Return:+*%trueif@dworkwaspending,%falseotherwise.+*/+boolcancel_delayed_kthread_work_sync(structdelayed_kthread_work*dwork)+{+return__cancel_kthread_work_sync(&dwork->work);+}+EXPORT_SYMBOL_GPL(cancel_delayed_kthread_work_sync);++/***flush_kthread_worker-flushallcurrentworksonakthread_worker*@worker:workertoflush*
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
Hello,
On Wed, Nov 18, 2015 at 02:25:14PM +0100, Petr Mladek wrote:
+static int
+try_to_cancel_kthread_work(struct kthread_work *work,
+ spinlock_t *lock,
+ unsigned long *flags)
+{
+ int ret = 0;
+
+ if (work->timer) {
+ /* Try to cancel the timer if pending. */
+ if (del_timer(work->timer)) {
+ ret = 1;
+ goto out;
+ }
+
+ /* Are we racing with the timer callback? */
+ if (timer_active(work->timer)) {
+ /* Bad luck, need to avoid a deadlock. */
+ spin_unlock_irqrestore(lock, *flags);
+ del_timer_sync(work->timer);
+ ret = -EAGAIN;
+ goto out;
+ }
As the timer side is already kinda trylocking anyway, can't the cancel
path be made simpler? Sth like
lock(worker);
work->canceling = true;
del_timer_sync(work->timer);
unlock(worker);
And the timer can do (ignoring the multiple worker support, do we even
need that?)
while (!trylock(worker)) {
if (work->canceling)
return;
cpu_relax();
}
queue;
unlock(worker);
Thanks.
--
tejun
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-24 10:21:47
On Mon 2015-11-23 17:58:23, Tejun Heo wrote:
Hello,
On Wed, Nov 18, 2015 at 02:25:14PM +0100, Petr Mladek wrote:
quoted
+static int
+try_to_cancel_kthread_work(struct kthread_work *work,
+ spinlock_t *lock,
+ unsigned long *flags)
+{
+ int ret = 0;
+
+ if (work->timer) {
+ /* Try to cancel the timer if pending. */
+ if (del_timer(work->timer)) {
+ ret = 1;
+ goto out;
+ }
+
+ /* Are we racing with the timer callback? */
+ if (timer_active(work->timer)) {
+ /* Bad luck, need to avoid a deadlock. */
+ spin_unlock_irqrestore(lock, *flags);
+ del_timer_sync(work->timer);
+ ret = -EAGAIN;
+ goto out;
+ }
As the timer side is already kinda trylocking anyway, can't the cancel
path be made simpler? Sth like
lock(worker);
work->canceling = true;
del_timer_sync(work->timer);
unlock(worker);
And the timer can do (ignoring the multiple worker support, do we even
need that?)
while (!trylock(worker)) {
if (work->canceling)
return;
cpu_relax();
}
queue;
unlock(worker);
Why did I not find out this myself ?:-)
Thanks for hint,
Petr
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
On Mon, Nov 23, 2015 at 2:58 PM, Tejun Heo [off-list ref] wrote:
And the timer can do (ignoring the multiple worker support, do we even
need that?)
while (!trylock(worker)) {
if (work->canceling)
return;
cpu_relax();
}
No no no!
People, you need to learn that code like the above is *not*
acceptable. It's busy-looping on a spinlock, and constantly trying to
*write* to the spinlock.
It will literally crater performance on a multi-socket SMP system if
it ever triggers. We're talking 10x slowdowns, and absolutely
unacceptable cache coherency traffic.
These kinds of loops absolutely *have* to have the read-only part. The
"cpu_relax()" above needs to be a loop that just tests the lock state
by *reading* it, so the cpu_relax() needs to be replaced with
something like
while (spin_is_locked(lock)) cpu_relax();
instead (possibly just "spin_unlock_wait()" - but the explicit loop
might be worth it if you then want to check the "canceling" flag
independently of the lock state too).
In general, it's very dangerous to try to cook up your own locking
rules. People *always* get it wrong.
Linus
Hello,
On Tue, Nov 24, 2015 at 12:23:53PM -0800, Linus Torvalds wrote:
instead (possibly just "spin_unlock_wait()" - but the explicit loop
I see. Wasn't thinking about cache traffic. Yeah, spin_unlock_wait()
seems a lot better.
might be worth it if you then want to check the "canceling" flag
independently of the lock state too).
In general, it's very dangerous to try to cook up your own locking
rules. People *always* get it wrong.
It's either trylock on timer side or timer active spinning trick on
canceling side, so this seems the lesser of the two evils.
Thanks.
--
tejun
On Tue, Nov 24, 2015 at 12:28 PM, Tejun Heo [off-list ref] wrote:
quoted
In general, it's very dangerous to try to cook up your own locking
rules. People *always* get it wrong.
It's either trylock on timer side or timer active spinning trick on
canceling side, so this seems the lesser of the two evils.
I'm not saying the approach is wrong.
I'm saying that people need to realize that locking is harder than
they think, and not cook up their own lock primitives using things
like trylock without really thinking about it a *lot*.
Basically, "trylock()" on its own should never be used in a loop. The
main use for trylock should be one of:
- thing that you can just not do at all if you can't get the lock
- avoiding ABBA deadlocks: if you have a A->B locking order, but you
already hold B, instead of "drop B, then take A and B in the right
order", you may decide to first "trylock(A)" - and if that fails you
then fall back on the "drop and relock in the right order".
but if what you want to create is a "get lock using trylock", you need
to be very aware of the cache coherency traffic issue at least.
It is possible that we should think about trying to introduce a new
primitive for that "loop_try_lock()" thing. But it's probably not
common enough to be worth it - we've had this issue before, but I
think it's a "once every couple of years" kind of thing rather than
anything that we need to worry about.
The "locking is hard" issue is very real, though. We've traditionally
had a *lot* of code that tried to do its own locking, and not getting
the memory ordering right etc. Things that happen to work on x86 but
don't on other architectures etc.
Linus
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:26:55
There are situations when we need to modify the delay of a delayed kthread
work. For example, when the work depends on an event and the initial delay
means a timeout. Then we want to queue the work immediately when the event
happens.
This patch implements mod_delayed_kthread_work() as inspired workqueues.
It tries to cancel the pending work and queue it again with the
given timeout.
A very special case is when the work is being canceled at the same time.
cancel_*kthread_work_sync() operation blocks queuing until the running
work finishes. Therefore we do nothing and let cancel() win. This should
not normally happen as the caller is supposed to synchronize these
operations a reasonable way.
Signed-off-by: Petr Mladek <pmladek@suse.com>
---
include/linux/kthread.h | 4 ++++
kernel/kthread.c | 50 +++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 54 insertions(+)
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:27:02
This patch allows to make kthread worker freezable via a new @flags
parameter. It will allow to avoid an init work in some kthreads.
It currently does not affect the function of kthread_worker_fn()
but it might help to do some optimization or fixes eventually.
I currently do not know about any other use for the @flags
parameter but I believe that we will want more flags
in the future.
Finally, I hope that it will not cause confusion with @flags member
in struct kthread. Well, I guess that we will want to rework the
basic kthreads implementation once all kthreads are converted into
kthread workers or workqueues. It is possible that we will merge
the two structures.
Signed-off-by: Petr Mladek <pmladek@suse.com>
---
include/linux/kthread.h | 11 ++++++++---
kernel/kthread.c | 17 ++++++++++++-----
2 files changed, 20 insertions(+), 8 deletions(-)
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:27:07
Kthreads are currently implemented as an infinite loop. Each
has its own variant of checks for terminating, freezing,
awakening. In many cases it is unclear to say in which state
it is and sometimes it is done a wrong way.
The plan is to convert kthreads into kthread_worker or workqueues
API. It allows to split the functionality into separate operations.
It helps to make a better structure. Also it defines a clean state
where no locks are taken, IRQs blocked, the kthread might sleep
or even be safely migrated.
The kthread worker API is useful when we want to have a dedicated
single thread for the work. It helps to make sure that it is
available when needed. Also it allows a better control, e.g.
define a scheduling priority.
This patch converts hungtaskd() in kthread worker API because
it modifies the priority.
The conversion is pretty straightforward. One iteration of the
main cycle is transferred into a self-queuing delayed kthread work.
We do not longer need to check if it was waken earlier. Instead,
the work timeout is modified when the timeout value is changed.
The user nice value is set from hung_task_init(). Otherwise, we
would need to add an extra init_work.
The patch also handles the error when the kthead worker could not
be crated from some reasons. It was broken before. For example,
wake_up_process would have failed if watchdog_task inclueded an error
code instead of a valid pointer.
Signed-off-by: Petr Mladek <pmladek@suse.com>
CC: linux-watchdog@vger.kernel.org
---
kernel/hung_task.c | 41 +++++++++++++++++++++++++----------------
1 file changed, 25 insertions(+), 16 deletions(-)
@@ -41,7 +41,9 @@ int __read_mostly sysctl_hung_task_warnings = 10;staticint__read_mostlydid_panic;-staticstructtask_struct*watchdog_task;+staticstructkthread_worker*watchdog_worker;+staticvoidwatchdog_func(structkthread_work*dummy);+staticDEFINE_DELAYED_KTHREAD_WORK(watchdog_work,watchdog_func);/**Shouldwepanic(andreboot,ifpanic_timeout=isset)whena
@@ -205,7 +207,9 @@ int proc_dohung_task_timeout_secs(struct ctl_table *table, int write,if(ret||!write)gotoout;-wake_up_process(watchdog_task);+if(watchdog_worker)+mod_delayed_kthread_work(watchdog_worker,&watchdog_work,+timeout_jiffies(sysctl_hung_task_timeout_secs));out:returnret;
@@ -222,30 +226,35 @@ EXPORT_SYMBOL_GPL(reset_hung_task_detector);/**kthreadwhichchecksfortasksstuckinDstate*/-staticintwatchdog(void*dummy)+staticvoidwatchdog_func(structkthread_work*dummy){-set_user_nice(current,0);+unsignedlongtimeout=sysctl_hung_task_timeout_secs;-for(;;){-unsignedlongtimeout=sysctl_hung_task_timeout_secs;+if(atomic_xchg(&reset_hung_task,0))+gotonext;-while(schedule_timeout_interruptible(timeout_jiffies(timeout)))-timeout=sysctl_hung_task_timeout_secs;+check_hung_uninterruptible_tasks(timeout);-if(atomic_xchg(&reset_hung_task,0))-continue;--check_hung_uninterruptible_tasks(timeout);-}--return0;+next:+queue_delayed_kthread_work(watchdog_worker,&watchdog_work,+timeout_jiffies(timeout));}staticint__inithung_task_init(void){+structkthread_worker*worker;+atomic_notifier_chain_register(&panic_notifier_list,&panic_block);-watchdog_task=kthread_run(watchdog,NULL,"khungtaskd");+worker=create_kthread_worker(0,"khungtaskd");+if(IS_ERR(worker)){+pr_warn("Failed to create khungtaskd\n");+gotoout;+}+watchdog_worker=worker;+set_user_nice(worker->task,0);+queue_delayed_kthread_work(worker,&watchdog_work,0);+out:return0;}subsys_initcall(hung_task_init);
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:27:10
Kthreads are currently implemented as an infinite loop. Each
has its own variant of checks for terminating, freezing,
awakening. In many cases it is unclear to say in which state
it is and sometimes it is done a wrong way.
The plan is to convert kthreads into kthread_worker or workqueues
API. It allows to split the functionality into separate operations.
It helps to make a better structure. Also it defines a clean state
where no locks are taken, IRQs blocked, the kthread might sleep
or even be safely migrated.
The kthread worker API is useful when we want to have a dedicated
single thread for the work. It helps to make sure that it is
available when needed. Also it allows a better control, e.g.
define a scheduling priority.
This patch converts the ring buffer benchmark producer into a kthread
worker because it modifies the scheduling priority and policy.
Also, it is a benchmark. It makes CPU very busy. It will most likely
run only limited time. IMHO, it does not make sense to mess the system
workqueues with it.
The thread is split into two independent works. It might look more
complicated but it helped me to find a race in the sleeping part
that was fixed separately.
kthread_should_stop() could not longer be used inside the works
because it defines the life of the worker and it needs to stay
usable until all works are done. Instead, we add @test_end
global variable. It is set during normal termination in compare
with @test_error.
Signed-off-by: Petr Mladek <pmladek@suse.com>
---
kernel/trace/ring_buffer_benchmark.c | 133 ++++++++++++++++-------------------
1 file changed, 59 insertions(+), 74 deletions(-)
@@ -281,14 +289,14 @@ static void ring_buffer_producer(void)}while(ktime_before(end_time,timeout)&&!break_test());trace_printk("End ring buffer hammer\n");-if(consumer){+if(rb_consumer_worker){/* Init both completions here to avoid races */init_completion(&read_start);init_completion(&read_done);/* the completions must be visible before the finish var */smp_wmb();reader_finish=1;-wake_up_process(consumer);+wake_up_process(rb_consumer_worker->task);wait_for_completion(&read_done);}
@@ -366,68 +374,39 @@ static void ring_buffer_producer(void)}}-staticvoidwait_to_die(void)-{-set_current_state(TASK_INTERRUPTIBLE);-while(!kthread_should_stop()){-schedule();-set_current_state(TASK_INTERRUPTIBLE);-}-__set_current_state(TASK_RUNNING);-}--staticintring_buffer_consumer_thread(void*arg)+staticvoidrb_consumer_func(structkthread_work*dummy){-while(!break_test()){-complete(&read_start);--ring_buffer_consumer();+complete(&read_start);-set_current_state(TASK_INTERRUPTIBLE);-if(break_test())-break;-schedule();-}-__set_current_state(TASK_RUNNING);--if(!kthread_should_stop())-wait_to_die();--return0;+ring_buffer_consumer();}-staticintring_buffer_producer_thread(void*arg)+staticvoidrb_producer_hammer_func(structkthread_work*dummy){-while(!break_test()){-ring_buffer_reset(buffer);+if(break_test())+return;-if(consumer){-wake_up_process(consumer);-wait_for_completion(&read_start);-}--ring_buffer_producer();-if(break_test())-gotoout_kill;+ring_buffer_reset(buffer);-trace_printk("Sleeping for 10 secs\n");-set_current_state(TASK_INTERRUPTIBLE);-if(break_test())-gotoout_kill;-schedule_timeout(HZ*SLEEP_TIME);+if(rb_consumer_worker){+queue_kthread_work(rb_consumer_worker,&rb_consumer_work);+wait_for_completion(&read_start);}-out_kill:-__set_current_state(TASK_RUNNING);-if(!kthread_should_stop())-wait_to_die();+ring_buffer_producer();-return0;+if(break_test())+return;++trace_printk("Sleeping for 10 secs\n");+queue_delayed_kthread_work(rb_producer_worker,+&rb_producer_hammer_work,+HZ*SLEEP_TIME);}staticint__initring_buffer_benchmark_init(void){-intret;+intret=0;/* make a one meg buffer in overwite mode */buffer=ring_buffer_alloc(1000000,RB_FL_OVERWRITE);
@@ -435,19 +414,21 @@ static int __init ring_buffer_benchmark_init(void)return-ENOMEM;if(!disable_reader){-consumer=kthread_create(ring_buffer_consumer_thread,-NULL,"rb_consumer");-ret=PTR_ERR(consumer);-if(IS_ERR(consumer))+rb_consumer_worker=create_kthread_worker(0,"rb_consumer");+if(IS_ERR(rb_consumer_worker)){+ret=PTR_ERR(rb_consumer_worker);gotoout_fail;+}}-producer=kthread_run(ring_buffer_producer_thread,-NULL,"rb_producer");-ret=PTR_ERR(producer);--if(IS_ERR(producer))+rb_producer_worker=create_kthread_worker(0,"rb_producer");+if(IS_ERR(rb_producer_worker)){+ret=PTR_ERR(rb_producer_worker);gotoout_kill;+}++queue_delayed_kthread_work(rb_producer_worker,+&rb_producer_hammer_work,0);/**Runthemaslow-priobackgroundtasksbydefault:
@@ -457,24 +438,26 @@ static int __init ring_buffer_benchmark_init(void)structsched_paramparam={.sched_priority=consumer_fifo};-sched_setscheduler(consumer,SCHED_FIFO,¶m);+sched_setscheduler(rb_consumer_worker->task,+SCHED_FIFO,¶m);}else-set_user_nice(consumer,consumer_nice);+set_user_nice(rb_consumer_worker->task,consumer_nice);}if(producer_fifo>=0){structsched_paramparam={.sched_priority=producer_fifo};-sched_setscheduler(producer,SCHED_FIFO,¶m);+sched_setscheduler(rb_producer_worker->task,+SCHED_FIFO,¶m);}else-set_user_nice(producer,producer_nice);+set_user_nice(rb_producer_worker->task,producer_nice);return0;out_kill:-if(consumer)-kthread_stop(consumer);+if(rb_consumer_worker)+destroy_kthread_worker(rb_consumer_worker);out_fail:ring_buffer_free(buffer);
@@ -483,9 +466,11 @@ static int __init ring_buffer_benchmark_init(void)staticvoid__exitring_buffer_benchmark_exit(void){-kthread_stop(producer);-if(consumer)-kthread_stop(consumer);+test_end=1;+cancel_delayed_kthread_work_sync(&rb_producer_hammer_work);+destroy_kthread_worker(rb_producer_worker);+if(rb_consumer_worker)+destroy_kthread_worker(rb_consumer_worker);ring_buffer_free(buffer);}
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:27:27
Kthreads are currently implemented as an infinite loop. Each
has its own variant of checks for terminating, freezing,
awakening. In many cases it is unclear to say in which state
it is and sometimes it is done a wrong way.
The plan is to convert kthreads into kthread_worker or workqueues
API. It allows to split the functionality into separate operations.
It helps to make a better structure. Also it defines a clean state
where no locks are taken, IRQs blocked, the kthread might sleep
or even be safely migrated.
The kthread worker API is useful when we want to have a dedicated
single thread for the work. It helps to make sure that it is
available when needed. Also it allows a better control, e.g.
define a scheduling priority.
This patch converts kipmi kthread into the kthread worker API because
it modifies the scheduling priority. The change is quite straightforward.
First, we move the per-thread variable "busy_until" into the per-thread
structure struct smi_info. As a side effect, we could omit one parameter
in ipmi_thread_busy_wait(). On the other hand, the structure could not
longer be passed with the const qualifier.
The value of "busy_until" is initialized when the kthread is created.
Also the scheduling priority is set there. This helps to avoid an extra
init work.
One iteration of the kthread cycle is moved to a delayed work function.
The different delays between the cycles are solved the following way:
+ immediate cycle (nope) is converted into goto within the same work
+ immediate cycle with a possible reschedule is converted into
re-queuing with a zero delay
+ schedule_timeout() is converted into re-queuing with the given
delay
+ interruptible sleep is converted into nothing; The work
will get queued again from the check_start_timer_thread().
By other words the external wakeup_up_process() will get
replaced by queuing with a zero delay.
Probably the most tricky change is when the worker is being stopped.
We need to explicitly cancel the work to prevent it from re-queuing.
Signed-off-by: Petr Mladek <pmladek@suse.com>
CC: Corey Minyard <redacted>
CC: openipmi-developer@lists.sourceforge.net
---
drivers/char/ipmi/ipmi_si_intf.c | 116 ++++++++++++++++++++++-----------------
1 file changed, 66 insertions(+), 50 deletions(-)
@@ -302,7 +302,9 @@ struct smi_info {/* Counters and things for the proc filesystem. */atomic_tstats[SI_NUM_STATS];-structtask_struct*thread;+structkthread_worker*worker;+structdelayed_kthread_workwork;+structtimespec64busy_until;structlist_headlink;unionipmi_smi_info_unionaddr_info;
@@ -1008,10 +1011,10 @@ static inline int ipmi_si_is_busy(struct timespec64 *ts)}staticinlineintipmi_thread_busy_wait(enumsi_sm_resultsmi_result,-conststructsmi_info*smi_info,-structtimespec64*busy_until)+structsmi_info*smi_info){unsignedintmax_busy_us=0;+structtimespec64*busy_until=&smi_info->busy_until;if(smi_info->intf_num<num_max_busy_us)max_busy_us=kipmid_max_busy_us[smi_info->intf_num];
@@ -1042,53 +1045,49 @@ static inline int ipmi_thread_busy_wait(enum si_sm_result smi_result,*(ifthatisenabled).Seetheparagraphonkimid_max_busy_usin*Documentation/IPMI.txtfordetails.*/-staticintipmi_thread(void*data)+staticvoidipmi_func(structkthread_work*work){-structsmi_info*smi_info=data;+structsmi_info*smi_info=container_of(work,structsmi_info,+work.work);unsignedlongflags;enumsi_sm_resultsmi_result;-structtimespec64busy_until;+intbusy_wait;-ipmi_si_set_not_busy(&busy_until);-set_user_nice(current,MAX_NICE);-while(!kthread_should_stop()){-intbusy_wait;+next:+spin_lock_irqsave(&(smi_info->si_lock),flags);+smi_result=smi_event_handler(smi_info,0);-spin_lock_irqsave(&(smi_info->si_lock),flags);-smi_result=smi_event_handler(smi_info,0);+/*+*Ifthedriverisdoingsomething,thereisapossible+*racewiththetimer.Ifthetimerhandlerseeidle,+*andthethreadhereseessomethingelse,thetimer+*handlerwon'trestartthetimereventhoughitis+*required.Sostartithereifnecessary.+*/+if(smi_result!=SI_SM_IDLE&&!smi_info->timer_running)+smi_mod_timer(smi_info,jiffies+SI_TIMEOUT_JIFFIES);-/*-*Ifthedriverisdoingsomething,thereisapossible-*racewiththetimer.Ifthetimerhandlerseeidle,-*andthethreadhereseessomethingelse,thetimer-*handlerwon'trestartthetimereventhoughitis-*required.Sostartithereifnecessary.-*/-if(smi_result!=SI_SM_IDLE&&!smi_info->timer_running)-smi_mod_timer(smi_info,jiffies+SI_TIMEOUT_JIFFIES);--spin_unlock_irqrestore(&(smi_info->si_lock),flags);-busy_wait=ipmi_thread_busy_wait(smi_result,smi_info,-&busy_until);-if(smi_result==SI_SM_CALL_WITHOUT_DELAY)-;/* do nothing */-elseif(smi_result==SI_SM_CALL_WITH_DELAY&&busy_wait)-schedule();-elseif(smi_result==SI_SM_IDLE){-if(atomic_read(&smi_info->need_watch)){-schedule_timeout_interruptible(100);-}else{-/* Wait to be woken up when we are needed. */-__set_current_state(TASK_INTERRUPTIBLE);-schedule();-}-}else-schedule_timeout_interruptible(1);+spin_unlock_irqrestore(&(smi_info->si_lock),flags);+busy_wait=ipmi_thread_busy_wait(smi_result,smi_info);++if(smi_result==SI_SM_CALL_WITHOUT_DELAY)+gotonext;+if(smi_result==SI_SM_CALL_WITH_DELAY&&busy_wait){+queue_delayed_kthread_work(smi_info->worker,+&smi_info->work,0);+}elseif(smi_result==SI_SM_IDLE){+if(atomic_read(&smi_info->need_watch)){+queue_delayed_kthread_work(smi_info->worker,+&smi_info->work,100);+}else{+/* Nope. Wait to be queued when we are needed. */+}+}else{+queue_delayed_kthread_work(smi_info->worker,+&smi_info->work,1);}-return0;}-staticvoidpoll(void*send_info){structsmi_info*smi_info=send_info;
@@ -1229,17 +1228,29 @@ static int smi_start_processing(void *send_info,enable=1;if(enable){-new_smi->thread=kthread_run(ipmi_thread,new_smi,-"kipmi%d",new_smi->intf_num);-if(IS_ERR(new_smi->thread)){+structkthread_worker*worker;++worker=create_kthread_worker(0,"kipmi%d",+new_smi->intf_num);++if(IS_ERR(worker)){dev_notice(new_smi->dev,"Could not start"" kernel thread due to error %ld, only using"" timers to drive the interface\n",-PTR_ERR(new_smi->thread));-new_smi->thread=NULL;+PTR_ERR(worker));+gotoout;}++ipmi_si_set_not_busy(&new_smi->busy_until);+set_user_nice(worker->task,MAX_NICE);++init_delayed_kthread_work(&new_smi->work,ipmi_func);+queue_delayed_kthread_work(worker,&new_smi->work,0);++new_smi->worker=worker;}+out:return0;}
Kthreads are currently implemented as an infinite loop. Each
has its own variant of checks for terminating, freezing,
awakening. In many cases it is unclear to say in which state
it is and sometimes it is done a wrong way.
The plan is to convert kthreads into kthread_worker or workqueues
API. It allows to split the functionality into separate operations.
It helps to make a better structure. Also it defines a clean state
where no locks are taken, IRQs blocked, the kthread might sleep
or even be safely migrated.
The kthread worker API is useful when we want to have a dedicated
single thread for the work. It helps to make sure that it is
available when needed. Also it allows a better control, e.g.
define a scheduling priority.
This patch converts kipmi kthread into the kthread worker API because
it modifies the scheduling priority. The change is quite straightforward.
I think this is correct. That code was hard to get right, but I don't
see where any
logic is actually changed.
This also doesn't really look any simpler (you end up with more LOC than
you did before :) ),
though it will make things more consistent and reduce errors and that's
a good thing.
My only comment is I would like the worker function named ipmi_worker,
not ipmi_func.
Reviewed-by: Corey Minyard <redacted>
quoted hunk
First, we move the per-thread variable "busy_until" into the per-thread
structure struct smi_info. As a side effect, we could omit one parameter
in ipmi_thread_busy_wait(). On the other hand, the structure could not
longer be passed with the const qualifier.
The value of "busy_until" is initialized when the kthread is created.
Also the scheduling priority is set there. This helps to avoid an extra
init work.
One iteration of the kthread cycle is moved to a delayed work function.
The different delays between the cycles are solved the following way:
+ immediate cycle (nope) is converted into goto within the same work
+ immediate cycle with a possible reschedule is converted into
re-queuing with a zero delay
+ schedule_timeout() is converted into re-queuing with the given
delay
+ interruptible sleep is converted into nothing; The work
will get queued again from the check_start_timer_thread().
By other words the external wakeup_up_process() will get
replaced by queuing with a zero delay.
Probably the most tricky change is when the worker is being stopped.
We need to explicitly cancel the work to prevent it from re-queuing.
Signed-off-by: Petr Mladek <pmladek@suse.com>
CC: Corey Minyard <redacted>
CC: openipmi-developer@lists.sourceforge.net
---
drivers/char/ipmi/ipmi_si_intf.c | 116 ++++++++++++++++++++++-----------------
1 file changed, 66 insertions(+), 50 deletions(-)
@@ -302,7 +302,9 @@ struct smi_info {/* Counters and things for the proc filesystem. */atomic_tstats[SI_NUM_STATS];-structtask_struct*thread;+structkthread_worker*worker;+structdelayed_kthread_workwork;+structtimespec64busy_until;structlist_headlink;unionipmi_smi_info_unionaddr_info;
@@ -1008,10 +1011,10 @@ static inline int ipmi_si_is_busy(struct timespec64 *ts)}staticinlineintipmi_thread_busy_wait(enumsi_sm_resultsmi_result,-conststructsmi_info*smi_info,-structtimespec64*busy_until)+structsmi_info*smi_info){unsignedintmax_busy_us=0;+structtimespec64*busy_until=&smi_info->busy_until;if(smi_info->intf_num<num_max_busy_us)max_busy_us=kipmid_max_busy_us[smi_info->intf_num];
@@ -1042,53 +1045,49 @@ static inline int ipmi_thread_busy_wait(enum si_sm_result smi_result,*(ifthatisenabled).Seetheparagraphonkimid_max_busy_usin*Documentation/IPMI.txtfordetails.*/-staticintipmi_thread(void*data)+staticvoidipmi_func(structkthread_work*work){-structsmi_info*smi_info=data;+structsmi_info*smi_info=container_of(work,structsmi_info,+work.work);unsignedlongflags;enumsi_sm_resultsmi_result;-structtimespec64busy_until;+intbusy_wait;-ipmi_si_set_not_busy(&busy_until);-set_user_nice(current,MAX_NICE);-while(!kthread_should_stop()){-intbusy_wait;+next:+spin_lock_irqsave(&(smi_info->si_lock),flags);+smi_result=smi_event_handler(smi_info,0);-spin_lock_irqsave(&(smi_info->si_lock),flags);-smi_result=smi_event_handler(smi_info,0);+/*+*Ifthedriverisdoingsomething,thereisapossible+*racewiththetimer.Ifthetimerhandlerseeidle,+*andthethreadhereseessomethingelse,thetimer+*handlerwon'trestartthetimereventhoughitis+*required.Sostartithereifnecessary.+*/+if(smi_result!=SI_SM_IDLE&&!smi_info->timer_running)+smi_mod_timer(smi_info,jiffies+SI_TIMEOUT_JIFFIES);-/*-*Ifthedriverisdoingsomething,thereisapossible-*racewiththetimer.Ifthetimerhandlerseeidle,-*andthethreadhereseessomethingelse,thetimer-*handlerwon'trestartthetimereventhoughitis-*required.Sostartithereifnecessary.-*/-if(smi_result!=SI_SM_IDLE&&!smi_info->timer_running)-smi_mod_timer(smi_info,jiffies+SI_TIMEOUT_JIFFIES);--spin_unlock_irqrestore(&(smi_info->si_lock),flags);-busy_wait=ipmi_thread_busy_wait(smi_result,smi_info,-&busy_until);-if(smi_result==SI_SM_CALL_WITHOUT_DELAY)-;/* do nothing */-elseif(smi_result==SI_SM_CALL_WITH_DELAY&&busy_wait)-schedule();-elseif(smi_result==SI_SM_IDLE){-if(atomic_read(&smi_info->need_watch)){-schedule_timeout_interruptible(100);-}else{-/* Wait to be woken up when we are needed. */-__set_current_state(TASK_INTERRUPTIBLE);-schedule();-}-}else-schedule_timeout_interruptible(1);+spin_unlock_irqrestore(&(smi_info->si_lock),flags);+busy_wait=ipmi_thread_busy_wait(smi_result,smi_info);++if(smi_result==SI_SM_CALL_WITHOUT_DELAY)+gotonext;+if(smi_result==SI_SM_CALL_WITH_DELAY&&busy_wait){+queue_delayed_kthread_work(smi_info->worker,+&smi_info->work,0);+}elseif(smi_result==SI_SM_IDLE){+if(atomic_read(&smi_info->need_watch)){+queue_delayed_kthread_work(smi_info->worker,+&smi_info->work,100);+}else{+/* Nope. Wait to be queued when we are needed. */+}+}else{+queue_delayed_kthread_work(smi_info->worker,+&smi_info->work,1);}-return0;}-staticvoidpoll(void*send_info){structsmi_info*smi_info=send_info;
@@ -1229,17 +1228,29 @@ static int smi_start_processing(void *send_info,enable=1;if(enable){-new_smi->thread=kthread_run(ipmi_thread,new_smi,-"kipmi%d",new_smi->intf_num);-if(IS_ERR(new_smi->thread)){+structkthread_worker*worker;++worker=create_kthread_worker(0,"kipmi%d",+new_smi->intf_num);++if(IS_ERR(worker)){dev_notice(new_smi->dev,"Could not start"" kernel thread due to error %ld, only using"" timers to drive the interface\n",-PTR_ERR(new_smi->thread));-new_smi->thread=NULL;+PTR_ERR(worker));+gotoout;}++ipmi_si_set_not_busy(&new_smi->busy_until);+set_user_nice(worker->task,MAX_NICE);++init_delayed_kthread_work(&new_smi->work,ipmi_func);+queue_delayed_kthread_work(worker,&new_smi->work,0);++new_smi->worker=worker;}+out:return0;}
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-24 12:12:38
On Mon 2015-11-23 13:36:06, Corey Minyard wrote:
On 11/18/2015 07:25 AM, Petr Mladek wrote:
quoted
Kthreads are currently implemented as an infinite loop. Each
has its own variant of checks for terminating, freezing,
awakening. In many cases it is unclear to say in which state
it is and sometimes it is done a wrong way.
The plan is to convert kthreads into kthread_worker or workqueues
API. It allows to split the functionality into separate operations.
It helps to make a better structure. Also it defines a clean state
where no locks are taken, IRQs blocked, the kthread might sleep
or even be safely migrated.
The kthread worker API is useful when we want to have a dedicated
single thread for the work. It helps to make sure that it is
available when needed. Also it allows a better control, e.g.
define a scheduling priority.
This patch converts kipmi kthread into the kthread worker API because
it modifies the scheduling priority. The change is quite straightforward.
I think this is correct. That code was hard to get right, but I don't
see where any
logic is actually changed.
I believe that it was hard to make it working.
This also doesn't really look any simpler (you end up with more LOC than
you did before :) ),
though it will make things more consistent and reduce errors and that's
a good thing.
I have just realized that the original code actually looks racy. For
example, it does:
__set_current_state(TASK_INTERRUPTIBLE);
schedule();
without rechecking the state in between. There might already be a new
message and it might miss the wake_up_process(). Similar problem is
with the schedule_timeout_interruptible(100); I mean:
CPU 0 CPU 1
ipmi_thread()
spin_lock_irqsave();
smi_result = smi_event_handler();
spin_unlock_irqrestore();
[...]
else if (smi_result == SI_SM_IDLE)
/* true */
if (atomic_read(need_watch)) {
/* true */
sender()
spin_lock_irqsave()
check_start_timer_thread()
wake_up_process()
/*
* NOPE because kthread
* is not sleeping
*/
schedule_timeout_interruptible(100);
/*
* We sleep 100 jiffies but
* there is a pending message.
*/
This is not a problem with the kthread worker API because
mod_delayed_kthread_work(smi_info->worker,
&smi_info->work, 0);
would queue the work to be done immediately and
queue_delayed_kthread_work(smi_info->worker,
&smi_info->work, 100);
would do nothing in this case.
My only comment is I would like the worker function named ipmi_worker,
not ipmi_func.
You probably want it because the original name was ipmi_thread. But
it might cause confusion with new_smi->worker. The function gets
assigned to work->func, see struct kthread_work. Therefore I think that
_func suffix makes more sense.
Kthreads are currently implemented as an infinite loop. Each
has its own variant of checks for terminating, freezing,
awakening. In many cases it is unclear to say in which state
it is and sometimes it is done a wrong way.
The plan is to convert kthreads into kthread_worker or workqueues
API. It allows to split the functionality into separate operations.
It helps to make a better structure. Also it defines a clean state
where no locks are taken, IRQs blocked, the kthread might sleep
or even be safely migrated.
The kthread worker API is useful when we want to have a dedicated
single thread for the work. It helps to make sure that it is
available when needed. Also it allows a better control, e.g.
define a scheduling priority.
This patch converts kipmi kthread into the kthread worker API because
it modifies the scheduling priority. The change is quite straightforward.
I think this is correct. That code was hard to get right, but I don't
see where any
logic is actually changed.
I believe that it was hard to make it working.
quoted
This also doesn't really look any simpler (you end up with more LOC than
you did before :) ),
though it will make things more consistent and reduce errors and that's
a good thing.
I have just realized that the original code actually looks racy. For
example, it does:
__set_current_state(TASK_INTERRUPTIBLE);
schedule();
without rechecking the state in between. There might already be a new
message and it might miss the wake_up_process(). Similar problem is
with the schedule_timeout_interruptible(100); I mean:
CPU 0 CPU 1
ipmi_thread()
spin_lock_irqsave();
smi_result = smi_event_handler();
spin_unlock_irqrestore();
[...]
else if (smi_result == SI_SM_IDLE)
/* true */
if (atomic_read(need_watch)) {
/* true */
sender()
spin_lock_irqsave()
check_start_timer_thread()
wake_up_process()
/*
* NOPE because kthread
* is not sleeping
*/
schedule_timeout_interruptible(100);
/*
* We sleep 100 jiffies but
* there is a pending message.
*/
Yes, I knew the code was racy, but this is a performance optimization and
it wasn't that important to get it perfect. The thread wouldn't actually
wait 100 jiffies, it would just be run by timer interrupts for that time.
This is not a problem with the kthread worker API because
mod_delayed_kthread_work(smi_info->worker,
&smi_info->work, 0);
would queue the work to be done immediately and
queue_delayed_kthread_work(smi_info->worker,
&smi_info->work, 100);
would do nothing in this case.
And indeed this is a lot better.
quoted
My only comment is I would like the worker function named ipmi_worker,
not ipmi_func.
You probably want it because the original name was ipmi_thread. But
it might cause confusion with new_smi->worker. The function gets
assigned to work->func, see struct kthread_work. Therefore I think that
_func suffix makes more sense.
My problem with _func is that it's way too generic. Is this a function
that handled IPMI messages? Message done handling? I'm not enamored
with my name, but I want something that gives a better indication of
what the function does. ipmi_kthread_worker_func() would be fine with me.
Thanks,
-corey
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:27:36
Kthreads are currently implemented as an infinite loop. Each
has its own variant of checks for terminating, freezing,
awakening. In many cases it is unclear to say in which state
it is and sometimes it is done a wrong way.
The plan is to convert kthreads into kthread_worker or workqueues
API. It allows to split the functionality into separate operations.
It helps to make a better structure. Also it defines a clean state
where no locks are taken, IRQs blocked, the kthread might sleep
or even be safely migrated.
The kthread worker API is useful when we want to have a dedicated
single thread for the work. It helps to make sure that it is
available when needed. Also it allows a better control, e.g.
define a scheduling priority.
This patch converts the frm_pool kthread into the kthread worker
API because I am not sure how busy the thread is. It is well
possible that it does not need a dedicated kthread and workqueues
would be perfectly fine. Well, the conversion between kthread
worker API and workqueues is pretty trivial.
The patch moves one iteration from the kthread into the work function.
It preserves the check for a spurious queuing (wake up). Then it
processes one request. Finally, it re-queues itself if more requests
are pending.
Otherwise, wake_up_process() is replaced by queuing the work.
Important: The change is only compile tested. I did not find an easy
way how to check it in a real life.
Signed-off-by: Petr Mladek <pmladek@suse.com>
CC: Doug Ledford <redacted>
CC: Sean Hefty <redacted>
CC: Hal Rosenstock <redacted>
CC: linux-rdma@vger.kernel.org
---
drivers/infiniband/core/fmr_pool.c | 54 ++++++++++++++++++--------------------
1 file changed, 25 insertions(+), 29 deletions(-)
@@ -412,7 +408,7 @@ int ib_flush_fmr_pool(struct ib_fmr_pool *pool)spin_unlock_irq(&pool->pool_lock);serial=atomic_inc_return(&pool->req_ser);-wake_up_process(pool->thread);+queue_kthread_work(pool->worker,&pool->work);if(wait_event_interruptible(pool->force_wait,atomic_read(&pool->flush_ser)-serial>=0))
@@ -526,7 +522,7 @@ int ib_fmr_pool_unmap(struct ib_pool_fmr *fmr)list_add_tail(&fmr->list,&pool->dirty_list);if(++pool->dirty_len>=pool->dirty_watermark){atomic_inc(&pool->req_ser);-wake_up_process(pool->thread);+queue_kthread_work(pool->worker,&pool->work);}}}
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
On Wed, Nov 18, 2015 at 02:25:23PM +0100, Petr Mladek wrote:
Kthreads are currently implemented as an infinite loop. Each
has its own variant of checks for terminating, freezing,
awakening. In many cases it is unclear to say in which state
it is and sometimes it is done a wrong way.
The plan is to convert kthreads into kthread_worker or workqueues
API. It allows to split the functionality into separate operations.
It helps to make a better structure. Also it defines a clean state
where no locks are taken, IRQs blocked, the kthread might sleep
or even be safely migrated.
The kthread worker API is useful when we want to have a dedicated
single thread for the work. It helps to make sure that it is
available when needed. Also it allows a better control, e.g.
define a scheduling priority.
This patch converts the frm_pool kthread into the kthread worker
s/frm/fmr
API because I am not sure how busy the thread is. It is well
possible that it does not need a dedicated kthread and workqueues
would be perfectly fine. Well, the conversion between kthread
worker API and workqueues is pretty trivial.
The patch moves one iteration from the kthread into the work function.
It preserves the check for a spurious queuing (wake up). Then it
processes one request. Finally, it re-queues itself if more requests
are pending.
Otherwise, wake_up_process() is replaced by queuing the work.
Important: The change is only compile tested. I did not find an easy
way how to check it in a real life.
What are the expectations?
quoted hunk
Signed-off-by: Petr Mladek <pmladek@suse.com>
CC: Doug Ledford <redacted>
CC: Sean Hefty <redacted>
CC: Hal Rosenstock <redacted>
CC: linux-rdma@vger.kernel.org
---
drivers/infiniband/core/fmr_pool.c | 54 ++++++++++++++++++--------------------
1 file changed, 25 insertions(+), 29 deletions(-)
--
1.8.5.6
--
To unsubscribe from this list: send the line "unsubscribe linux-rdma" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at http://vger.kernel.org/majordomo-info.html
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:27:43
There is an attempt to print debug messages when the kthread is waken
and when it goes into sleep. It does not work well because the spin lock
does not guard all manipulations with the thread state.
I did not find a way how to print a message when the kthread really
goes into sleep. Instead, I added a state variable. It clearly marks
when a series of IO requests is started and finished. It makes sure
that we always have a pair of started/done messages.
The only problem is that it will print these messages also when
the kthread is created and there is no real work. We might want
to use create_kthread() instead of run_kthread(). Then the kthread
will stay stopped until the first request.
Important: This change is only compile tested. I did not find an easy
way how to test it. This is why I was conservative and did not modify
the kthread creation.
Signed-off-by: Petr Mladek <pmladek@suse.com>
CC: Maxim Levitsky <maximlevitsky@gmail.com>
---
drivers/memstick/host/r592.c | 19 +++++++++----------
drivers/memstick/host/r592.h | 2 +-
2 files changed, 10 insertions(+), 11 deletions(-)
@@ -568,21 +568,24 @@ static int r592_process_thread(void *data){interror;structr592_device*dev=(structr592_device*)data;-unsignedlongflags;while(!kthread_should_stop()){-spin_lock_irqsave(&dev->io_thread_lock,flags);+if(!dev->io_started){+dbg_verbose("IO: started");+dev->io_started=true;+}+set_current_state(TASK_INTERRUPTIBLE);error=memstick_next_req(dev->host,&dev->req);-spin_unlock_irqrestore(&dev->io_thread_lock,flags);if(error){if(error==-ENXIO||error==-EAGAIN){-dbg_verbose("IO: done IO, sleeping");+dbg_verbose("IO: done");}else{dbg("IO: unknown error from ""memstick_next_req %d",error);}+dev->io_started=false;if(kthread_should_stop())set_current_state(TASK_RUNNING);
@@ -714,15 +717,11 @@ static int r592_set_param(struct memstick_host *host,staticvoidr592_submit_req(structmemstick_host*host){structr592_device*dev=memstick_priv(host);-unsignedlongflags;if(dev->req)return;-spin_lock_irqsave(&dev->io_thread_lock,flags);-if(wake_up_process(dev->io_thread))-dbg_verbose("IO thread woken to process requests");-spin_unlock_irqrestore(&dev->io_thread_lock,flags);+wake_up_process(dev->io_thread);}staticconststructpci_device_idr592_pci_id_tbl[]={
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:28:23
Kthreads are currently implemented as an infinite loop. Each
has its own variant of checks for terminating, freezing,
awakening. In many cases it is unclear to say in which state
it is and sometimes it is done a wrong way.
The plan is to convert kthreads into kthread_worker or workqueues
API. It allows to split the functionality into separate operations.
It helps to make a better structure. Also it defines a clean state
where no locks are taken, IRQs blocked, the kthread might sleep
or even be safely migrated.
The kthread worker API is useful when we want to have a dedicated
single thread for the work. It helps to make sure that it is
available when needed. Also it allows a better control, e.g.
define a scheduling priority.
This patch converts the r592_io kthread into the kthread worker
API. I am not sure how busy the kthread is and if anyone would
like to control the resources. It is well possible that a workqueue
would be perfectly fine. Well, the conversion between kthread
worker API and workqueues is pretty trivial.
The patch moves one iteration from the kthread into the kthread
worker function. It helps to remove all the hackery with process
state and kthread_should_stop().
The work is queued instead of waking the thread.
The work is explicitly canceled before the worker is destroyed.
It is self-queuing and it might take a long time until the queue
is drained, otherwise.
Important: The change is only compile tested. I did not find an easy
way how to check it in use.
Signed-off-by: Petr Mladek <pmladek@suse.com>
CC: Maxim Levitsky <maximlevitsky@gmail.com>
---
drivers/memstick/host/r592.c | 58 ++++++++++++++++++++------------------------
drivers/memstick/host/r592.h | 3 ++-
2 files changed, 28 insertions(+), 33 deletions(-)
@@ -563,40 +563,32 @@ out:return;}-/* Main request processing thread */-staticintr592_process_thread(void*data)+/* Main request processing work */+staticvoidr592_process_func(structkthread_work*work){interror;-structr592_device*dev=(structr592_device*)data;--while(!kthread_should_stop()){-if(!dev->io_started){-dbg_verbose("IO: started");-dev->io_started=true;-}--set_current_state(TASK_INTERRUPTIBLE);-error=memstick_next_req(dev->host,&dev->req);+structr592_device*dev=+container_of(work,structr592_device,io_work);-if(error){-if(error==-ENXIO||error==-EAGAIN){-dbg_verbose("IO: done");-}else{-dbg("IO: unknown error from "-"memstick_next_req %d",error);-}-dev->io_started=false;+if(!dev->io_started){+dbg_verbose("IO: started");+dev->io_started=true;+}-if(kthread_should_stop())-set_current_state(TASK_RUNNING);+error=memstick_next_req(dev->host,&dev->req);-schedule();+if(error){+if(error==-ENXIO||error==-EAGAIN){+dbg_verbose("IO: done");}else{-set_current_state(TASK_RUNNING);-r592_execute_tpc(dev);+dbg("IO: unknown error from memstick_next_req %d",+error);}+dev->io_started=false;+}else{+r592_execute_tpc(dev);+queue_kthread_work(dev->io_worker,&dev->io_work);}-return0;}/* Reprogram chip to detect change in card state */
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:28:32
This patch removes a code duplication. It does not modify
the functionality.
Signed-off-by: Petr Mladek <pmladek@suse.com>
CC: Zhang Rui <rui.zhang@intel.com>
CC: Eduardo Valentin <edubezval@gmail.com>
CC: Jacob Pan <redacted>
CC: linux-pm@vger.kernel.org
---
drivers/thermal/intel_powerclamp.c | 45 +++++++++++++++++---------------------
1 file changed, 20 insertions(+), 25 deletions(-)
@@ -505,10 +505,27 @@ static void poll_pkg_cstate(struct work_struct *dummy)schedule_delayed_work(&poll_pkg_cstate_work,HZ);}+staticvoidstart_power_clamp_thread(unsignedlongcpu)+{+structtask_struct**p=per_cpu_ptr(powerclamp_thread,cpu);+structtask_struct*thread;++thread=kthread_create_on_node(clamp_thread,+(void*)cpu,+cpu_to_node(cpu),+"kidle_inject/%ld",cpu);+if(IS_ERR(thread))+return;++/* bind to cpu here */+kthread_bind(thread,cpu);+wake_up_process(thread);+*p=thread;+}+staticintstart_power_clamp(void){unsignedlongcpu;-structtask_struct*thread;/* check if pkg cstate counter is completely 0, abort in this case */if(!has_pkg_state_counter()){
@@ -530,20 +547,7 @@ static int start_power_clamp(void)/* start one thread per online cpu */for_each_online_cpu(cpu){-structtask_struct**p=-per_cpu_ptr(powerclamp_thread,cpu);--thread=kthread_create_on_node(clamp_thread,-(void*)cpu,-cpu_to_node(cpu),-"kidle_inject/%ld",cpu);-/* bind to cpu here */-if(likely(!IS_ERR(thread))){-kthread_bind(thread,cpu);-wake_up_process(thread);-*p=thread;-}-+start_power_clamp_thread(cpu);}put_online_cpus();
@@ -575,7 +579,6 @@ static int powerclamp_cpu_callback(struct notifier_block *nfb,unsignedlongaction,void*hcpu){unsignedlongcpu=(unsignedlong)hcpu;-structtask_struct*thread;structtask_struct**percpu_thread=per_cpu_ptr(powerclamp_thread,cpu);
@@ -584,15 +587,7 @@ static int powerclamp_cpu_callback(struct notifier_block *nfb,switch(action){caseCPU_ONLINE:-thread=kthread_create_on_node(clamp_thread,-(void*)cpu,-cpu_to_node(cpu),-"kidle_inject/%lu",cpu);-if(likely(!IS_ERR(thread))){-kthread_bind(thread,cpu);-wake_up_process(thread);-*percpu_thread=thread;-}+start_power_clamp_thread(cpu);/* prefer BSP as controlling CPU */if(cpu==0){control_cpu=0;
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:28:43
Kthreads are currently implemented as an infinite loop. Each
has its own variant of checks for terminating, freezing,
awakening. In many cases it is unclear to say in which state
it is and sometimes it is done a wrong way.
The plan is to convert kthreads into kthread_worker or workqueues
API. It allows to split the functionality into separate operations.
It helps to make a better structure. Also it defines a clean state
where no locks are taken, IRQs blocked, the kthread might sleep
or even be safely migrated.
The kthread worker API is useful when we want to have a dedicated
single thread for the work. It helps to make sure that it is
available when needed. Also it allows a better control, e.g.
define a scheduling priority.
This patch converts the intel powerclamp kthreads into the kthread
worker because they need to have a good control over the assigned
CPUs.
IMHO, the most natural way is to split one cycle into two works.
First one does some balancing and let the CPU work normal
way for some time. The second work checks what the CPU has done
in the meantime and put it into C-state to reach the required
idle time ratio. The delay between the two works is achieved
by the delayed kthread work.
The two works have to share some data that used to be local
variables of the single kthread function. This is achieved
by the new per-CPU struct kthread_worker_data. It might look
as a complication. On the other hand, the long original kthread
function was not nice either.
The patch tries to avoid extra init and cleanup works. All the
actions might be done outside the thread. They are moved
to the functions that create or destroy the worker. Especially,
I checked that the timers are assigned to the right CPU.
The two works are queuing each other. It makes it a bit tricky to
break it when we want to stop the worker. We use the global and
per-worker "clamping" variables to make sure that the re-queuing
eventually stops. We also cancel the works to make it faster.
Note that the canceling is not reliable because the handling
of the two variables and queuing is not synchronized via a lock.
But it is not a big deal because it is just an optimization.
The job is stopped faster than before in most cases.
Signed-off-by: Petr Mladek <pmladek@suse.com>
CC: Zhang Rui <rui.zhang@intel.com>
CC: Eduardo Valentin <edubezval@gmail.com>
CC: Jacob Pan <redacted>
CC: linux-pm@vger.kernel.org
---
drivers/thermal/intel_powerclamp.c | 287 ++++++++++++++++++++++---------------
1 file changed, 168 insertions(+), 119 deletions(-)
@@ -86,11 +86,27 @@ static unsigned int control_cpu; /* The cpu assigned to collect stat and update*/staticboolclamping;+staticconststructsched_paramsparam={+.sched_priority=MAX_USER_RT_PRIO/2,+};+structpowerclamp_worker_data{+structkthread_worker*worker;+structkthread_workbalancing_work;+structdelayed_kthread_workidle_injection_work;+structtimer_listwakeup_timer;+unsignedintcpu;+unsignedintcount;+unsignedintguard;+unsignedintwindow_size_now;+unsignedinttarget_ratio;+unsignedintduration_jiffies;+boolclamping;+};-staticstructtask_struct*__percpu*powerclamp_thread;+staticstructpowerclamp_worker_data*__percpuworker_data;staticstructthermal_cooling_device*cooling_dev;staticunsignedlong*cpu_clamping_mask;/* bit map for tracking per cpu-*clampingthread+*clampingkthreadworker*/staticunsignedintduration;
@@ -368,100 +384,102 @@ static bool powerclamp_adjust_controls(unsigned int target_ratio,returnset_target_ratio+guard<=current_ratio;}-staticintclamp_thread(void*arg)+staticvoidclamp_balancing_func(structkthread_work*work){-intcpunr=(unsignedlong)arg;-DEFINE_TIMER(wakeup_timer,noop_timer,0,0);-staticconststructsched_paramparam={-.sched_priority=MAX_USER_RT_PRIO/2,-};-unsignedintcount=0;-unsignedinttarget_ratio;+structpowerclamp_worker_data*w_data;+intsleeptime;+unsignedlongtarget_jiffies;+unsignedintcompensation;+intinterval;/* jiffies to sleep for each attempt */-set_bit(cpunr,cpu_clamping_mask);-set_freezable();-init_timer_on_stack(&wakeup_timer);-sched_setscheduler(current,SCHED_FIFO,¶m);--while(true==clamping&&!kthread_should_stop()&&-cpu_online(cpunr)){-intsleeptime;-unsignedlongtarget_jiffies;-unsignedintguard;-unsignedintcompensation=0;-intinterval;/* jiffies to sleep for each attempt */-unsignedintduration_jiffies=msecs_to_jiffies(duration);-unsignedintwindow_size_now;--try_to_freeze();-/*-*makesureuserselectedratiodoesnottakeeffectuntil-*thenextround.adjusttarget_ratioifuserhaschanged-*targetsuchthatwecanconvergequickly.-*/-target_ratio=set_target_ratio;-guard=1+target_ratio/20;-window_size_now=window_size;-count++;+w_data=container_of(work,structpowerclamp_worker_data,+balancing_work);-/*-*systemsmayhavedifferentabilitytoenterpackagelevel-*c-states,thusweneedtocompensatetheinjectedidleratio-*toachievetheactualtargetreportedbytheHW.-*/-compensation=get_compensation(target_ratio);-interval=duration_jiffies*100/(target_ratio+compensation);--/* align idle time */-target_jiffies=roundup(jiffies,interval);-sleeptime=target_jiffies-jiffies;-if(sleeptime<=0)-sleeptime=1;-schedule_timeout_interruptible(sleeptime);-/*-*onlyelectedcontrollingcpucancollectstatsandupdate-*controlparameters.-*/-if(cpunr==control_cpu&&!(count%window_size_now)){-should_skip=-powerclamp_adjust_controls(target_ratio,-guard,window_size_now);-smp_mb();-}+/*+*makesureuserselectedratiodoesnottakeeffectuntil+*thenextround.adjusttarget_ratioifuserhaschanged+*targetsuchthatwecanconvergequickly.+*/+w_data->target_ratio=READ_ONCE(set_target_ratio);+w_data->guard=1+w_data->target_ratio/20;+w_data->window_size_now=window_size;+w_data->duration_jiffies=msecs_to_jiffies(duration);+w_data->count++;++/*+*systemsmayhavedifferentabilitytoenterpackagelevel+*c-states,thusweneedtocompensatetheinjectedidleratio+*toachievetheactualtargetreportedbytheHW.+*/+compensation=get_compensation(w_data->target_ratio);+interval=w_data->duration_jiffies*100/+(w_data->target_ratio+compensation);++/* align idle time */+target_jiffies=roundup(jiffies,interval);+sleeptime=target_jiffies-jiffies;+if(sleeptime<=0)+sleeptime=1;++if(clamping&&w_data->clamping&&cpu_online(w_data->cpu))+queue_delayed_kthread_work(w_data->worker,+&w_data->idle_injection_work,+sleeptime);+}++staticvoidclamp_idle_injection_func(structkthread_work*work)+{+structpowerclamp_worker_data*w_data;+unsignedlongtarget_jiffies;++w_data=container_of(work,structpowerclamp_worker_data,+idle_injection_work.work);++/*+*onlyelectedcontrollingcpucancollectstatsandupdate+*controlparameters.+*/+if(w_data->cpu==control_cpu&&+!(w_data->count%w_data->window_size_now)){+should_skip=+powerclamp_adjust_controls(w_data->target_ratio,+w_data->guard,+w_data->window_size_now);+smp_mb();+}-if(should_skip)-continue;+if(should_skip)+gotobalance;++target_jiffies=jiffies+w_data->duration_jiffies;+mod_timer(&w_data->wakeup_timer,target_jiffies);+if(unlikely(local_softirq_pending()))+gotobalance;+/*+*stoptickschedduringidletime,interruptsarestill+*allowed.thusjiffiesareupdatedproperly.+*/+preempt_disable();+/* mwait until target jiffies is reached */+while(time_before(jiffies,target_jiffies)){+unsignedlongecx=1;+unsignedlongeax=target_mwait;-target_jiffies=jiffies+duration_jiffies;-mod_timer(&wakeup_timer,target_jiffies);-if(unlikely(local_softirq_pending()))-continue;/*-*stoptickschedduringidletime,interruptsarestill-*allowed.thusjiffiesareupdatedproperly.+*REVISIT:maycallenter_idle()tonotifydriverswho+*cansavepowerduringcpuidle.sameforexit_idle()*/-preempt_disable();-/* mwait until target jiffies is reached */-while(time_before(jiffies,target_jiffies)){-unsignedlongecx=1;-unsignedlongeax=target_mwait;--/*-*REVISIT:maycallenter_idle()tonotifydriverswho-*cansavepowerduringcpuidle.sameforexit_idle()-*/-local_touch_nmi();-stop_critical_timings();-mwait_idle_with_hints(eax,ecx);-start_critical_timings();-atomic_inc(&idle_wakeup_counter);-}-preempt_enable();+local_touch_nmi();+stop_critical_timings();+mwait_idle_with_hints(eax,ecx);+start_critical_timings();+atomic_inc(&idle_wakeup_counter);}-del_timer_sync(&wakeup_timer);-clear_bit(cpunr,cpu_clamping_mask);+preempt_enable();-return0;+balance:+if(clamping&&w_data->clamping&&cpu_online(w_data->cpu))+queue_kthread_work(w_data->worker,&w_data->balancing_work);}/*
@@ -505,22 +523,58 @@ static void poll_pkg_cstate(struct work_struct *dummy)schedule_delayed_work(&poll_pkg_cstate_work,HZ);}-staticvoidstart_power_clamp_thread(unsignedlongcpu)+staticvoidstart_power_clamp_worker(unsignedlongcpu){-structtask_struct**p=per_cpu_ptr(powerclamp_thread,cpu);-structtask_struct*thread;--thread=kthread_create_on_node(clamp_thread,-(void*)cpu,-cpu_to_node(cpu),-"kidle_inject/%ld",cpu);-if(IS_ERR(thread))+structpowerclamp_worker_data*w_data=per_cpu_ptr(worker_data,cpu);+structkthread_worker*worker;++worker=create_kthread_worker_on_cpu(KTW_FREEZABLE,cpu,+"kidle_inject/%ld");+if(IS_ERR(worker))return;-/* bind to cpu here */-kthread_bind(thread,cpu);-wake_up_process(thread);-*p=thread;+w_data->worker=worker;+w_data->count=0;+w_data->cpu=cpu;+w_data->clamping=true;+set_bit(cpu,cpu_clamping_mask);+setup_timer(&w_data->wakeup_timer,noop_timer,0);+sched_setscheduler(worker->task,SCHED_FIFO,&sparam);+init_kthread_work(&w_data->balancing_work,clamp_balancing_func);+init_delayed_kthread_work(&w_data->idle_injection_work,+clamp_idle_injection_func);+queue_kthread_work(w_data->worker,&w_data->balancing_work);+}++staticvoidstop_power_clamp_worker(unsignedlongcpu)+{+structpowerclamp_worker_data*w_data=per_cpu_ptr(worker_data,cpu);++if(!w_data->worker)+return;++w_data->clamping=false;+/*+*Makesurethatallworksthatgetqueuedafterthispointsee+*theclampingdisabled.Thecounterpartisnotneededbecause+*thereisanimplicitmemorybarrierwhenthequeuedwork+*isproceed.+*/+smp_wmb();+cancel_kthread_work_sync(&w_data->balancing_work);+cancel_delayed_kthread_work_sync(&w_data->idle_injection_work);+/*+*Thebalancingworkstillmightbequeuedherebecause+*thehandlingofthe"clapming"variable,cancel,andqueue+*operationsarenotsynchronizedviaalock.Butitisnot+*abigdeal.Thebalancingworkisfastanddestroykthread+*willwaitforit.+*/+del_timer_sync(&w_data->wakeup_timer);+clear_bit(w_data->cpu,cpu_clamping_mask);+destroy_kthread_worker(w_data->worker);++w_data->worker=NULL;}staticintstart_power_clamp(void)
@@ -545,9 +599,9 @@ static int start_power_clamp(void)clamping=true;schedule_delayed_work(&poll_pkg_cstate_work,0);-/* start one thread per online cpu */+/* start one kthread worker per online cpu */for_each_online_cpu(cpu){-start_power_clamp_thread(cpu);+start_power_clamp_worker(cpu);}put_online_cpus();
@@ -557,20 +611,17 @@ static int start_power_clamp(void)staticvoidend_power_clamp(void){inti;-structtask_struct*thread;-clamping=false;/*-*makeclampingvisibletoothercpusandgivepercpuclampingthreads-*sometimetoexit,orgetskilledlater.+*Blockrequeuinginallthekthreadworkers.Theywilldrainand+*stopfaster.*/-smp_mb();-msleep(20);+clamping=false;if(bitmap_weight(cpu_clamping_mask,num_possible_cpus())){for_each_set_bit(i,cpu_clamping_mask,num_possible_cpus()){-pr_debug("clamping thread for cpu %d alive, kill\n",i);-thread=*per_cpu_ptr(powerclamp_thread,i);-kthread_stop(thread);+pr_debug("clamping worker for cpu %d alive, destroy\n",+i);+stop_power_clamp_worker(i);}}}
@@ -579,15 +630,13 @@ static int powerclamp_cpu_callback(struct notifier_block *nfb,unsignedlongaction,void*hcpu){unsignedlongcpu=(unsignedlong)hcpu;-structtask_struct**percpu_thread=-per_cpu_ptr(powerclamp_thread,cpu);if(false==clamping)gotoexit_ok;switch(action){caseCPU_ONLINE:-start_power_clamp_thread(cpu);+start_power_clamp_worker(cpu);/* prefer BSP as controlling CPU */if(cpu==0){control_cpu=0;
@@ -598,7 +647,7 @@ static int powerclamp_cpu_callback(struct notifier_block *nfb,if(test_bit(cpu,cpu_clamping_mask)){pr_err("cpu %lu dead but powerclamping thread is not\n",cpu);-kthread_stop(*percpu_thread);+stop_power_clamp_worker(cpu);}if(cpu==control_cpu){control_cpu=smp_processor_id();
@@ -785,8 +834,8 @@ static int __init powerclamp_init(void)window_size=2;register_hotcpu_notifier(&powerclamp_cpu_notifier);-powerclamp_thread=alloc_percpu(structtask_struct*);-if(!powerclamp_thread){+worker_data=alloc_percpu(structpowerclamp_worker_data);+if(!worker_data){retval=-ENOMEM;gotoexit_unregister;}
@@ -806,7 +855,7 @@ static int __init powerclamp_init(void)return0;exit_free_thread:-free_percpu(powerclamp_thread);+free_percpu(worker_data);exit_unregister:unregister_hotcpu_notifier(&powerclamp_cpu_notifier);exit_free:
From: Jacob Pan <hidden> Date: 2016-01-07 19:56:46
On Wed, 18 Nov 2015 14:25:27 +0100
Petr Mladek [off-list ref] wrote:
From: Petr Mladek <pmladek@suse.com>
To: Andrew Morton <akpm@linux-foundation.org>, Oleg Nesterov
[off-list ref], Tejun Heo [off-list ref], Ingo Molnar
[off-list ref], Peter Zijlstra [off-list ref] Cc: Steven
Rostedt [off-list ref], "Paul E. McKenney"
[off-list ref], Josh Triplett [off-list ref],
Thomas Gleixner [off-list ref], Linus Torvalds
[off-list ref], Jiri Kosina [off-list ref],
Borislav Petkov [off-list ref], Michal Hocko [off-list ref],
linux-mm@kvack.org, Vlastimil Babka [off-list ref],
linux-api@vger.kernel.org, linux-kernel@vger.kernel.org, Petr Mladek
[off-list ref], Zhang Rui [off-list ref], Eduardo Valentin
[off-list ref], Jacob Pan [off-list ref],
linux-pm@vger.kernel.org Subject: [PATCH v3 22/22]
thermal/intel_powerclamp: Convert the kthread to kthread worker API
Date: Wed, 18 Nov 2015 14:25:27 +0100 X-Mailer: git-send-email 1.8.5.6
Kthreads are currently implemented as an infinite loop. Each
has its own variant of checks for terminating, freezing,
awakening. In many cases it is unclear to say in which state
it is and sometimes it is done a wrong way.
The plan is to convert kthreads into kthread_worker or workqueues
API. It allows to split the functionality into separate operations.
It helps to make a better structure. Also it defines a clean state
where no locks are taken, IRQs blocked, the kthread might sleep
or even be safely migrated.
The kthread worker API is useful when we want to have a dedicated
single thread for the work. It helps to make sure that it is
available when needed. Also it allows a better control, e.g.
define a scheduling priority.
This patch converts the intel powerclamp kthreads into the kthread
worker because they need to have a good control over the assigned
CPUs.
I have tested this patchset and found no obvious issues in terms of
functionality, power and performance. Tested CPU online/offline,
suspend resume, freeze etc.
Power numbers are comparable too. e.g. on IVB 8C system. Inject idle
from 5 to 50% and read package power while running CPU bound workload.
Before:
IdlePct Perf RAPL WallPower
5 256.28 16.50 0.0
10 248.86 15.64 0.0
15 209.01 14.57 0.0
20 176.17 13.88 0.0
25 161.25 13.37 0.0
30 165.62 13.38 0.0
35 150.94 12.89 0.0
40 137.45 12.47 0.0
45 123.80 11.83 0.0
50 137.59 11.80 0.0
After:
(deb_chroot)root@ubuntu-jp-nfs:~/powercap-power# ./test.py -c 5
IdlePct Perf RAPL WallPower
5 266.30 16.34 0.0
10 226.32 15.27 0.0
15 195.52 14.29 0.0
20 200.96 13.98 0.0
25 174.77 13.08 0.0
30 162.05 13.04 0.0
35 166.70 12.90 0.0
40 134.78 12.12 0.0
45 128.08 11.70 0.0
50 117.74 11.74 0.0
IMHO, the most natural way is to split one cycle into two works.
First one does some balancing and let the CPU work normal
way for some time. The second work checks what the CPU has done
in the meantime and put it into C-state to reach the required
idle time ratio. The delay between the two works is achieved
by the delayed kthread work.
The two works have to share some data that used to be local
variables of the single kthread function. This is achieved
by the new per-CPU struct kthread_worker_data. It might look
as a complication. On the other hand, the long original kthread
function was not nice either.
The patch tries to avoid extra init and cleanup works. All the
actions might be done outside the thread. They are moved
to the functions that create or destroy the worker. Especially,
I checked that the timers are assigned to the right CPU.
The two works are queuing each other. It makes it a bit tricky to
break it when we want to stop the worker. We use the global and
per-worker "clamping" variables to make sure that the re-queuing
eventually stops. We also cancel the works to make it faster.
Note that the canceling is not reliable because the handling
of the two variables and queuing is not synchronized via a lock.
But it is not a big deal because it is just an optimization.
The job is stopped faster than before in most cases.
I am not convinced this added complexity is necessary, here are my
concerns by breaking down into two work items.
- overhead of queuing, per cpu data as you already mentioned.
- since we need to have very tight timing control, two items may limit
our turnaround time. Wouldn't it take one extra tick for the scheduler
to run the balance work then add delay? as opposed to just
schedule_timeout()?
- vulnerable to future changes of queuing work
Jacob
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2016-01-08 16:49:42
On Thu 2016-01-07 11:55:31, Jacob Pan wrote:
On Wed, 18 Nov 2015 14:25:27 +0100
Petr Mladek [off-list ref] wrote:
I have tested this patchset and found no obvious issues in terms of
functionality, power and performance. Tested CPU online/offline,
suspend resume, freeze etc.
Power numbers are comparable too. e.g. on IVB 8C system. Inject idle
from 5 to 50% and read package power while running CPU bound workload.
Great news. Thanks a lot for testing.
quoted
IMHO, the most natural way is to split one cycle into two works.
First one does some balancing and let the CPU work normal
way for some time. The second work checks what the CPU has done
in the meantime and put it into C-state to reach the required
idle time ratio. The delay between the two works is achieved
by the delayed kthread work.
The two works have to share some data that used to be local
variables of the single kthread function. This is achieved
by the new per-CPU struct kthread_worker_data. It might look
as a complication. On the other hand, the long original kthread
function was not nice either.
The two works are queuing each other. It makes it a bit tricky to
break it when we want to stop the worker. We use the global and
per-worker "clamping" variables to make sure that the re-queuing
eventually stops. We also cancel the works to make it faster.
Note that the canceling is not reliable because the handling
of the two variables and queuing is not synchronized via a lock.
But it is not a big deal because it is just an optimization.
The job is stopped faster than before in most cases.
I am not convinced this added complexity is necessary, here are my
concerns by breaking down into two work items.
I am not super happy with the split either. But the current state has
its drawback as well.
- overhead of queuing,
Good question. Here is a rather typical snippet from function_graph
tracer of the clamp_balancing func:
31) | clamp_balancing_func() {
31) | queue_delayed_kthread_work() {
31) | __queue_delayed_kthread_work() {
31) | add_timer() {
31) 4.906 us | }
31) 5.959 us | }
31) 9.702 us | }
31) + 10.878 us | }
On one hand it spends most of the time (10 of 11 secs) in queueing
the work. On the other hand, half of this time is spent on adding
the timer. schedule_timeout() would need to setup the timer as well.
Here is a snippet from clamp_idle_injection_func()
31) | clamp_idle_injection_func() {
31) | smp_apic_timer_interrupt() {
31) + 67.523 us | }
31) | smp_apic_timer_interrupt() {
31) + 59.946 us | }
...
31) | queue_kthread_work() {
31) 4.314 us | }
31) * 24075.11 us | }
Of course, it spends most of the time in the idle state. Anyway, the
time spent on queuing is negligible in compare with the time spent
in the several timer interrupt handlers.
per cpu data as you already mentioned.
On the other hand, the variables need to be stored somewhere.
Also it helps to split the rather long function into more pieces.
- since we need to have very tight timing control, two items may limit
our turnaround time. Wouldn't it take one extra tick for the scheduler
to run the balance work then add delay? as opposed to just
schedule_timeout()?
Kthread worker processes works until the queue is empty. It calls
try_to_freeze() and __preempt_schedule() between the works.
Where __preempt_schedule() is hidden in the spin_unlock_irq().
try_to_freeze() is in the original code as well.
Is the __preempt_schedule() a problem? It allows to switch the process
when needed. I thought that it was safe because try_to_freeze() might
have slept as well.
- vulnerable to future changes of queuing work
The question is if it is safe to sleep, freeze, or even migrate
the system between the works. It looks like because of the
try_to_freeze() and schedule_interrupt() calls in the original code.
BTW: I wonder if the original code correctly handle freezing after
the schedule_timeout(). It does not call try_to_freeze()
there and the forced idle states might block freezing.
I think that the small overhead of kthread works is worth
solving such bugs. It makes it easier to maintain these
sleeping states.
Thanks a lot for feedback,
Petr
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Jacob Pan <hidden> Date: 2016-01-12 02:20:23
On Fri, 8 Jan 2016 17:49:31 +0100
Petr Mladek [off-list ref] wrote:
Is the __preempt_schedule() a problem? It allows to switch the process
when needed. I thought that it was safe because try_to_freeze() might
have slept as well.
not a problem. i originally thought queue_kthread_work() may add
delay but it doesn't since there is no other work on this kthread.
quoted
- vulnerable to future changes of queuing work
The question is if it is safe to sleep, freeze, or even migrate
the system between the works. It looks like because of the
try_to_freeze() and schedule_interrupt() calls in the original code.
BTW: I wonder if the original code correctly handle freezing after
the schedule_timeout(). It does not call try_to_freeze()
there and the forced idle states might block freezing.
I think that the small overhead of kthread works is worth
solving such bugs. It makes it easier to maintain these
sleeping states.
it is in a while loop, so try_to_freeze() gets called. Am I missing
something?
Thanks,
Jacob
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2016-01-12 10:11:38
On Mon 2016-01-11 18:17:18, Jacob Pan wrote:
On Fri, 8 Jan 2016 17:49:31 +0100
Petr Mladek [off-list ref] wrote:
quoted
Is the __preempt_schedule() a problem? It allows to switch the process
when needed. I thought that it was safe because try_to_freeze() might
have slept as well.
not a problem. i originally thought queue_kthread_work() may add
delay but it doesn't since there is no other work on this kthread.
Great.
quoted
quoted
- vulnerable to future changes of queuing work
The question is if it is safe to sleep, freeze, or even migrate
the system between the works. It looks like because of the
try_to_freeze() and schedule_interrupt() calls in the original code.
BTW: I wonder if the original code correctly handle freezing after
the schedule_timeout(). It does not call try_to_freeze()
there and the forced idle states might block freezing.
I think that the small overhead of kthread works is worth
solving such bugs. It makes it easier to maintain these
sleeping states.
it is in a while loop, so try_to_freeze() gets called. Am I missing
something?
But it might take some time until try_to_freeze() is called.
If I get it correctly. try_to_freeze_tasks() wakes freezable
tasks to get them into the fridge. If clamp_thread() is waken
from that schedule_timeout_interruptible(), it still might inject
the idle state before calling try_to_freeze(). It means that freezer
needs to wait "quite" some time until the kthread ends up in the
fridge.
Hmm, even my conversion does not solve this entirely. We might
need to call freezing(current) in the
while (time_before(jiffies, target_jiffies)) {
cycle. And break injecting the idle state when freezing is requested.
Or do I miss something, please?
Best Regards,
Petr
Best Regards,
Petr
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Jacob Pan <hidden> Date: 2016-01-12 16:21:37
On Tue, 12 Jan 2016 11:11:29 +0100
Petr Mladek [off-list ref] wrote:
quoted
quoted
BTW: I wonder if the original code correctly handle freezing after
the schedule_timeout(). It does not call try_to_freeze()
there and the forced idle states might block freezing.
I think that the small overhead of kthread works is worth
solving such bugs. It makes it easier to maintain these
sleeping states.
it is in a while loop, so try_to_freeze() gets called. Am I missing
something?
But it might take some time until try_to_freeze() is called.
If I get it correctly. try_to_freeze_tasks() wakes freezable
tasks to get them into the fridge. If clamp_thread() is waken
from that schedule_timeout_interruptible(), it still might inject
the idle state before calling try_to_freeze(). It means that freezer
needs to wait "quite" some time until the kthread ends up in the
fridge.
Hmm, even my conversion does not solve this entirely. We might
need to call freezing(current) in the
while (time_before(jiffies, target_jiffies)) {
cycle. And break injecting the idle state when freezing is requested.
The injection time for each period is very short, default 6ms. While on
the other side the default freeze timeout is 20 sec. So I think task
freeze can wait :)
i.e.
unsigned int __read_mostly freeze_timeout_msecs = 20 * MSEC_PER_SEC;
From: Petr Mladek <pmladek@suse.com> Date: 2016-01-13 10:18:40
On Tue 2016-01-12 08:20:21, Jacob Pan wrote:
On Tue, 12 Jan 2016 11:11:29 +0100
Petr Mladek [off-list ref] wrote:
quoted
quoted
quoted
BTW: I wonder if the original code correctly handle freezing after
the schedule_timeout(). It does not call try_to_freeze()
there and the forced idle states might block freezing.
I think that the small overhead of kthread works is worth
solving such bugs. It makes it easier to maintain these
sleeping states.
it is in a while loop, so try_to_freeze() gets called. Am I missing
something?
But it might take some time until try_to_freeze() is called.
If I get it correctly. try_to_freeze_tasks() wakes freezable
tasks to get them into the fridge. If clamp_thread() is waken
from that schedule_timeout_interruptible(), it still might inject
the idle state before calling try_to_freeze(). It means that freezer
needs to wait "quite" some time until the kthread ends up in the
fridge.
Hmm, even my conversion does not solve this entirely. We might
need to call freezing(current) in the
while (time_before(jiffies, target_jiffies)) {
cycle. And break injecting the idle state when freezing is requested.
The injection time for each period is very short, default 6ms. While on
the other side the default freeze timeout is 20 sec. So I think task
freeze can wait :)
i.e.
unsigned int __read_mostly freeze_timeout_msecs = 20 * MSEC_PER_SEC;
You are right. And it does not make sense to add an extra
freezer-specific code if not really necessary.
Otherwise, I will keep the conversion into the kthread worker as is
for now. Please, let me know if you are strongly against the split
into the two works.
Best Regards,
Petr
From: Jacob Pan <hidden> Date: 2016-01-13 17:54:18
On Wed, 13 Jan 2016 11:18:31 +0100
Petr Mladek [off-list ref] wrote:
quoted
unsigned int __read_mostly freeze_timeout_msecs = 20 *
MSEC_PER_SEC;
You are right. And it does not make sense to add an extra
freezer-specific code if not really necessary.
Otherwise, I will keep the conversion into the kthread worker as is
for now. Please, let me know if you are strongly against the split
into the two works.
I am fine with the split now.
Another question, are you planning to convert acpi_pad.c as well? It
uses kthread similar way.
Jacob
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2016-01-14 15:38:13
On Wed 2016-01-13 09:53:53, Jacob Pan wrote:
On Wed, 13 Jan 2016 11:18:31 +0100
Petr Mladek [off-list ref] wrote:
quoted
Otherwise, I will keep the conversion into the kthread worker as is
for now. Please, let me know if you are strongly against the split
into the two works.
I am fine with the split now.
Great.
Another question, are you planning to convert acpi_pad.c as well? It
uses kthread similar way.
Yup. I would like to convert as many kthreads as possible either to
the kthread worker or workqueue APIs in the long term.
Best Regards,
Petr
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:29:33
Kthreads are currently implemented as an infinite loop. Each
has its own variant of checks for terminating, freezing,
awakening. In many cases it is unclear to say in which state
it is and sometimes it is done a wrong way.
The plan is to convert kthreads into kthread_worker or workqueues
API. It allows to split the functionality into separate operations.
It helps to make a better structure. Also it defines a clean state
where no locks are taken, IRQs blocked, the kthread might sleep
or even be safely migrated.
The kthread worker API is useful when we want to have a dedicated
single thread for the work. It helps to make sure that it is
available when needed. Also it allows a better control, e.g.
define a scheduling priority.
This patch converts the kmemleak kthread into the kthread worker
API because it modifies the scheduling priority.
The result is a simple self-queuing work that just calls kmemleak_scan().
The info messages and set_user_nice() are moved to the functions that
start and stop the worker. These are also renamed to mention worker
instead of thread.
We do not longer need to handle a spurious wakeup and count the remaining
timeout. It is handled by the worker. The delayed work is queued after
the full timeout passes.
Finally, the initial delay is done only when the kthread is started
during the boot. For this we added a parameter to the start function.
Signed-off-by: Petr Mladek <pmladek@suse.com>
CC: Catalin Marinas <catalin.marinas@arm.com>
---
mm/kmemleak.c | 86 +++++++++++++++++++++++++++++------------------------------
1 file changed, 42 insertions(+), 44 deletions(-)
@@ -217,7 +217,9 @@ static int kmemleak_error;staticunsignedlongmin_addr=ULONG_MAX;staticunsignedlongmax_addr;-staticstructtask_struct*scan_thread;+staticstructkthread_worker*kmemleak_scan_worker;+staticvoidkmemleak_scan_func(structkthread_work*dummy);+staticDEFINE_DELAYED_KTHREAD_WORK(kmemleak_scan_work,kmemleak_scan_func);/* used to avoid reporting of recently allocated objects */staticunsignedlongjiffies_min_age;staticunsignedlongjiffies_last_scan;
@@ -1471,54 +1473,46 @@ static void kmemleak_scan(void)}/*-*Threadfunctionperformingautomaticmemoryscanning.Unreferencedobjects-*attheendofamemoryscanarereportedbutonlythefirsttime.+*Kthreadworkerfunctionperformingautomaticmemoryscanning.+*Unreferencedobjectsattheendofamemoryscanarereported+*butonlythefirsttime.*/-staticintkmemleak_scan_thread(void*arg)+staticvoidkmemleak_scan_func(structkthread_work*dummy){-staticintfirst_run=1;--pr_info("Automatic memory scanning thread started\n");-set_user_nice(current,10);--/*-*Waitbeforethefirstscantoallowthesystemtofullyinitialize.-*/-if(first_run){-first_run=0;-ssleep(SECS_FIRST_SCAN);-}--while(!kthread_should_stop()){-signedlongtimeout=jiffies_scan_wait;--mutex_lock(&scan_mutex);-kmemleak_scan();-mutex_unlock(&scan_mutex);--/* wait before the next scan */-while(timeout&&!kthread_should_stop())-timeout=schedule_timeout_interruptible(timeout);-}--pr_info("Automatic memory scanning thread ended\n");+mutex_lock(&scan_mutex);+kmemleak_scan();+mutex_unlock(&scan_mutex);-return0;+queue_delayed_kthread_work(kmemleak_scan_worker,&kmemleak_scan_work,+jiffies_scan_wait);}/**Starttheautomaticmemoryscanningthread.Thisfunctionmustbecalled*withthescan_mutexheld.*/-staticvoidstart_scan_thread(void)+staticvoidstart_scan_thread(boolboot){-if(scan_thread)+unsignedlongtimeout=0;++if(kmemleak_scan_worker)return;-scan_thread=kthread_run(kmemleak_scan_thread,NULL,"kmemleak");-if(IS_ERR(scan_thread)){-pr_warning("Failed to create the scan thread\n");-scan_thread=NULL;+kmemleak_scan_worker=create_kthread_worker(0,"kmemleak");+if(IS_ERR(kmemleak_scan_worker)){+pr_warn("Failed to create the memory scan worker\n");+kmemleak_scan_worker=NULL;}+pr_info("Automatic memory scanning thread started\n");+set_user_nice(kmemleak_scan_worker->task,10);++/*+*Waitbeforethefirstscantoallowthesystemtofullyinitialize.+*/+if(boot)+timeout=msecs_to_jiffies(SECS_FIRST_SCAN*MSEC_PER_SEC);++queue_delayed_kthread_work(kmemleak_scan_worker,&kmemleak_scan_work,+timeout);}/*
@@ -1963,7 +1961,7 @@ static int __init kmemleak_late_init(void)if(!dentry)pr_warning("Failed to create the debugfs kmemleak file\n");mutex_lock(&scan_mutex);-start_scan_thread();+start_scan_thread(true);mutex_unlock(&scan_mutex);pr_info("Kernel memory leak detector initialized\n");
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:30:23
Kthreads are currently implemented as an infinite loop. Each
has its own variant of checks for terminating, freezing,
awakening. In many cases it is unclear to say in which state
it is and sometimes it is done a wrong way.
The plan is to convert kthreads into kthread_worker or workqueues
API. It allows to split the functionality into separate operations.
It helps to make a better structure. Also it defines a clean state
where no locks are taken, IRQs blocked, the kthread might sleep
or even be safely migrated.
The kthread worker API is useful when we want to have a dedicated
single thread for the work. It helps to make sure that it is
available when needed. Also it allows a better control, e.g.
define a scheduling priority.
This patch converts khugepaged() in kthread worker API
because it modifies the scheduling.
It keeps the functionality except that we do not wakeup the worker
when it is already created and someone calls start() once again.
set_freezable() is not needed because the kthread worker is
created as freezable.
set_user_nice() is called from start_stop_khugepaged(). It need
not be done from within the kthread.
The scan work must be queued only when the worker is available.
We have to use "khugepaged_mm_lock" to avoid a race between the check
and queuing. I admit that this was a bit easier before because wake_up()
was a nope when the kthread did not exist.
Also the scan work is queued only when the list of scanned pages is
not empty. It adds one check but it is cleaner.
They delay between scans is done using a delayed work.
Note that @khugepaged_wait waitqueue had two purposes. It was used
to wait between scans and when an allocation failed. It is still used
for the second purpose. Therefore it was renamed to better describe
the current use.
Also note that we could not longer check for kthread_should_stop()
in the works. The kthread used by the worker has to stay alive
until all queued works are finished. Instead, we use the existing
check khugepaged_enabled() that returns false when we are going down.
Signed-off-by: Petr Mladek <pmladek@suse.com>
---
mm/huge_memory.c | 134 ++++++++++++++++++++++++++++++-------------------------
1 file changed, 72 insertions(+), 62 deletions(-)
@@ -57,10 +57,17 @@ static unsigned int khugepaged_full_scans;staticunsignedintkhugepaged_scan_sleep_millisecs__read_mostly=10000;/* during fragmentation poll the hugepage allocator once every minute */staticunsignedintkhugepaged_alloc_sleep_millisecs__read_mostly=60000;-staticstructtask_struct*khugepaged_thread__read_mostly;++staticvoidkhugepaged_do_scan_func(structkthread_work*dummy);+staticvoidkhugepaged_cleanup_func(structkthread_work*dummy);+staticstructkthread_worker*khugepaged_worker;+staticDEFINE_DELAYED_KTHREAD_WORK(khugepaged_do_scan_work,+khugepaged_do_scan_func);+staticDEFINE_KTHREAD_WORK(khugepaged_cleanup_work,khugepaged_cleanup_func);+staticDEFINE_MUTEX(khugepaged_mutex);staticDEFINE_SPINLOCK(khugepaged_mm_lock);-staticDECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);+staticDECLARE_WAIT_QUEUE_HEAD(khugepaged_alloc_wait);/**defaultcollapsehugepagesifthereisatleastoneptemappedlike*itwouldhavehappenedifthevmawaslargeenoughduringpage
@@ -144,29 +150,50 @@ static void set_recommended_min_free_kbytes(void)setup_per_zone_wmarks();}+staticintkhugepaged_has_work(void)+{+return!list_empty(&khugepaged_scan.mm_head);+}+staticintstart_stop_khugepaged(void){+structkthread_worker*worker;interr=0;+if(khugepaged_enabled()){-if(!khugepaged_thread)-khugepaged_thread=kthread_run(khugepaged,NULL,-"khugepaged");-if(IS_ERR(khugepaged_thread)){-pr_err("khugepaged: kthread_run(khugepaged) failed\n");-err=PTR_ERR(khugepaged_thread);-khugepaged_thread=NULL;-gotofail;+if(khugepaged_worker)+gotoout;++worker=create_kthread_worker(KTW_FREEZABLE,"khugepaged");+if(IS_ERR(worker)){+pr_err("khugepaged: failed to create kthread worker\n");+gotoout;}-if(!list_empty(&khugepaged_scan.mm_head))-wake_up_interruptible(&khugepaged_wait);+set_user_nice(worker->task,MAX_NICE);++/* Make the worker public and check for work synchronously. */+spin_lock(&khugepaged_mm_lock);+khugepaged_worker=worker;+if(khugepaged_has_work())+queue_delayed_kthread_work(worker,+&khugepaged_do_scan_work,+0);+spin_unlock(&khugepaged_mm_lock);set_recommended_min_free_kbytes();-}elseif(khugepaged_thread){-kthread_stop(khugepaged_thread);-khugepaged_thread=NULL;+}elseif(khugepaged_worker){+/* First, stop others from using the worker. */+spin_lock(&khugepaged_mm_lock);+worker=khugepaged_worker;+khugepaged_worker=NULL;+spin_unlock(&khugepaged_mm_lock);++cancel_delayed_kthread_work_sync(&khugepaged_do_scan_work);+queue_kthread_work(worker,&khugepaged_cleanup_work);+destroy_kthread_worker(worker);}-fail:+out:returnerr;}
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:30:26
Remove code duplication and use the new try_lock_kthread_work()
function in flush_kthread_work() as well.
Signed-off-by: Petr Mladek <pmladek@suse.com>
---
kernel/kthread.c | 12 ++++--------
1 file changed, 4 insertions(+), 8 deletions(-)
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:31:49
We are going to use kthread_worker more widely and delayed works
will be pretty useful.
The implementation is inspired by workqueues. It uses a timer to
queue the work after the requested delay. If the delay is zero,
the work is queued immediately.
In compare with workqueues, each work is associated with a single
worker (kthread). Therefore the implementation could be much easier.
In particular, we use the worker->lock to synchronized all the
operations with the work. And we do not use any flags variable.
On the other hand, we add a pointer[*] to the timer into the struct
kthread_work. The kthread worker need to know if the work is used
and if it could clear work->worker. For this, it needs to know
whether the timer is active or not.
Finally, the timer callback knows only about the struct work.
It is better be paranoid and try to get the worker->lock carefully.
The try_lock_thread_work() function will be later useful also when
canceling the work.
[*] I considered also adding the entire struct timer_list into
struct kthread_work. But it would increase the size from
40 to 120 bytes on x86_64 with an often unused stuff.
Another alternative was to add a flags variable. But this
would add an extra code to synchronize it with the state
of the timer.
Signed-off-by: Petr Mladek <pmladek@suse.com>
---
include/linux/kthread.h | 34 +++++++++++++
kernel/kthread.c | 130 +++++++++++++++++++++++++++++++++++++++++++++++-
2 files changed, 162 insertions(+), 2 deletions(-)
@@ -771,6 +782,121 @@ bool queue_kthread_work(struct kthread_worker *worker,}EXPORT_SYMBOL_GPL(queue_kthread_work);+staticbooltry_lock_kthread_work(structkthread_work*work)+{+structkthread_worker*worker;+intret=false;++try_again:+worker=work->worker;++if(!worker)+gotoout;++spin_lock(&worker->lock);+if(worker!=work->worker){+spin_unlock(&worker->lock);+gototry_again;+}+ret=true;++out:+returnret;+}++staticinlinevoidunlock_kthread_work(structkthread_work*work)+{+spin_unlock(&work->worker->lock);+}++/**+*delayed_kthread_work_timer_fn-callbackthatqueuestheassociateddelayed+*kthreadworkwhenthetimerexpires.+*@__data:pointertothedataassociatedwiththetimer+*+*Theformatofthefunctionisdefinedbystructtimer_list.+*Itshouldhavebeencalledfromirqsafetimerwithirqalreadyoff.+*/+voiddelayed_kthread_work_timer_fn(unsignedlong__data)+{+structdelayed_kthread_work*dwork=+(structdelayed_kthread_work*)__data;+structkthread_work*work=&dwork->work;++if(WARN_ON(!try_lock_kthread_work(work)))+return;++__queue_kthread_work(work->worker,work);+unlock_kthread_work(work);+}+EXPORT_SYMBOL(delayed_kthread_work_timer_fn);++void__queue_delayed_kthread_work(structkthread_worker*worker,+structdelayed_kthread_work*dwork,+unsignedlongdelay)+{+structtimer_list*timer=&dwork->timer;+structkthread_work*work=&dwork->work;++WARN_ON_ONCE(timer->function!=delayed_kthread_work_timer_fn||+timer->data!=(unsignedlong)dwork);+WARN_ON_ONCE(timer_pending(timer));++/*+*If@delayis0,queue@dwork->workimmediately.Thisisfor+*bothoptimizationandcorrectness.Theearliest@timercan+*expireisontheclosestnexttickanddelayed_workusersdepend+*onthatthere'snosuchdelaywhen@delayis0.+*/+if(!delay){+__queue_kthread_work(worker,work);+return;+}++/* Be paranoid and try to detect possible races already now. */+insert_kthread_work_sanity_check(worker,work);++work->worker=worker;+timer_stats_timer_set_start_info(&dwork->timer);+timer->expires=jiffies+delay;+add_timer(timer);+}++/**+*queue_delayed_kthread_work-queuetheassociatedkthreadwork+*afteradelay.+*@worker:targetkthread_worker+*@work:kthread_worktoqueue+*delay:numberofjiffiestowaitbeforequeuing+*+*Iftheworkhasnotbeenpendingitstartsatimerthatwillqueue+*theworkafterthegiven@delay.If@delayiszero,itqueuesthe+*workimmediately.+*+*Return:%falseifthe@workhasalreadybeenpending.Itmeansthat+*eitherthetimerwasrunningortheworkwasqueued.Itreturns%true+*otherwise.+*/+boolqueue_delayed_kthread_work(structkthread_worker*worker,+structdelayed_kthread_work*dwork,+unsignedlongdelay)+{+structkthread_work*work=&dwork->work;+unsignedlongflags;+boolret=false;++spin_lock_irqsave(&worker->lock,flags);++if(!kthread_work_pending(work)){+__queue_delayed_kthread_work(worker,dwork,delay);+ret=true;+}++spin_unlock_irqrestore(&worker->lock,flags);+returnret;+}+EXPORT_SYMBOL_GPL(queue_delayed_kthread_work);+structkthread_flush_work{structkthread_workwork;structcompletiondone;
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Petr Mladek <pmladek@suse.com> Date: 2015-11-18 13:32:32
flush_kthread_worker() returns when the currently queued works are proceed.
But some other works might have been queued in the meantime.
This patch adds drain_kthread_work() that is inspired by drain_workqueue().
It returns when the queue is completely empty and warns when it takes too
long.
The initial implementation does not block queuing new works when draining.
It makes things much easier. The blocking would be useful to debug
potential problems but it is not clear if it is worth the complication
at the moment.
Signed-off-by: Petr Mladek <pmladek@suse.com>
---
kernel/kthread.c | 34 ++++++++++++++++++++++++++++++++++
1 file changed, 34 insertions(+)
--
1.8.5.6
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>
From: Paul E. McKenney <hidden> Date: 2015-11-18 14:25:39
On Wed, Nov 18, 2015 at 02:25:05PM +0100, Petr Mladek wrote:
My intention is to make it easier to manipulate and maintain kthreads.
Especially, I want to replace all the custom main cycles with a
generic one. Also I want to make the kthreads sleep in a consistent
state in a common place when there is no work.
My first attempt was with a brand new API (iterant kthread), see
http://thread.gmane.org/gmane.linux.kernel.api/11892 . But I was
directed to improve the existing kthread worker API. This is
the 3rd iteration of the new direction.
1st patch: add support to check if a timer callback is being called
2nd..12th patches: improve the existing kthread worker API
13th..18th, 20th, 22nd patches: convert several kthreads into
the kthread worker API, namely: khugepaged, ring buffer
benchmark, hung_task, kmemleak, ipmi, IB/fmr_pool,
memstick/r592, intel_powerclamp
21st, 23rd patches: do some preparation steps; they usually do
some clean up that makes sense even without the conversion.
Changes against v2:
+ used worker->lock to synchronize the operations with the work
instead of the PENDING bit as suggested by Tejun Heo; it simplified
the implementation in several ways
+ added timer_active(); used it together with del_timer_sync()
to cancel the work a less tricky way
+ removed the controversial conversion of the RCU kthreads
Thank you! ;-)
Thanx, Paul
--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to majordomo@kvack.org. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"dont@kvack.org"> email@kvack.org </a>