1 // SPDX-License-Identifier: GPL-2.0-only 2 /* Kernel thread helper functions. 3 * Copyright (C) 2004 IBM Corporation, Rusty Russell. 4 * Copyright (C) 2009 Red Hat, Inc. 5 * 6 * Creation is done via kthreadd, so that we get a clean environment 7 * even if we're invoked from userspace (think modprobe, hotplug cpu, 8 * etc.). 9 */ 10 #include <uapi/linux/sched/types.h> 11 #include <linux/mm.h> 12 #include <linux/mmu_context.h> 13 #include <linux/sched.h> 14 #include <linux/sched/mm.h> 15 #include <linux/sched/task.h> 16 #include <linux/kthread.h> 17 #include <linux/completion.h> 18 #include <linux/err.h> 19 #include <linux/cgroup.h> 20 #include <linux/cpuset.h> 21 #include <linux/unistd.h> 22 #include <linux/file.h> 23 #include <linux/export.h> 24 #include <linux/mutex.h> 25 #include <linux/slab.h> 26 #include <linux/freezer.h> 27 #include <linux/ptrace.h> 28 #include <linux/uaccess.h> 29 #include <linux/numa.h> 30 #include <linux/sched/isolation.h> 31 #include <trace/events/sched.h> 32 33 34 static DEFINE_SPINLOCK(kthread_create_lock); 35 static LIST_HEAD(kthread_create_list); 36 struct task_struct *kthreadd_task; 37 38 static LIST_HEAD(kthread_affinity_list); 39 static DEFINE_MUTEX(kthread_affinity_lock); 40 41 struct kthread_create_info 42 { 43 /* Information passed to kthread() from kthreadd. */ 44 char *full_name; 45 int (*threadfn)(void *data); 46 void *data; 47 int node; 48 49 /* Result passed back to kthread_create() from kthreadd. */ 50 struct task_struct *result; 51 struct completion *done; 52 53 struct list_head list; 54 }; 55 56 struct kthread { 57 unsigned long flags; 58 unsigned int cpu; 59 unsigned int node; 60 int started; 61 int result; 62 int (*threadfn)(void *); 63 void *data; 64 struct completion parked; 65 struct completion exited; 66 #ifdef CONFIG_BLK_CGROUP 67 struct cgroup_subsys_state *blkcg_css; 68 #endif 69 /* To store the full name if task comm is truncated. */ 70 char *full_name; 71 struct task_struct *task; 72 struct list_head affinity_node; 73 struct cpumask *preferred_affinity; 74 }; 75 76 enum KTHREAD_BITS { 77 KTHREAD_IS_PER_CPU = 0, 78 KTHREAD_SHOULD_STOP, 79 KTHREAD_SHOULD_PARK, 80 }; 81 82 static inline struct kthread *to_kthread(struct task_struct *k) 83 { 84 WARN_ON(!(k->flags & PF_KTHREAD)); 85 return k->worker_private; 86 } 87 88 void get_kthread_comm(char *buf, size_t buf_size, struct task_struct *tsk) 89 { 90 struct kthread *kthread = to_kthread(tsk); 91 92 if (!kthread || !kthread->full_name) { 93 strscpy(buf, tsk->comm, buf_size); 94 return; 95 } 96 97 strscpy_pad(buf, kthread->full_name, buf_size); 98 } 99 100 bool set_kthread_struct(struct task_struct *p) 101 { 102 struct kthread *kthread; 103 104 if (WARN_ON_ONCE(to_kthread(p))) 105 return false; 106 107 kthread = kzalloc_obj(*kthread); 108 if (!kthread) 109 return false; 110 111 init_completion(&kthread->exited); 112 init_completion(&kthread->parked); 113 INIT_LIST_HEAD(&kthread->affinity_node); 114 p->vfork_done = &kthread->exited; 115 116 kthread->task = p; 117 kthread->node = tsk_fork_get_node(current); 118 p->worker_private = kthread; 119 return true; 120 } 121 122 void free_kthread_struct(struct task_struct *k) 123 { 124 struct kthread *kthread; 125 126 /* 127 * Can be NULL if kmalloc() in set_kthread_struct() failed. 128 */ 129 kthread = to_kthread(k); 130 if (!kthread) 131 return; 132 133 #ifdef CONFIG_BLK_CGROUP 134 WARN_ON_ONCE(kthread->blkcg_css); 135 #endif 136 k->worker_private = NULL; 137 kfree(kthread->full_name); 138 kfree(kthread); 139 } 140 141 /** 142 * kthread_should_stop - should this kthread return now? 143 * 144 * When someone calls kthread_stop() on your kthread, it will be woken 145 * and this will return true. You should then return, and your return 146 * value will be passed through to kthread_stop(). 147 */ 148 bool kthread_should_stop(void) 149 { 150 return test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags); 151 } 152 EXPORT_SYMBOL(kthread_should_stop); 153 154 static bool __kthread_should_park(struct task_struct *k) 155 { 156 return test_bit(KTHREAD_SHOULD_PARK, &to_kthread(k)->flags); 157 } 158 159 /** 160 * kthread_should_park - should this kthread park now? 161 * 162 * When someone calls kthread_park() on your kthread, it will be woken 163 * and this will return true. You should then do the necessary 164 * cleanup and call kthread_parkme() 165 * 166 * Similar to kthread_should_stop(), but this keeps the thread alive 167 * and in a park position. kthread_unpark() "restarts" the thread and 168 * calls the thread function again. 169 */ 170 bool kthread_should_park(void) 171 { 172 return __kthread_should_park(current); 173 } 174 EXPORT_SYMBOL_GPL(kthread_should_park); 175 176 bool kthread_should_stop_or_park(void) 177 { 178 struct kthread *kthread = tsk_is_kthread(current); 179 180 if (!kthread) 181 return false; 182 183 return kthread->flags & (BIT(KTHREAD_SHOULD_STOP) | BIT(KTHREAD_SHOULD_PARK)); 184 } 185 186 /** 187 * kthread_freezable_should_stop - should this freezable kthread return now? 188 * @was_frozen: optional out parameter, indicates whether %current was frozen 189 * 190 * kthread_should_stop() for freezable kthreads, which will enter 191 * refrigerator if necessary. This function is safe from kthread_stop() / 192 * freezer deadlock and freezable kthreads should use this function instead 193 * of calling try_to_freeze() directly. 194 */ 195 bool kthread_freezable_should_stop(bool *was_frozen) 196 { 197 bool frozen = false; 198 199 might_sleep(); 200 201 if (unlikely(freezing(current))) 202 frozen = __refrigerator(true); 203 204 if (was_frozen) 205 *was_frozen = frozen; 206 207 return kthread_should_stop(); 208 } 209 EXPORT_SYMBOL_GPL(kthread_freezable_should_stop); 210 211 /** 212 * kthread_func - return the function specified on kthread creation 213 * @task: kthread task in question 214 * 215 * Returns NULL if the task is not a kthread. 216 */ 217 void *kthread_func(struct task_struct *task) 218 { 219 struct kthread *kthread = tsk_is_kthread(task); 220 if (kthread) 221 return kthread->threadfn; 222 return NULL; 223 } 224 EXPORT_SYMBOL_GPL(kthread_func); 225 226 /** 227 * kthread_data - return data value specified on kthread creation 228 * @task: kthread task in question 229 * 230 * Return the data value specified when kthread @task was created. 231 * The caller is responsible for ensuring the validity of @task when 232 * calling this function. 233 */ 234 void *kthread_data(struct task_struct *task) 235 { 236 return to_kthread(task)->data; 237 } 238 EXPORT_SYMBOL_GPL(kthread_data); 239 240 /** 241 * kthread_probe_data - speculative version of kthread_data() 242 * @task: possible kthread task in question 243 * 244 * @task could be a kthread task. Return the data value specified when it 245 * was created if accessible. If @task isn't a kthread task or its data is 246 * inaccessible for any reason, %NULL is returned. This function requires 247 * that @task itself is safe to dereference. 248 */ 249 void *kthread_probe_data(struct task_struct *task) 250 { 251 struct kthread *kthread = tsk_is_kthread(task); 252 void *data = NULL; 253 254 if (kthread) 255 copy_from_kernel_nofault(&data, &kthread->data, sizeof(data)); 256 return data; 257 } 258 259 static void __kthread_parkme(struct kthread *self) 260 { 261 for (;;) { 262 /* 263 * TASK_PARKED is a special state; we must serialize against 264 * possible pending wakeups to avoid store-store collisions on 265 * task->state. 266 * 267 * Such a collision might possibly result in the task state 268 * changin from TASK_PARKED and us failing the 269 * wait_task_inactive() in kthread_park(). 270 */ 271 set_special_state(TASK_PARKED); 272 if (!test_bit(KTHREAD_SHOULD_PARK, &self->flags)) 273 break; 274 275 /* 276 * Thread is going to call schedule(), do not preempt it, 277 * or the caller of kthread_park() may spend more time in 278 * wait_task_inactive(). 279 */ 280 preempt_disable(); 281 complete(&self->parked); 282 schedule_preempt_disabled(); 283 preempt_enable(); 284 } 285 __set_current_state(TASK_RUNNING); 286 } 287 288 void kthread_parkme(void) 289 { 290 __kthread_parkme(to_kthread(current)); 291 } 292 EXPORT_SYMBOL_GPL(kthread_parkme); 293 294 void kthread_do_exit(struct kthread *kthread, long result) 295 { 296 kthread->result = result; 297 if (!list_empty(&kthread->affinity_node)) { 298 mutex_lock(&kthread_affinity_lock); 299 list_del(&kthread->affinity_node); 300 mutex_unlock(&kthread_affinity_lock); 301 302 if (kthread->preferred_affinity) { 303 kfree(kthread->preferred_affinity); 304 kthread->preferred_affinity = NULL; 305 } 306 } 307 } 308 309 /** 310 * kthread_complete_and_exit - Exit the current kthread. 311 * @comp: Completion to complete 312 * @code: The integer value to return to kthread_stop(). 313 * 314 * If present, complete @comp and then return code to kthread_stop(). 315 * 316 * A kernel thread whose module may be removed after the completion of 317 * @comp can use this function to exit safely. 318 * 319 * Does not return. 320 */ 321 void __noreturn kthread_complete_and_exit(struct completion *comp, long code) 322 { 323 if (comp) 324 complete(comp); 325 326 kthread_exit(code); 327 } 328 EXPORT_SYMBOL(kthread_complete_and_exit); 329 330 static void kthread_fetch_affinity(struct kthread *kthread, struct cpumask *cpumask) 331 { 332 const struct cpumask *pref; 333 334 guard(rcu)(); 335 336 if (kthread->preferred_affinity) { 337 pref = kthread->preferred_affinity; 338 } else { 339 if (kthread->node == NUMA_NO_NODE) 340 pref = housekeeping_cpumask(HK_TYPE_DOMAIN); 341 else 342 pref = cpumask_of_node(kthread->node); 343 } 344 345 cpumask_and(cpumask, pref, housekeeping_cpumask(HK_TYPE_DOMAIN)); 346 if (cpumask_empty(cpumask)) 347 cpumask_copy(cpumask, housekeeping_cpumask(HK_TYPE_DOMAIN)); 348 } 349 350 static void kthread_affine_node(void) 351 { 352 struct kthread *kthread = to_kthread(current); 353 cpumask_var_t affinity; 354 355 if (WARN_ON_ONCE(kthread_is_per_cpu(current))) 356 return; 357 358 if (!zalloc_cpumask_var(&affinity, GFP_KERNEL)) { 359 WARN_ON_ONCE(1); 360 return; 361 } 362 363 mutex_lock(&kthread_affinity_lock); 364 WARN_ON_ONCE(!list_empty(&kthread->affinity_node)); 365 list_add_tail(&kthread->affinity_node, &kthread_affinity_list); 366 /* 367 * The node cpumask is racy when read from kthread() but: 368 * - a racing CPU going down will either fail on the subsequent 369 * call to set_cpus_allowed_ptr() or be migrated to housekeepers 370 * afterwards by the scheduler. 371 * - a racing CPU going up will be handled by kthreads_online_cpu() 372 */ 373 kthread_fetch_affinity(kthread, affinity); 374 set_cpus_allowed_ptr(current, affinity); 375 mutex_unlock(&kthread_affinity_lock); 376 377 free_cpumask_var(affinity); 378 } 379 380 static int kthread(void *_create) 381 { 382 static const struct sched_param param = { .sched_priority = 0 }; 383 /* Copy data: it's on kthread's stack */ 384 struct kthread_create_info *create = _create; 385 int (*threadfn)(void *data) = create->threadfn; 386 void *data = create->data; 387 struct completion *done; 388 struct kthread *self; 389 int ret; 390 391 self = to_kthread(current); 392 393 /* Release the structure when caller killed by a fatal signal. */ 394 done = xchg(&create->done, NULL); 395 if (!done) { 396 kfree(create->full_name); 397 kfree(create); 398 kthread_exit(-EINTR); 399 } 400 401 self->full_name = create->full_name; 402 self->threadfn = threadfn; 403 self->data = data; 404 405 /* 406 * The new thread inherited kthreadd's priority and CPU mask. Reset 407 * back to default in case they have been changed. 408 */ 409 sched_setscheduler_nocheck(current, SCHED_NORMAL, ¶m); 410 411 /* OK, tell user we're spawned, wait for stop or wakeup */ 412 __set_current_state(TASK_UNINTERRUPTIBLE); 413 create->result = current; 414 /* 415 * Thread is going to call schedule(), do not preempt it, 416 * or the creator may spend more time in wait_task_inactive(). 417 */ 418 preempt_disable(); 419 complete(done); 420 schedule_preempt_disabled(); 421 preempt_enable(); 422 423 self->started = 1; 424 425 /* 426 * Apply default node affinity if no call to kthread_bind[_mask]() nor 427 * kthread_affine_preferred() was issued before the first wake-up. 428 */ 429 if (!(current->flags & PF_NO_SETAFFINITY) && !self->preferred_affinity) 430 kthread_affine_node(); 431 432 ret = -EINTR; 433 if (!test_bit(KTHREAD_SHOULD_STOP, &self->flags)) { 434 cgroup_kthread_ready(); 435 __kthread_parkme(self); 436 ret = threadfn(data); 437 } 438 kthread_exit(ret); 439 } 440 441 /* called from kernel_clone() to get node information for about to be created task */ 442 int tsk_fork_get_node(struct task_struct *tsk) 443 { 444 #ifdef CONFIG_NUMA 445 if (tsk == kthreadd_task) 446 return tsk->pref_node_fork; 447 #endif 448 return NUMA_NO_NODE; 449 } 450 451 static void create_kthread(struct kthread_create_info *create) 452 { 453 int pid; 454 455 #ifdef CONFIG_NUMA 456 current->pref_node_fork = create->node; 457 #endif 458 /* We want our own signal handler (we take no signals by default). */ 459 pid = kernel_thread(kthread, create, create->full_name, 460 CLONE_FS | CLONE_FILES | SIGCHLD); 461 if (pid < 0) { 462 /* Release the structure when caller killed by a fatal signal. */ 463 struct completion *done = xchg(&create->done, NULL); 464 465 kfree(create->full_name); 466 if (!done) { 467 kfree(create); 468 return; 469 } 470 create->result = ERR_PTR(pid); 471 complete(done); 472 } 473 } 474 475 static __printf(4, 0) 476 struct task_struct *__kthread_create_on_node(int (*threadfn)(void *data), 477 void *data, int node, 478 const char namefmt[], 479 va_list args) 480 { 481 DECLARE_COMPLETION_ONSTACK(done); 482 struct task_struct *task; 483 struct kthread_create_info *create = kmalloc_obj(*create); 484 485 if (!create) 486 return ERR_PTR(-ENOMEM); 487 create->threadfn = threadfn; 488 create->data = data; 489 create->node = node; 490 create->done = &done; 491 create->full_name = kvasprintf(GFP_KERNEL, namefmt, args); 492 if (!create->full_name) { 493 task = ERR_PTR(-ENOMEM); 494 goto free_create; 495 } 496 497 spin_lock(&kthread_create_lock); 498 list_add_tail(&create->list, &kthread_create_list); 499 spin_unlock(&kthread_create_lock); 500 501 wake_up_process(kthreadd_task); 502 /* 503 * Wait for completion in killable state, for I might be chosen by 504 * the OOM killer while kthreadd is trying to allocate memory for 505 * new kernel thread. 506 */ 507 if (unlikely(wait_for_completion_killable(&done))) { 508 /* 509 * If I was killed by a fatal signal before kthreadd (or new 510 * kernel thread) calls complete(), leave the cleanup of this 511 * structure to that thread. 512 */ 513 if (xchg(&create->done, NULL)) 514 return ERR_PTR(-EINTR); 515 /* 516 * kthreadd (or new kernel thread) will call complete() 517 * shortly. 518 */ 519 wait_for_completion(&done); 520 } 521 task = create->result; 522 free_create: 523 kfree(create); 524 return task; 525 } 526 527 /** 528 * kthread_create_on_node - create a kthread. 529 * @threadfn: the function to run until signal_pending(current). 530 * @data: data ptr for @threadfn. 531 * @node: task and thread structures for the thread are allocated on this node 532 * @namefmt: printf-style name for the thread. 533 * 534 * Description: This helper function creates and names a kernel 535 * thread. The thread will be stopped: use wake_up_process() to start 536 * it. See also kthread_run(). The new thread has SCHED_NORMAL policy and 537 * is affine to all CPUs. 538 * 539 * If thread is going to be bound on a particular cpu, give its node 540 * in @node, to get NUMA affinity for kthread stack, or else give NUMA_NO_NODE. 541 * When woken, the thread will run @threadfn() with @data as its 542 * argument. @threadfn() can either return directly if it is a 543 * standalone thread for which no one will call kthread_stop(), or 544 * return when 'kthread_should_stop()' is true (which means 545 * kthread_stop() has been called). The return value should be zero 546 * or a negative error number; it will be passed to kthread_stop(). 547 * 548 * Returns a task_struct or ERR_PTR(-ENOMEM) or ERR_PTR(-EINTR). 549 */ 550 struct task_struct *kthread_create_on_node(int (*threadfn)(void *data), 551 void *data, int node, 552 const char namefmt[], 553 ...) 554 { 555 struct task_struct *task; 556 va_list args; 557 558 va_start(args, namefmt); 559 task = __kthread_create_on_node(threadfn, data, node, namefmt, args); 560 va_end(args); 561 562 return task; 563 } 564 EXPORT_SYMBOL(kthread_create_on_node); 565 566 static void __kthread_bind_mask(struct task_struct *p, const struct cpumask *mask, unsigned int state) 567 { 568 if (!wait_task_inactive(p, state)) { 569 WARN_ON(1); 570 return; 571 } 572 573 scoped_guard (raw_spinlock_irqsave, &p->pi_lock) 574 set_cpus_allowed_force(p, mask); 575 576 /* It's safe because the task is inactive. */ 577 p->flags |= PF_NO_SETAFFINITY; 578 } 579 580 static void __kthread_bind(struct task_struct *p, unsigned int cpu, unsigned int state) 581 { 582 __kthread_bind_mask(p, cpumask_of(cpu), state); 583 } 584 585 void kthread_bind_mask(struct task_struct *p, const struct cpumask *mask) 586 { 587 struct kthread *kthread = to_kthread(p); 588 __kthread_bind_mask(p, mask, TASK_UNINTERRUPTIBLE); 589 WARN_ON_ONCE(kthread->started); 590 } 591 592 /** 593 * kthread_bind - bind a just-created kthread to a cpu. 594 * @p: thread created by kthread_create(). 595 * @cpu: cpu (might not be online, must be possible) for @k to run on. 596 * 597 * Description: This function is equivalent to set_cpus_allowed(), 598 * except that @cpu doesn't need to be online, and the thread must be 599 * stopped (i.e., just returned from kthread_create()). 600 */ 601 void kthread_bind(struct task_struct *p, unsigned int cpu) 602 { 603 struct kthread *kthread = to_kthread(p); 604 __kthread_bind(p, cpu, TASK_UNINTERRUPTIBLE); 605 WARN_ON_ONCE(kthread->started); 606 } 607 EXPORT_SYMBOL(kthread_bind); 608 609 /** 610 * kthread_create_on_cpu - Create a cpu bound kthread 611 * @threadfn: the function to run until signal_pending(current). 612 * @data: data ptr for @threadfn. 613 * @cpu: The cpu on which the thread should be bound, 614 * @namefmt: printf-style name for the thread. Format is restricted 615 * to "name.*%u". Code fills in cpu number. 616 * 617 * Description: This helper function creates and names a kernel thread 618 */ 619 struct task_struct *kthread_create_on_cpu(int (*threadfn)(void *data), 620 void *data, unsigned int cpu, 621 const char *namefmt) 622 { 623 struct task_struct *p; 624 625 p = kthread_create_on_node(threadfn, data, cpu_to_node(cpu), namefmt, 626 cpu); 627 if (IS_ERR(p)) 628 return p; 629 kthread_bind(p, cpu); 630 /* CPU hotplug need to bind once again when unparking the thread. */ 631 to_kthread(p)->cpu = cpu; 632 return p; 633 } 634 EXPORT_SYMBOL(kthread_create_on_cpu); 635 636 void kthread_set_per_cpu(struct task_struct *k, int cpu) 637 { 638 struct kthread *kthread = to_kthread(k); 639 if (!kthread) 640 return; 641 642 WARN_ON_ONCE(!(k->flags & PF_NO_SETAFFINITY)); 643 644 if (cpu < 0) { 645 clear_bit(KTHREAD_IS_PER_CPU, &kthread->flags); 646 return; 647 } 648 649 kthread->cpu = cpu; 650 set_bit(KTHREAD_IS_PER_CPU, &kthread->flags); 651 } 652 653 bool kthread_is_per_cpu(struct task_struct *p) 654 { 655 struct kthread *kthread = tsk_is_kthread(p); 656 if (!kthread) 657 return false; 658 659 return test_bit(KTHREAD_IS_PER_CPU, &kthread->flags); 660 } 661 662 /** 663 * kthread_unpark - unpark a thread created by kthread_create(). 664 * @k: thread created by kthread_create(). 665 * 666 * Sets kthread_should_park() for @k to return false, wakes it, and 667 * waits for it to return. If the thread is marked percpu then its 668 * bound to the cpu again. 669 */ 670 void kthread_unpark(struct task_struct *k) 671 { 672 struct kthread *kthread = to_kthread(k); 673 674 if (!test_bit(KTHREAD_SHOULD_PARK, &kthread->flags)) 675 return; 676 /* 677 * Newly created kthread was parked when the CPU was offline. 678 * The binding was lost and we need to set it again. 679 */ 680 if (test_bit(KTHREAD_IS_PER_CPU, &kthread->flags)) 681 __kthread_bind(k, kthread->cpu, TASK_PARKED); 682 683 clear_bit(KTHREAD_SHOULD_PARK, &kthread->flags); 684 /* 685 * __kthread_parkme() will either see !SHOULD_PARK or get the wakeup. 686 */ 687 wake_up_state(k, TASK_PARKED); 688 } 689 EXPORT_SYMBOL_GPL(kthread_unpark); 690 691 /** 692 * kthread_park - park a thread created by kthread_create(). 693 * @k: thread created by kthread_create(). 694 * 695 * Sets kthread_should_park() for @k to return true, wakes it, and 696 * waits for it to return. This can also be called after kthread_create() 697 * instead of calling wake_up_process(): the thread will park without 698 * calling threadfn(). 699 * 700 * Returns 0 if the thread is parked, -ENOSYS if the thread exited. 701 * If called by the kthread itself just the park bit is set. 702 */ 703 int kthread_park(struct task_struct *k) 704 { 705 struct kthread *kthread = to_kthread(k); 706 707 if (WARN_ON(k->flags & PF_EXITING)) 708 return -ENOSYS; 709 710 if (WARN_ON_ONCE(test_bit(KTHREAD_SHOULD_PARK, &kthread->flags))) 711 return -EBUSY; 712 713 set_bit(KTHREAD_SHOULD_PARK, &kthread->flags); 714 if (k != current) { 715 wake_up_process(k); 716 /* 717 * Wait for __kthread_parkme() to complete(), this means we 718 * _will_ have TASK_PARKED and are about to call schedule(). 719 */ 720 wait_for_completion(&kthread->parked); 721 /* 722 * Now wait for that schedule() to complete and the task to 723 * get scheduled out. 724 */ 725 WARN_ON_ONCE(!wait_task_inactive(k, TASK_PARKED)); 726 } 727 728 return 0; 729 } 730 EXPORT_SYMBOL_GPL(kthread_park); 731 732 /** 733 * kthread_stop - stop a thread created by kthread_create(). 734 * @k: thread created by kthread_create(). 735 * 736 * Sets kthread_should_stop() for @k to return true, wakes it, and 737 * waits for it to exit. This can also be called after kthread_create() 738 * instead of calling wake_up_process(): the thread will exit without 739 * calling threadfn(). 740 * 741 * If threadfn() may call kthread_exit() itself, the caller must ensure 742 * task_struct can't go away. 743 * 744 * Returns the result of threadfn(), or %-EINTR if wake_up_process() 745 * was never called. 746 */ 747 int kthread_stop(struct task_struct *k) 748 { 749 struct kthread *kthread; 750 int ret; 751 752 trace_sched_kthread_stop(k); 753 754 get_task_struct(k); 755 kthread = to_kthread(k); 756 set_bit(KTHREAD_SHOULD_STOP, &kthread->flags); 757 kthread_unpark(k); 758 set_tsk_thread_flag(k, TIF_NOTIFY_SIGNAL); 759 wake_up_process(k); 760 wait_for_completion(&kthread->exited); 761 ret = kthread->result; 762 put_task_struct(k); 763 764 trace_sched_kthread_stop_ret(ret); 765 return ret; 766 } 767 EXPORT_SYMBOL(kthread_stop); 768 769 /** 770 * kthread_stop_put - stop a thread and put its task struct 771 * @k: thread created by kthread_create(). 772 * 773 * Stops a thread created by kthread_create() and put its task_struct. 774 * Only use when holding an extra task struct reference obtained by 775 * calling get_task_struct(). 776 */ 777 int kthread_stop_put(struct task_struct *k) 778 { 779 int ret; 780 781 ret = kthread_stop(k); 782 put_task_struct(k); 783 return ret; 784 } 785 EXPORT_SYMBOL(kthread_stop_put); 786 787 int kthreadd(void *unused) 788 { 789 static const char comm[TASK_COMM_LEN] = "kthreadd"; 790 struct task_struct *tsk = current; 791 792 /* Setup a clean context for our children to inherit. */ 793 set_task_comm(tsk, comm); 794 ignore_signals(tsk); 795 set_mems_allowed(node_states[N_MEMORY]); 796 797 current->flags |= PF_NOFREEZE; 798 cgroup_init_kthreadd(); 799 800 kthread_affine_node(); 801 802 for (;;) { 803 set_current_state(TASK_INTERRUPTIBLE); 804 if (list_empty(&kthread_create_list)) 805 schedule(); 806 __set_current_state(TASK_RUNNING); 807 808 spin_lock(&kthread_create_lock); 809 while (!list_empty(&kthread_create_list)) { 810 struct kthread_create_info *create; 811 812 create = list_entry(kthread_create_list.next, 813 struct kthread_create_info, list); 814 list_del_init(&create->list); 815 spin_unlock(&kthread_create_lock); 816 817 create_kthread(create); 818 819 spin_lock(&kthread_create_lock); 820 } 821 spin_unlock(&kthread_create_lock); 822 } 823 824 return 0; 825 } 826 827 /** 828 * kthread_affine_preferred - Define a kthread's preferred affinity 829 * @p: thread created by kthread_create(). 830 * @mask: preferred mask of CPUs (might not be online, must be possible) for @p 831 * to run on. 832 * 833 * Similar to kthread_bind_mask() except that the affinity is not a requirement 834 * but rather a preference that can be constrained by CPU isolation or CPU hotplug. 835 * Must be called before the first wakeup of the kthread. 836 * 837 * Returns 0 if the affinity has been applied. 838 */ 839 int kthread_affine_preferred(struct task_struct *p, const struct cpumask *mask) 840 { 841 struct kthread *kthread = to_kthread(p); 842 cpumask_var_t affinity; 843 int ret = 0; 844 845 if (!wait_task_inactive(p, TASK_UNINTERRUPTIBLE) || kthread->started) { 846 WARN_ON(1); 847 return -EINVAL; 848 } 849 850 WARN_ON_ONCE(kthread->preferred_affinity); 851 852 if (!zalloc_cpumask_var(&affinity, GFP_KERNEL)) 853 return -ENOMEM; 854 855 kthread->preferred_affinity = kzalloc(sizeof(struct cpumask), GFP_KERNEL); 856 if (!kthread->preferred_affinity) { 857 ret = -ENOMEM; 858 goto out; 859 } 860 861 mutex_lock(&kthread_affinity_lock); 862 cpumask_copy(kthread->preferred_affinity, mask); 863 WARN_ON_ONCE(!list_empty(&kthread->affinity_node)); 864 list_add_tail(&kthread->affinity_node, &kthread_affinity_list); 865 kthread_fetch_affinity(kthread, affinity); 866 867 scoped_guard (raw_spinlock_irqsave, &p->pi_lock) 868 set_cpus_allowed_force(p, affinity); 869 870 mutex_unlock(&kthread_affinity_lock); 871 out: 872 free_cpumask_var(affinity); 873 874 return ret; 875 } 876 EXPORT_SYMBOL_GPL(kthread_affine_preferred); 877 878 static int kthreads_update_affinity(bool force) 879 { 880 cpumask_var_t affinity; 881 struct kthread *k; 882 int ret; 883 884 guard(mutex)(&kthread_affinity_lock); 885 886 if (list_empty(&kthread_affinity_list)) 887 return 0; 888 889 if (!zalloc_cpumask_var(&affinity, GFP_KERNEL)) 890 return -ENOMEM; 891 892 ret = 0; 893 894 list_for_each_entry(k, &kthread_affinity_list, affinity_node) { 895 if (WARN_ON_ONCE((k->task->flags & PF_NO_SETAFFINITY) || 896 kthread_is_per_cpu(k->task))) { 897 ret = -EINVAL; 898 continue; 899 } 900 901 /* 902 * Unbound kthreads without preferred affinity are already affine 903 * to housekeeping, whether those CPUs are online or not. So no need 904 * to handle newly online CPUs for them. However housekeeping changes 905 * have to be applied. 906 * 907 * But kthreads with a preferred affinity or node are different: 908 * if none of their preferred CPUs are online and part of 909 * housekeeping at the same time, they must be affine to housekeeping. 910 * But as soon as one of their preferred CPU becomes online, they must 911 * be affine to them. 912 */ 913 if (force || k->preferred_affinity || k->node != NUMA_NO_NODE) { 914 kthread_fetch_affinity(k, affinity); 915 set_cpus_allowed_ptr(k->task, affinity); 916 } 917 } 918 919 free_cpumask_var(affinity); 920 921 return ret; 922 } 923 924 /** 925 * kthreads_update_housekeeping - Update kthreads affinity on cpuset change 926 * 927 * When cpuset changes a partition type to/from "isolated" or updates related 928 * cpumasks, propagate the housekeeping cpumask change to preferred kthreads 929 * affinity. 930 * 931 * Returns 0 if successful, -ENOMEM if temporary mask couldn't 932 * be allocated or -EINVAL in case of internal error. 933 */ 934 int kthreads_update_housekeeping(void) 935 { 936 return kthreads_update_affinity(true); 937 } 938 939 /* 940 * Re-affine kthreads according to their preferences 941 * and the newly online CPU. The CPU down part is handled 942 * by select_fallback_rq() which default re-affines to 943 * housekeepers from other nodes in case the preferred 944 * affinity doesn't apply anymore. 945 */ 946 static int kthreads_online_cpu(unsigned int cpu) 947 { 948 return kthreads_update_affinity(false); 949 } 950 951 static int kthreads_init(void) 952 { 953 return cpuhp_setup_state(CPUHP_AP_KTHREADS_ONLINE, "kthreads:online", 954 kthreads_online_cpu, NULL); 955 } 956 early_initcall(kthreads_init); 957 958 void __kthread_init_worker(struct kthread_worker *worker, 959 const char *name, 960 struct lock_class_key *key) 961 { 962 memset(worker, 0, sizeof(struct kthread_worker)); 963 raw_spin_lock_init(&worker->lock); 964 lockdep_set_class_and_name(&worker->lock, key, name); 965 INIT_LIST_HEAD(&worker->work_list); 966 INIT_LIST_HEAD(&worker->delayed_work_list); 967 } 968 EXPORT_SYMBOL_GPL(__kthread_init_worker); 969 970 /** 971 * kthread_worker_fn - kthread function to process kthread_worker 972 * @worker_ptr: pointer to initialized kthread_worker 973 * 974 * This function implements the main cycle of kthread worker. It processes 975 * work_list until it is stopped with kthread_stop(). It sleeps when the queue 976 * is empty. 977 * 978 * The works are not allowed to keep any locks, disable preemption or interrupts 979 * when they finish. There is defined a safe point for freezing when one work 980 * finishes and before a new one is started. 981 * 982 * Also the works must not be handled by more than one worker at the same time, 983 * see also kthread_queue_work(). 984 */ 985 int kthread_worker_fn(void *worker_ptr) 986 { 987 struct kthread_worker *worker = worker_ptr; 988 struct kthread_work *work; 989 990 /* 991 * FIXME: Update the check and remove the assignment when all kthread 992 * worker users are created using kthread_create_worker*() functions. 993 */ 994 WARN_ON(worker->task && worker->task != current); 995 worker->task = current; 996 997 if (worker->flags & KTW_FREEZABLE) 998 set_freezable(); 999 1000 repeat: 1001 set_current_state(TASK_INTERRUPTIBLE); /* mb paired w/ kthread_stop */ 1002 1003 if (kthread_should_stop()) { 1004 __set_current_state(TASK_RUNNING); 1005 raw_spin_lock_irq(&worker->lock); 1006 worker->task = NULL; 1007 raw_spin_unlock_irq(&worker->lock); 1008 return 0; 1009 } 1010 1011 work = NULL; 1012 raw_spin_lock_irq(&worker->lock); 1013 if (!list_empty(&worker->work_list)) { 1014 work = list_first_entry(&worker->work_list, 1015 struct kthread_work, node); 1016 list_del_init(&work->node); 1017 } 1018 worker->current_work = work; 1019 raw_spin_unlock_irq(&worker->lock); 1020 1021 if (work) { 1022 kthread_work_func_t func = work->func; 1023 __set_current_state(TASK_RUNNING); 1024 trace_sched_kthread_work_execute_start(work); 1025 work->func(work); 1026 /* 1027 * Avoid dereferencing work after this point. The trace 1028 * event only cares about the address. 1029 */ 1030 trace_sched_kthread_work_execute_end(work, func); 1031 } else if (!freezing(current)) { 1032 schedule(); 1033 } else { 1034 /* 1035 * Handle the case where the current remains 1036 * TASK_INTERRUPTIBLE. try_to_freeze() expects 1037 * the current to be TASK_RUNNING. 1038 */ 1039 __set_current_state(TASK_RUNNING); 1040 } 1041 1042 try_to_freeze(); 1043 cond_resched(); 1044 goto repeat; 1045 } 1046 EXPORT_SYMBOL_GPL(kthread_worker_fn); 1047 1048 static __printf(3, 0) struct kthread_worker * 1049 __kthread_create_worker_on_node(unsigned int flags, int node, 1050 const char namefmt[], va_list args) 1051 { 1052 struct kthread_worker *worker; 1053 struct task_struct *task; 1054 1055 worker = kzalloc_obj(*worker); 1056 if (!worker) 1057 return ERR_PTR(-ENOMEM); 1058 1059 kthread_init_worker(worker); 1060 1061 task = __kthread_create_on_node(kthread_worker_fn, worker, 1062 node, namefmt, args); 1063 if (IS_ERR(task)) 1064 goto fail_task; 1065 1066 worker->flags = flags; 1067 worker->task = task; 1068 1069 return worker; 1070 1071 fail_task: 1072 kfree(worker); 1073 return ERR_CAST(task); 1074 } 1075 1076 /** 1077 * kthread_create_worker_on_node - create a kthread worker 1078 * @flags: flags modifying the default behavior of the worker 1079 * @node: task structure for the thread is allocated on this node 1080 * @namefmt: printf-style name for the kthread worker (task). 1081 * 1082 * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM) 1083 * when the needed structures could not get allocated, and ERR_PTR(-EINTR) 1084 * when the caller was killed by a fatal signal. 1085 */ 1086 struct kthread_worker * 1087 kthread_create_worker_on_node(unsigned int flags, int node, const char namefmt[], ...) 1088 { 1089 struct kthread_worker *worker; 1090 va_list args; 1091 1092 va_start(args, namefmt); 1093 worker = __kthread_create_worker_on_node(flags, node, namefmt, args); 1094 va_end(args); 1095 1096 return worker; 1097 } 1098 EXPORT_SYMBOL(kthread_create_worker_on_node); 1099 1100 /** 1101 * kthread_create_worker_on_cpu - create a kthread worker and bind it 1102 * to a given CPU and the associated NUMA node. 1103 * @cpu: CPU number 1104 * @flags: flags modifying the default behavior of the worker 1105 * @namefmt: printf-style name for the thread. Format is restricted 1106 * to "name.*%u". Code fills in cpu number. 1107 * 1108 * Use a valid CPU number if you want to bind the kthread worker 1109 * to the given CPU and the associated NUMA node. 1110 * 1111 * A good practice is to add the cpu number also into the worker name. 1112 * For example, use kthread_create_worker_on_cpu(cpu, "helper/%d", cpu). 1113 * 1114 * CPU hotplug: 1115 * The kthread worker API is simple and generic. It just provides a way 1116 * to create, use, and destroy workers. 1117 * 1118 * It is up to the API user how to handle CPU hotplug. They have to decide 1119 * how to handle pending work items, prevent queuing new ones, and 1120 * restore the functionality when the CPU goes off and on. There are a 1121 * few catches: 1122 * 1123 * - CPU affinity gets lost when it is scheduled on an offline CPU. 1124 * 1125 * - The worker might not exist when the CPU was off when the user 1126 * created the workers. 1127 * 1128 * Good practice is to implement two CPU hotplug callbacks and to 1129 * destroy/create the worker when the CPU goes down/up. 1130 * 1131 * Return: 1132 * The pointer to the allocated worker on success, ERR_PTR(-ENOMEM) 1133 * when the needed structures could not get allocated, and ERR_PTR(-EINTR) 1134 * when the caller was killed by a fatal signal. 1135 */ 1136 struct kthread_worker * 1137 kthread_create_worker_on_cpu(int cpu, unsigned int flags, 1138 const char namefmt[]) 1139 { 1140 struct kthread_worker *worker; 1141 1142 worker = kthread_create_worker_on_node(flags, cpu_to_node(cpu), namefmt, cpu); 1143 if (!IS_ERR(worker)) 1144 kthread_bind(worker->task, cpu); 1145 1146 return worker; 1147 } 1148 EXPORT_SYMBOL(kthread_create_worker_on_cpu); 1149 1150 /* 1151 * Returns true when the work could not be queued at the moment. 1152 * It happens when it is already pending in a worker list 1153 * or when it is being cancelled. 1154 */ 1155 static inline bool queuing_blocked(struct kthread_worker *worker, 1156 struct kthread_work *work) 1157 { 1158 lockdep_assert_held(&worker->lock); 1159 1160 return !list_empty(&work->node) || work->canceling; 1161 } 1162 1163 static void kthread_insert_work_sanity_check(struct kthread_worker *worker, 1164 struct kthread_work *work) 1165 { 1166 lockdep_assert_held(&worker->lock); 1167 WARN_ON_ONCE(!list_empty(&work->node)); 1168 /* Do not use a work with >1 worker, see kthread_queue_work() */ 1169 WARN_ON_ONCE(work->worker && work->worker != worker); 1170 } 1171 1172 /* insert @work before @pos in @worker */ 1173 static void kthread_insert_work(struct kthread_worker *worker, 1174 struct kthread_work *work, 1175 struct list_head *pos) 1176 { 1177 kthread_insert_work_sanity_check(worker, work); 1178 1179 trace_sched_kthread_work_queue_work(worker, work); 1180 1181 list_add_tail(&work->node, pos); 1182 work->worker = worker; 1183 if (!worker->current_work && likely(worker->task)) 1184 wake_up_process(worker->task); 1185 } 1186 1187 /** 1188 * kthread_queue_work - queue a kthread_work 1189 * @worker: target kthread_worker 1190 * @work: kthread_work to queue 1191 * 1192 * Queue @work to work processor @task for async execution. @task 1193 * must have been created with kthread_create_worker(). Returns %true 1194 * if @work was successfully queued, %false if it was already pending. 1195 * 1196 * Reinitialize the work if it needs to be used by another worker. 1197 * For example, when the worker was stopped and started again. 1198 */ 1199 bool kthread_queue_work(struct kthread_worker *worker, 1200 struct kthread_work *work) 1201 { 1202 bool ret = false; 1203 unsigned long flags; 1204 1205 raw_spin_lock_irqsave(&worker->lock, flags); 1206 if (!queuing_blocked(worker, work)) { 1207 kthread_insert_work(worker, work, &worker->work_list); 1208 ret = true; 1209 } 1210 raw_spin_unlock_irqrestore(&worker->lock, flags); 1211 return ret; 1212 } 1213 EXPORT_SYMBOL_GPL(kthread_queue_work); 1214 1215 /** 1216 * kthread_delayed_work_timer_fn - callback that queues the associated kthread 1217 * delayed work when the timer expires. 1218 * @t: pointer to the expired timer 1219 * 1220 * The format of the function is defined by struct timer_list. 1221 * It should have been called from irqsafe timer with irq already off. 1222 */ 1223 void kthread_delayed_work_timer_fn(struct timer_list *t) 1224 { 1225 struct kthread_delayed_work *dwork = timer_container_of(dwork, t, 1226 timer); 1227 struct kthread_work *work = &dwork->work; 1228 struct kthread_worker *worker = work->worker; 1229 unsigned long flags; 1230 1231 /* 1232 * This might happen when a pending work is reinitialized. 1233 * It means that it is used a wrong way. 1234 */ 1235 if (WARN_ON_ONCE(!worker)) 1236 return; 1237 1238 raw_spin_lock_irqsave(&worker->lock, flags); 1239 /* Work must not be used with >1 worker, see kthread_queue_work(). */ 1240 WARN_ON_ONCE(work->worker != worker); 1241 1242 /* Move the work from worker->delayed_work_list. */ 1243 WARN_ON_ONCE(list_empty(&work->node)); 1244 list_del_init(&work->node); 1245 if (!work->canceling) 1246 kthread_insert_work(worker, work, &worker->work_list); 1247 1248 raw_spin_unlock_irqrestore(&worker->lock, flags); 1249 } 1250 EXPORT_SYMBOL(kthread_delayed_work_timer_fn); 1251 1252 static void __kthread_queue_delayed_work(struct kthread_worker *worker, 1253 struct kthread_delayed_work *dwork, 1254 unsigned long delay) 1255 { 1256 struct timer_list *timer = &dwork->timer; 1257 struct kthread_work *work = &dwork->work; 1258 1259 WARN_ON_ONCE(timer->function != kthread_delayed_work_timer_fn); 1260 1261 /* 1262 * If @delay is 0, queue @dwork->work immediately. This is for 1263 * both optimization and correctness. The earliest @timer can 1264 * expire is on the closest next tick and delayed_work users depend 1265 * on that there's no such delay when @delay is 0. 1266 */ 1267 if (!delay) { 1268 kthread_insert_work(worker, work, &worker->work_list); 1269 return; 1270 } 1271 1272 /* Be paranoid and try to detect possible races already now. */ 1273 kthread_insert_work_sanity_check(worker, work); 1274 1275 list_add(&work->node, &worker->delayed_work_list); 1276 work->worker = worker; 1277 timer->expires = jiffies + delay; 1278 add_timer(timer); 1279 } 1280 1281 /** 1282 * kthread_queue_delayed_work - queue the associated kthread work 1283 * after a delay. 1284 * @worker: target kthread_worker 1285 * @dwork: kthread_delayed_work to queue 1286 * @delay: number of jiffies to wait before queuing 1287 * 1288 * If the work has not been pending it starts a timer that will queue 1289 * the work after the given @delay. If @delay is zero, it queues the 1290 * work immediately. 1291 * 1292 * Return: %false if the @work has already been pending. It means that 1293 * either the timer was running or the work was queued. It returns %true 1294 * otherwise. 1295 */ 1296 bool kthread_queue_delayed_work(struct kthread_worker *worker, 1297 struct kthread_delayed_work *dwork, 1298 unsigned long delay) 1299 { 1300 struct kthread_work *work = &dwork->work; 1301 unsigned long flags; 1302 bool ret = false; 1303 1304 raw_spin_lock_irqsave(&worker->lock, flags); 1305 1306 if (!queuing_blocked(worker, work)) { 1307 __kthread_queue_delayed_work(worker, dwork, delay); 1308 ret = true; 1309 } 1310 1311 raw_spin_unlock_irqrestore(&worker->lock, flags); 1312 return ret; 1313 } 1314 EXPORT_SYMBOL_GPL(kthread_queue_delayed_work); 1315 1316 struct kthread_flush_work { 1317 struct kthread_work work; 1318 struct completion done; 1319 }; 1320 1321 static void kthread_flush_work_fn(struct kthread_work *work) 1322 { 1323 struct kthread_flush_work *fwork = 1324 container_of(work, struct kthread_flush_work, work); 1325 complete(&fwork->done); 1326 } 1327 1328 /** 1329 * kthread_flush_work - flush a kthread_work 1330 * @work: work to flush 1331 * 1332 * If @work is queued or executing, wait for it to finish execution. 1333 */ 1334 void kthread_flush_work(struct kthread_work *work) 1335 { 1336 struct kthread_flush_work fwork = { 1337 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn), 1338 COMPLETION_INITIALIZER_ONSTACK(fwork.done), 1339 }; 1340 struct kthread_worker *worker; 1341 bool noop = false; 1342 1343 worker = work->worker; 1344 if (!worker) 1345 return; 1346 1347 raw_spin_lock_irq(&worker->lock); 1348 /* Work must not be used with >1 worker, see kthread_queue_work(). */ 1349 WARN_ON_ONCE(work->worker != worker); 1350 1351 if (!list_empty(&work->node)) 1352 kthread_insert_work(worker, &fwork.work, work->node.next); 1353 else if (worker->current_work == work) 1354 kthread_insert_work(worker, &fwork.work, 1355 worker->work_list.next); 1356 else 1357 noop = true; 1358 1359 raw_spin_unlock_irq(&worker->lock); 1360 1361 if (!noop) 1362 wait_for_completion(&fwork.done); 1363 } 1364 EXPORT_SYMBOL_GPL(kthread_flush_work); 1365 1366 /* 1367 * Make sure that the timer is neither set nor running and could 1368 * not manipulate the work list_head any longer. 1369 * 1370 * The function is called under worker->lock. The lock is temporary 1371 * released but the timer can't be set again in the meantime. 1372 */ 1373 static void kthread_cancel_delayed_work_timer(struct kthread_work *work, 1374 unsigned long *flags) 1375 { 1376 struct kthread_delayed_work *dwork = 1377 container_of(work, struct kthread_delayed_work, work); 1378 struct kthread_worker *worker = work->worker; 1379 1380 /* 1381 * timer_delete_sync() must be called to make sure that the timer 1382 * callback is not running. The lock must be temporary released 1383 * to avoid a deadlock with the callback. In the meantime, 1384 * any queuing is blocked by setting the canceling counter. 1385 */ 1386 work->canceling++; 1387 raw_spin_unlock_irqrestore(&worker->lock, *flags); 1388 timer_delete_sync(&dwork->timer); 1389 raw_spin_lock_irqsave(&worker->lock, *flags); 1390 work->canceling--; 1391 } 1392 1393 /* 1394 * This function removes the work from the worker queue. 1395 * 1396 * It is called under worker->lock. The caller must make sure that 1397 * the timer used by delayed work is not running, e.g. by calling 1398 * kthread_cancel_delayed_work_timer(). 1399 * 1400 * The work might still be in use when this function finishes. See the 1401 * current_work proceed by the worker. 1402 * 1403 * Return: %true if @work was pending and successfully canceled, 1404 * %false if @work was not pending 1405 */ 1406 static bool __kthread_cancel_work(struct kthread_work *work) 1407 { 1408 /* 1409 * Try to remove the work from a worker list. It might either 1410 * be from worker->work_list or from worker->delayed_work_list. 1411 */ 1412 if (!list_empty(&work->node)) { 1413 list_del_init(&work->node); 1414 return true; 1415 } 1416 1417 return false; 1418 } 1419 1420 /** 1421 * kthread_mod_delayed_work - modify delay of or queue a kthread delayed work 1422 * @worker: kthread worker to use 1423 * @dwork: kthread delayed work to queue 1424 * @delay: number of jiffies to wait before queuing 1425 * 1426 * If @dwork is idle, equivalent to kthread_queue_delayed_work(). Otherwise, 1427 * modify @dwork's timer so that it expires after @delay. If @delay is zero, 1428 * @work is guaranteed to be queued immediately. 1429 * 1430 * Return: %false if @dwork was idle and queued, %true otherwise. 1431 * 1432 * A special case is when the work is being canceled in parallel. 1433 * It might be caused either by the real kthread_cancel_delayed_work_sync() 1434 * or yet another kthread_mod_delayed_work() call. We let the other command 1435 * win and return %true here. The return value can be used for reference 1436 * counting and the number of queued works stays the same. Anyway, the caller 1437 * is supposed to synchronize these operations a reasonable way. 1438 * 1439 * This function is safe to call from any context including IRQ handler. 1440 * See __kthread_cancel_work() and kthread_delayed_work_timer_fn() 1441 * for details. 1442 */ 1443 bool kthread_mod_delayed_work(struct kthread_worker *worker, 1444 struct kthread_delayed_work *dwork, 1445 unsigned long delay) 1446 { 1447 struct kthread_work *work = &dwork->work; 1448 unsigned long flags; 1449 int ret; 1450 1451 raw_spin_lock_irqsave(&worker->lock, flags); 1452 1453 /* Do not bother with canceling when never queued. */ 1454 if (!work->worker) { 1455 ret = false; 1456 goto fast_queue; 1457 } 1458 1459 /* Work must not be used with >1 worker, see kthread_queue_work() */ 1460 WARN_ON_ONCE(work->worker != worker); 1461 1462 /* 1463 * Temporary cancel the work but do not fight with another command 1464 * that is canceling the work as well. 1465 * 1466 * It is a bit tricky because of possible races with another 1467 * mod_delayed_work() and cancel_delayed_work() callers. 1468 * 1469 * The timer must be canceled first because worker->lock is released 1470 * when doing so. But the work can be removed from the queue (list) 1471 * only when it can be queued again so that the return value can 1472 * be used for reference counting. 1473 */ 1474 kthread_cancel_delayed_work_timer(work, &flags); 1475 if (work->canceling) { 1476 /* The number of works in the queue does not change. */ 1477 ret = true; 1478 goto out; 1479 } 1480 ret = __kthread_cancel_work(work); 1481 1482 fast_queue: 1483 __kthread_queue_delayed_work(worker, dwork, delay); 1484 out: 1485 raw_spin_unlock_irqrestore(&worker->lock, flags); 1486 return ret; 1487 } 1488 EXPORT_SYMBOL_GPL(kthread_mod_delayed_work); 1489 1490 static bool __kthread_cancel_work_sync(struct kthread_work *work, bool is_dwork) 1491 { 1492 struct kthread_worker *worker = work->worker; 1493 unsigned long flags; 1494 int ret = false; 1495 1496 if (!worker) 1497 goto out; 1498 1499 raw_spin_lock_irqsave(&worker->lock, flags); 1500 /* Work must not be used with >1 worker, see kthread_queue_work(). */ 1501 WARN_ON_ONCE(work->worker != worker); 1502 1503 if (is_dwork) 1504 kthread_cancel_delayed_work_timer(work, &flags); 1505 1506 ret = __kthread_cancel_work(work); 1507 1508 if (worker->current_work != work) 1509 goto out_fast; 1510 1511 /* 1512 * The work is in progress and we need to wait with the lock released. 1513 * In the meantime, block any queuing by setting the canceling counter. 1514 */ 1515 work->canceling++; 1516 raw_spin_unlock_irqrestore(&worker->lock, flags); 1517 kthread_flush_work(work); 1518 raw_spin_lock_irqsave(&worker->lock, flags); 1519 work->canceling--; 1520 1521 out_fast: 1522 raw_spin_unlock_irqrestore(&worker->lock, flags); 1523 out: 1524 return ret; 1525 } 1526 1527 /** 1528 * kthread_cancel_work_sync - cancel a kthread work and wait for it to finish 1529 * @work: the kthread work to cancel 1530 * 1531 * Cancel @work and wait for its execution to finish. This function 1532 * can be used even if the work re-queues itself. On return from this 1533 * function, @work is guaranteed to be not pending or executing on any CPU. 1534 * 1535 * kthread_cancel_work_sync(&delayed_work->work) must not be used for 1536 * delayed_work's. Use kthread_cancel_delayed_work_sync() instead. 1537 * 1538 * The caller must ensure that the worker on which @work was last 1539 * queued can't be destroyed before this function returns. 1540 * 1541 * Return: %true if @work was pending, %false otherwise. 1542 */ 1543 bool kthread_cancel_work_sync(struct kthread_work *work) 1544 { 1545 return __kthread_cancel_work_sync(work, false); 1546 } 1547 EXPORT_SYMBOL_GPL(kthread_cancel_work_sync); 1548 1549 /** 1550 * kthread_cancel_delayed_work_sync - cancel a kthread delayed work and 1551 * wait for it to finish. 1552 * @dwork: the kthread delayed work to cancel 1553 * 1554 * This is kthread_cancel_work_sync() for delayed works. 1555 * 1556 * Return: %true if @dwork was pending, %false otherwise. 1557 */ 1558 bool kthread_cancel_delayed_work_sync(struct kthread_delayed_work *dwork) 1559 { 1560 return __kthread_cancel_work_sync(&dwork->work, true); 1561 } 1562 EXPORT_SYMBOL_GPL(kthread_cancel_delayed_work_sync); 1563 1564 /** 1565 * kthread_flush_worker - flush all current works on a kthread_worker 1566 * @worker: worker to flush 1567 * 1568 * Wait until all currently executing or pending works on @worker are 1569 * finished. 1570 */ 1571 void kthread_flush_worker(struct kthread_worker *worker) 1572 { 1573 struct kthread_flush_work fwork = { 1574 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn), 1575 COMPLETION_INITIALIZER_ONSTACK(fwork.done), 1576 }; 1577 1578 kthread_queue_work(worker, &fwork.work); 1579 wait_for_completion(&fwork.done); 1580 } 1581 EXPORT_SYMBOL_GPL(kthread_flush_worker); 1582 1583 /** 1584 * kthread_destroy_worker - destroy a kthread worker 1585 * @worker: worker to be destroyed 1586 * 1587 * Flush and destroy @worker. The simple flush is enough because the kthread 1588 * worker API is used only in trivial scenarios. There are no multi-step state 1589 * machines needed. 1590 * 1591 * Note that this function is not responsible for handling delayed work, so 1592 * caller should be responsible for queuing or canceling all delayed work items 1593 * before invoke this function. 1594 */ 1595 void kthread_destroy_worker(struct kthread_worker *worker) 1596 { 1597 struct task_struct *task; 1598 1599 task = worker->task; 1600 if (WARN_ON(!task)) 1601 return; 1602 1603 kthread_flush_worker(worker); 1604 kthread_stop(task); 1605 WARN_ON(!list_empty(&worker->delayed_work_list)); 1606 WARN_ON(!list_empty(&worker->work_list)); 1607 kfree(worker); 1608 } 1609 EXPORT_SYMBOL(kthread_destroy_worker); 1610 1611 /** 1612 * kthread_use_mm - make the calling kthread operate on an address space 1613 * @mm: address space to operate on 1614 */ 1615 void kthread_use_mm(struct mm_struct *mm) 1616 { 1617 struct mm_struct *active_mm; 1618 struct task_struct *tsk = current; 1619 1620 WARN_ON_ONCE(!(tsk->flags & PF_KTHREAD)); 1621 WARN_ON_ONCE(tsk->mm); 1622 WARN_ON_ONCE(!mm->user_ns); 1623 1624 /* 1625 * It is possible for mm to be the same as tsk->active_mm, but 1626 * we must still mmgrab(mm) and mmdrop_lazy_tlb(active_mm), 1627 * because these references are not equivalent. 1628 */ 1629 mmgrab(mm); 1630 1631 task_lock(tsk); 1632 /* Hold off tlb flush IPIs while switching mm's */ 1633 local_irq_disable(); 1634 active_mm = tsk->active_mm; 1635 tsk->active_mm = mm; 1636 tsk->mm = mm; 1637 membarrier_update_current_mm(mm); 1638 switch_mm_irqs_off(active_mm, mm, tsk); 1639 local_irq_enable(); 1640 task_unlock(tsk); 1641 #ifdef finish_arch_post_lock_switch 1642 finish_arch_post_lock_switch(); 1643 #endif 1644 1645 /* 1646 * When a kthread starts operating on an address space, the loop 1647 * in membarrier_{private,global}_expedited() may not observe 1648 * that tsk->mm, and not issue an IPI. Membarrier requires a 1649 * memory barrier after storing to tsk->mm, before accessing 1650 * user-space memory. A full memory barrier for membarrier 1651 * {PRIVATE,GLOBAL}_EXPEDITED is implicitly provided by 1652 * mmdrop_lazy_tlb(). 1653 */ 1654 mmdrop_lazy_tlb(active_mm); 1655 } 1656 EXPORT_SYMBOL_GPL(kthread_use_mm); 1657 1658 /** 1659 * kthread_unuse_mm - reverse the effect of kthread_use_mm() 1660 * @mm: address space to operate on 1661 */ 1662 void kthread_unuse_mm(struct mm_struct *mm) 1663 { 1664 struct task_struct *tsk = current; 1665 1666 WARN_ON_ONCE(!(tsk->flags & PF_KTHREAD)); 1667 WARN_ON_ONCE(!tsk->mm); 1668 1669 task_lock(tsk); 1670 /* 1671 * When a kthread stops operating on an address space, the loop 1672 * in membarrier_{private,global}_expedited() may not observe 1673 * that tsk->mm, and not issue an IPI. Membarrier requires a 1674 * memory barrier after accessing user-space memory, before 1675 * clearing tsk->mm. 1676 */ 1677 smp_mb__after_spinlock(); 1678 local_irq_disable(); 1679 tsk->mm = NULL; 1680 membarrier_update_current_mm(NULL); 1681 mmgrab_lazy_tlb(mm); 1682 /* active_mm is still 'mm' */ 1683 enter_lazy_tlb(mm, tsk); 1684 local_irq_enable(); 1685 task_unlock(tsk); 1686 1687 mmdrop(mm); 1688 } 1689 EXPORT_SYMBOL_GPL(kthread_unuse_mm); 1690 1691 #ifdef CONFIG_BLK_CGROUP 1692 /** 1693 * kthread_associate_blkcg - associate blkcg to current kthread 1694 * @css: the cgroup info 1695 * 1696 * Current thread must be a kthread. The thread is running jobs on behalf of 1697 * other threads. In some cases, we expect the jobs attach cgroup info of 1698 * original threads instead of that of current thread. This function stores 1699 * original thread's cgroup info in current kthread context for later 1700 * retrieval. 1701 */ 1702 void kthread_associate_blkcg(struct cgroup_subsys_state *css) 1703 { 1704 struct kthread *kthread; 1705 1706 if (!(current->flags & PF_KTHREAD)) 1707 return; 1708 kthread = to_kthread(current); 1709 if (!kthread) 1710 return; 1711 1712 if (kthread->blkcg_css) { 1713 css_put(kthread->blkcg_css); 1714 kthread->blkcg_css = NULL; 1715 } 1716 if (css) { 1717 css_get(css); 1718 kthread->blkcg_css = css; 1719 } 1720 } 1721 EXPORT_SYMBOL(kthread_associate_blkcg); 1722 1723 /** 1724 * kthread_blkcg - get associated blkcg css of current kthread 1725 * 1726 * Current thread must be a kthread. 1727 */ 1728 struct cgroup_subsys_state *kthread_blkcg(void) 1729 { 1730 struct kthread *kthread; 1731 1732 if (current->flags & PF_KTHREAD) { 1733 kthread = to_kthread(current); 1734 if (kthread) 1735 return kthread->blkcg_css; 1736 } 1737 return NULL; 1738 } 1739 #endif 1740