percpu_counter.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Fast batching percpu counters.
  4. */
  5. #include <linux/percpu_counter.h>
  6. #include <linux/mutex.h>
  7. #include <linux/init.h>
  8. #include <linux/cpu.h>
  9. #include <linux/module.h>
  10. #include <linux/debugobjects.h>
  11. #ifdef CONFIG_HOTPLUG_CPU
  12. static LIST_HEAD(percpu_counters);
  13. static DEFINE_SPINLOCK(percpu_counters_lock);
  14. #endif
  15. #ifdef CONFIG_DEBUG_OBJECTS_PERCPU_COUNTER
  16. static const struct debug_obj_descr percpu_counter_debug_descr;
  17. static bool percpu_counter_fixup_free(void *addr, enum debug_obj_state state)
  18. {
  19. struct percpu_counter *fbc = addr;
  20. switch (state) {
  21. case ODEBUG_STATE_ACTIVE:
  22. percpu_counter_destroy(fbc);
  23. debug_object_free(fbc, &percpu_counter_debug_descr);
  24. return true;
  25. default:
  26. return false;
  27. }
  28. }
  29. static const struct debug_obj_descr percpu_counter_debug_descr = {
  30. .name = "percpu_counter",
  31. .fixup_free = percpu_counter_fixup_free,
  32. };
  33. static inline void debug_percpu_counter_activate(struct percpu_counter *fbc)
  34. {
  35. debug_object_init(fbc, &percpu_counter_debug_descr);
  36. debug_object_activate(fbc, &percpu_counter_debug_descr);
  37. }
  38. static inline void debug_percpu_counter_deactivate(struct percpu_counter *fbc)
  39. {
  40. debug_object_deactivate(fbc, &percpu_counter_debug_descr);
  41. debug_object_free(fbc, &percpu_counter_debug_descr);
  42. }
  43. #else /* CONFIG_DEBUG_OBJECTS_PERCPU_COUNTER */
  44. static inline void debug_percpu_counter_activate(struct percpu_counter *fbc)
  45. { }
  46. static inline void debug_percpu_counter_deactivate(struct percpu_counter *fbc)
  47. { }
  48. #endif /* CONFIG_DEBUG_OBJECTS_PERCPU_COUNTER */
  49. void percpu_counter_set(struct percpu_counter *fbc, s64 amount)
  50. {
  51. int cpu;
  52. unsigned long flags;
  53. raw_spin_lock_irqsave(&fbc->lock, flags);
  54. for_each_possible_cpu(cpu) {
  55. s32 *pcount = per_cpu_ptr(fbc->counters, cpu);
  56. *pcount = 0;
  57. }
  58. fbc->count = amount;
  59. raw_spin_unlock_irqrestore(&fbc->lock, flags);
  60. }
  61. EXPORT_SYMBOL(percpu_counter_set);
  62. /*
  63. * Add to a counter while respecting batch size.
  64. *
  65. * There are 2 implementations, both dealing with the following problem:
  66. *
  67. * The decision slow path/fast path and the actual update must be atomic.
  68. * Otherwise a call in process context could check the current values and
  69. * decide that the fast path can be used. If now an interrupt occurs before
  70. * the this_cpu_add(), and the interrupt updates this_cpu(*fbc->counters),
  71. * then the this_cpu_add() that is executed after the interrupt has completed
  72. * can produce values larger than "batch" or even overflows.
  73. */
  74. #ifdef CONFIG_HAVE_CMPXCHG_LOCAL
  75. /*
  76. * Safety against interrupts is achieved in 2 ways:
  77. * 1. the fast path uses local cmpxchg (note: no lock prefix)
  78. * 2. the slow path operates with interrupts disabled
  79. */
  80. void percpu_counter_add_batch(struct percpu_counter *fbc, s64 amount, s32 batch)
  81. {
  82. s64 count;
  83. unsigned long flags;
  84. count = this_cpu_read(*fbc->counters);
  85. do {
  86. if (unlikely(abs(count + amount) >= batch)) {
  87. raw_spin_lock_irqsave(&fbc->lock, flags);
  88. /*
  89. * Note: by now we might have migrated to another CPU
  90. * or the value might have changed.
  91. */
  92. count = __this_cpu_read(*fbc->counters);
  93. fbc->count += count + amount;
  94. __this_cpu_sub(*fbc->counters, count);
  95. raw_spin_unlock_irqrestore(&fbc->lock, flags);
  96. return;
  97. }
  98. } while (!this_cpu_try_cmpxchg(*fbc->counters, &count, count + amount));
  99. }
  100. #else
  101. /*
  102. * local_irq_save() is used to make the function irq safe:
  103. * - The slow path would be ok as protected by an irq-safe spinlock.
  104. * - this_cpu_add would be ok as it is irq-safe by definition.
  105. */
  106. void percpu_counter_add_batch(struct percpu_counter *fbc, s64 amount, s32 batch)
  107. {
  108. s64 count;
  109. unsigned long flags;
  110. local_irq_save(flags);
  111. count = __this_cpu_read(*fbc->counters) + amount;
  112. if (abs(count) >= batch) {
  113. raw_spin_lock(&fbc->lock);
  114. fbc->count += count;
  115. __this_cpu_sub(*fbc->counters, count - amount);
  116. raw_spin_unlock(&fbc->lock);
  117. } else {
  118. this_cpu_add(*fbc->counters, amount);
  119. }
  120. local_irq_restore(flags);
  121. }
  122. #endif
  123. EXPORT_SYMBOL(percpu_counter_add_batch);
  124. /*
  125. * For percpu_counter with a big batch, the devication of its count could
  126. * be big, and there is requirement to reduce the deviation, like when the
  127. * counter's batch could be runtime decreased to get a better accuracy,
  128. * which can be achieved by running this sync function on each CPU.
  129. */
  130. void percpu_counter_sync(struct percpu_counter *fbc)
  131. {
  132. unsigned long flags;
  133. s64 count;
  134. raw_spin_lock_irqsave(&fbc->lock, flags);
  135. count = __this_cpu_read(*fbc->counters);
  136. fbc->count += count;
  137. __this_cpu_sub(*fbc->counters, count);
  138. raw_spin_unlock_irqrestore(&fbc->lock, flags);
  139. }
  140. EXPORT_SYMBOL(percpu_counter_sync);
  141. /*
  142. * Add up all the per-cpu counts, return the result. This is a more accurate
  143. * but much slower version of percpu_counter_read_positive().
  144. *
  145. * We use the cpu mask of (cpu_online_mask | cpu_dying_mask) to capture sums
  146. * from CPUs that are in the process of being taken offline. Dying cpus have
  147. * been removed from the online mask, but may not have had the hotplug dead
  148. * notifier called to fold the percpu count back into the global counter sum.
  149. * By including dying CPUs in the iteration mask, we avoid this race condition
  150. * so __percpu_counter_sum() just does the right thing when CPUs are being taken
  151. * offline.
  152. */
  153. s64 __percpu_counter_sum(struct percpu_counter *fbc)
  154. {
  155. s64 ret;
  156. int cpu;
  157. unsigned long flags;
  158. raw_spin_lock_irqsave(&fbc->lock, flags);
  159. ret = fbc->count;
  160. for_each_cpu_or(cpu, cpu_online_mask, cpu_dying_mask) {
  161. s32 *pcount = per_cpu_ptr(fbc->counters, cpu);
  162. ret += *pcount;
  163. }
  164. raw_spin_unlock_irqrestore(&fbc->lock, flags);
  165. return ret;
  166. }
  167. EXPORT_SYMBOL(__percpu_counter_sum);
  168. int __percpu_counter_init_many(struct percpu_counter *fbc, s64 amount,
  169. gfp_t gfp, u32 nr_counters,
  170. struct lock_class_key *key)
  171. {
  172. unsigned long flags __maybe_unused;
  173. size_t counter_size;
  174. s32 __percpu *counters;
  175. u32 i;
  176. counter_size = ALIGN(sizeof(*counters), __alignof__(*counters));
  177. counters = __alloc_percpu_gfp(nr_counters * counter_size,
  178. __alignof__(*counters), gfp);
  179. if (!counters) {
  180. fbc[0].counters = NULL;
  181. return -ENOMEM;
  182. }
  183. for (i = 0; i < nr_counters; i++) {
  184. raw_spin_lock_init(&fbc[i].lock);
  185. lockdep_set_class(&fbc[i].lock, key);
  186. #ifdef CONFIG_HOTPLUG_CPU
  187. INIT_LIST_HEAD(&fbc[i].list);
  188. #endif
  189. fbc[i].count = amount;
  190. fbc[i].counters = (void __percpu *)counters + i * counter_size;
  191. debug_percpu_counter_activate(&fbc[i]);
  192. }
  193. #ifdef CONFIG_HOTPLUG_CPU
  194. spin_lock_irqsave(&percpu_counters_lock, flags);
  195. for (i = 0; i < nr_counters; i++)
  196. list_add(&fbc[i].list, &percpu_counters);
  197. spin_unlock_irqrestore(&percpu_counters_lock, flags);
  198. #endif
  199. return 0;
  200. }
  201. EXPORT_SYMBOL(__percpu_counter_init_many);
  202. void percpu_counter_destroy_many(struct percpu_counter *fbc, u32 nr_counters)
  203. {
  204. unsigned long flags __maybe_unused;
  205. u32 i;
  206. if (WARN_ON_ONCE(!fbc))
  207. return;
  208. if (!fbc[0].counters)
  209. return;
  210. for (i = 0; i < nr_counters; i++)
  211. debug_percpu_counter_deactivate(&fbc[i]);
  212. #ifdef CONFIG_HOTPLUG_CPU
  213. spin_lock_irqsave(&percpu_counters_lock, flags);
  214. for (i = 0; i < nr_counters; i++)
  215. list_del(&fbc[i].list);
  216. spin_unlock_irqrestore(&percpu_counters_lock, flags);
  217. #endif
  218. free_percpu(fbc[0].counters);
  219. for (i = 0; i < nr_counters; i++)
  220. fbc[i].counters = NULL;
  221. }
  222. EXPORT_SYMBOL(percpu_counter_destroy_many);
  223. int percpu_counter_batch __read_mostly = 32;
  224. EXPORT_SYMBOL(percpu_counter_batch);
  225. static int compute_batch_value(unsigned int cpu)
  226. {
  227. int nr = num_online_cpus();
  228. percpu_counter_batch = max(32, nr*2);
  229. return 0;
  230. }
  231. static int percpu_counter_cpu_dead(unsigned int cpu)
  232. {
  233. #ifdef CONFIG_HOTPLUG_CPU
  234. struct percpu_counter *fbc;
  235. compute_batch_value(cpu);
  236. spin_lock_irq(&percpu_counters_lock);
  237. list_for_each_entry(fbc, &percpu_counters, list) {
  238. s32 *pcount;
  239. raw_spin_lock(&fbc->lock);
  240. pcount = per_cpu_ptr(fbc->counters, cpu);
  241. fbc->count += *pcount;
  242. *pcount = 0;
  243. raw_spin_unlock(&fbc->lock);
  244. }
  245. spin_unlock_irq(&percpu_counters_lock);
  246. #endif
  247. return 0;
  248. }
  249. /*
  250. * Compare counter against given value.
  251. * Return 1 if greater, 0 if equal and -1 if less
  252. */
  253. int __percpu_counter_compare(struct percpu_counter *fbc, s64 rhs, s32 batch)
  254. {
  255. s64 count;
  256. count = percpu_counter_read(fbc);
  257. /* Check to see if rough count will be sufficient for comparison */
  258. if (abs(count - rhs) > (batch * num_online_cpus())) {
  259. if (count > rhs)
  260. return 1;
  261. else
  262. return -1;
  263. }
  264. /* Need to use precise count */
  265. count = percpu_counter_sum(fbc);
  266. if (count > rhs)
  267. return 1;
  268. else if (count < rhs)
  269. return -1;
  270. else
  271. return 0;
  272. }
  273. EXPORT_SYMBOL(__percpu_counter_compare);
  274. /*
  275. * Compare counter, and add amount if total is: less than or equal to limit if
  276. * amount is positive, or greater than or equal to limit if amount is negative.
  277. * Return true if amount is added, or false if total would be beyond the limit.
  278. *
  279. * Negative limit is allowed, but unusual.
  280. * When negative amounts (subs) are given to percpu_counter_limited_add(),
  281. * the limit would most naturally be 0 - but other limits are also allowed.
  282. *
  283. * Overflow beyond S64_MAX is not allowed for: counter, limit and amount
  284. * are all assumed to be sane (far from S64_MIN and S64_MAX).
  285. */
  286. bool __percpu_counter_limited_add(struct percpu_counter *fbc,
  287. s64 limit, s64 amount, s32 batch)
  288. {
  289. s64 count;
  290. s64 unknown;
  291. unsigned long flags;
  292. bool good = false;
  293. if (amount == 0)
  294. return true;
  295. local_irq_save(flags);
  296. unknown = batch * num_online_cpus();
  297. count = __this_cpu_read(*fbc->counters);
  298. /* Skip taking the lock when safe */
  299. if (abs(count + amount) <= batch &&
  300. ((amount > 0 && fbc->count + unknown <= limit) ||
  301. (amount < 0 && fbc->count - unknown >= limit))) {
  302. this_cpu_add(*fbc->counters, amount);
  303. local_irq_restore(flags);
  304. return true;
  305. }
  306. raw_spin_lock(&fbc->lock);
  307. count = fbc->count + amount;
  308. /* Skip percpu_counter_sum() when safe */
  309. if (amount > 0) {
  310. if (count - unknown > limit)
  311. goto out;
  312. if (count + unknown <= limit)
  313. good = true;
  314. } else {
  315. if (count + unknown < limit)
  316. goto out;
  317. if (count - unknown >= limit)
  318. good = true;
  319. }
  320. if (!good) {
  321. s32 *pcount;
  322. int cpu;
  323. for_each_cpu_or(cpu, cpu_online_mask, cpu_dying_mask) {
  324. pcount = per_cpu_ptr(fbc->counters, cpu);
  325. count += *pcount;
  326. }
  327. if (amount > 0) {
  328. if (count > limit)
  329. goto out;
  330. } else {
  331. if (count < limit)
  332. goto out;
  333. }
  334. good = true;
  335. }
  336. count = __this_cpu_read(*fbc->counters);
  337. fbc->count += count + amount;
  338. __this_cpu_sub(*fbc->counters, count);
  339. out:
  340. raw_spin_unlock(&fbc->lock);
  341. local_irq_restore(flags);
  342. return good;
  343. }
  344. static int __init percpu_counter_startup(void)
  345. {
  346. int ret;
  347. ret = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "lib/percpu_cnt:online",
  348. compute_batch_value, NULL);
  349. WARN_ON(ret < 0);
  350. ret = cpuhp_setup_state_nocalls(CPUHP_PERCPU_CNT_DEAD,
  351. "lib/percpu_cnt:dead", NULL,
  352. percpu_counter_cpu_dead);
  353. WARN_ON(ret < 0);
  354. return 0;
  355. }
  356. module_init(percpu_counter_startup);