memalloc.c 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /* Copyright (c) 2022 Meta Platforms, Inc. and affiliates. */
  3. #include <linux/mm.h>
  4. #include <linux/llist.h>
  5. #include <linux/bpf.h>
  6. #include <linux/irq_work.h>
  7. #include <linux/bpf_mem_alloc.h>
  8. #include <linux/memcontrol.h>
  9. #include <asm/local.h>
  10. /* Any context (including NMI) BPF specific memory allocator.
  11. *
  12. * Tracing BPF programs can attach to kprobe and fentry. Hence they
  13. * run in unknown context where calling plain kmalloc() might not be safe.
  14. *
  15. * Front-end kmalloc() with per-cpu per-bucket cache of free elements.
  16. * Refill this cache asynchronously from irq_work.
  17. *
  18. * CPU_0 buckets
  19. * 16 32 64 96 128 196 256 512 1024 2048 4096
  20. * ...
  21. * CPU_N buckets
  22. * 16 32 64 96 128 196 256 512 1024 2048 4096
  23. *
  24. * The buckets are prefilled at the start.
  25. * BPF programs always run with migration disabled.
  26. * It's safe to allocate from cache of the current cpu with irqs disabled.
  27. * Free-ing is always done into bucket of the current cpu as well.
  28. * irq_work trims extra free elements from buckets with kfree
  29. * and refills them with kmalloc, so global kmalloc logic takes care
  30. * of freeing objects allocated by one cpu and freed on another.
  31. *
  32. * Every allocated objected is padded with extra 8 bytes that contains
  33. * struct llist_node.
  34. */
  35. #define LLIST_NODE_SZ sizeof(struct llist_node)
  36. #define BPF_MEM_ALLOC_SIZE_MAX 4096
  37. /* similar to kmalloc, but sizeof == 8 bucket is gone */
  38. static u8 size_index[24] __ro_after_init = {
  39. 3, /* 8 */
  40. 3, /* 16 */
  41. 4, /* 24 */
  42. 4, /* 32 */
  43. 5, /* 40 */
  44. 5, /* 48 */
  45. 5, /* 56 */
  46. 5, /* 64 */
  47. 1, /* 72 */
  48. 1, /* 80 */
  49. 1, /* 88 */
  50. 1, /* 96 */
  51. 6, /* 104 */
  52. 6, /* 112 */
  53. 6, /* 120 */
  54. 6, /* 128 */
  55. 2, /* 136 */
  56. 2, /* 144 */
  57. 2, /* 152 */
  58. 2, /* 160 */
  59. 2, /* 168 */
  60. 2, /* 176 */
  61. 2, /* 184 */
  62. 2 /* 192 */
  63. };
  64. static int bpf_mem_cache_idx(size_t size)
  65. {
  66. if (!size || size > BPF_MEM_ALLOC_SIZE_MAX)
  67. return -1;
  68. if (size <= 192)
  69. return size_index[(size - 1) / 8] - 1;
  70. return fls(size - 1) - 2;
  71. }
  72. #define NUM_CACHES 11
  73. struct bpf_mem_cache {
  74. /* per-cpu list of free objects of size 'unit_size'.
  75. * All accesses are done with interrupts disabled and 'active' counter
  76. * protection with __llist_add() and __llist_del_first().
  77. */
  78. struct llist_head free_llist;
  79. local_t active;
  80. /* Operations on the free_list from unit_alloc/unit_free/bpf_mem_refill
  81. * are sequenced by per-cpu 'active' counter. But unit_free() cannot
  82. * fail. When 'active' is busy the unit_free() will add an object to
  83. * free_llist_extra.
  84. */
  85. struct llist_head free_llist_extra;
  86. struct irq_work refill_work;
  87. struct obj_cgroup *objcg;
  88. int unit_size;
  89. /* count of objects in free_llist */
  90. int free_cnt;
  91. int low_watermark, high_watermark, batch;
  92. int percpu_size;
  93. bool draining;
  94. struct bpf_mem_cache *tgt;
  95. /* list of objects to be freed after RCU GP */
  96. struct llist_head free_by_rcu;
  97. struct llist_node *free_by_rcu_tail;
  98. struct llist_head waiting_for_gp;
  99. struct llist_node *waiting_for_gp_tail;
  100. struct rcu_head rcu;
  101. atomic_t call_rcu_in_progress;
  102. struct llist_head free_llist_extra_rcu;
  103. /* list of objects to be freed after RCU tasks trace GP */
  104. struct llist_head free_by_rcu_ttrace;
  105. struct llist_head waiting_for_gp_ttrace;
  106. struct rcu_head rcu_ttrace;
  107. atomic_t call_rcu_ttrace_in_progress;
  108. };
  109. struct bpf_mem_caches {
  110. struct bpf_mem_cache cache[NUM_CACHES];
  111. };
  112. static const u16 sizes[NUM_CACHES] = {96, 192, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096};
  113. static struct llist_node notrace *__llist_del_first(struct llist_head *head)
  114. {
  115. struct llist_node *entry, *next;
  116. entry = head->first;
  117. if (!entry)
  118. return NULL;
  119. next = entry->next;
  120. head->first = next;
  121. return entry;
  122. }
  123. static void *__alloc(struct bpf_mem_cache *c, int node, gfp_t flags)
  124. {
  125. if (c->percpu_size) {
  126. void __percpu **obj = kmalloc_node(c->percpu_size, flags, node);
  127. void __percpu *pptr = __alloc_percpu_gfp(c->unit_size, 8, flags);
  128. if (!obj || !pptr) {
  129. free_percpu(pptr);
  130. kfree(obj);
  131. return NULL;
  132. }
  133. obj[1] = pptr;
  134. return obj;
  135. }
  136. return kmalloc_node(c->unit_size, flags | __GFP_ZERO, node);
  137. }
  138. static struct mem_cgroup *get_memcg(const struct bpf_mem_cache *c)
  139. {
  140. #ifdef CONFIG_MEMCG
  141. if (c->objcg)
  142. return get_mem_cgroup_from_objcg(c->objcg);
  143. return root_mem_cgroup;
  144. #else
  145. return NULL;
  146. #endif
  147. }
  148. static void inc_active(struct bpf_mem_cache *c, unsigned long *flags)
  149. {
  150. if (IS_ENABLED(CONFIG_PREEMPT_RT))
  151. /* In RT irq_work runs in per-cpu kthread, so disable
  152. * interrupts to avoid preemption and interrupts and
  153. * reduce the chance of bpf prog executing on this cpu
  154. * when active counter is busy.
  155. */
  156. local_irq_save(*flags);
  157. /* alloc_bulk runs from irq_work which will not preempt a bpf
  158. * program that does unit_alloc/unit_free since IRQs are
  159. * disabled there. There is no race to increment 'active'
  160. * counter. It protects free_llist from corruption in case NMI
  161. * bpf prog preempted this loop.
  162. */
  163. WARN_ON_ONCE(local_inc_return(&c->active) != 1);
  164. }
  165. static void dec_active(struct bpf_mem_cache *c, unsigned long *flags)
  166. {
  167. local_dec(&c->active);
  168. if (IS_ENABLED(CONFIG_PREEMPT_RT))
  169. local_irq_restore(*flags);
  170. }
  171. static void add_obj_to_free_list(struct bpf_mem_cache *c, void *obj)
  172. {
  173. unsigned long flags;
  174. inc_active(c, &flags);
  175. __llist_add(obj, &c->free_llist);
  176. c->free_cnt++;
  177. dec_active(c, &flags);
  178. }
  179. /* Mostly runs from irq_work except __init phase. */
  180. static void alloc_bulk(struct bpf_mem_cache *c, int cnt, int node, bool atomic)
  181. {
  182. struct mem_cgroup *memcg = NULL, *old_memcg;
  183. gfp_t gfp;
  184. void *obj;
  185. int i;
  186. gfp = __GFP_NOWARN | __GFP_ACCOUNT;
  187. gfp |= atomic ? GFP_NOWAIT : GFP_KERNEL;
  188. for (i = 0; i < cnt; i++) {
  189. /*
  190. * For every 'c' llist_del_first(&c->free_by_rcu_ttrace); is
  191. * done only by one CPU == current CPU. Other CPUs might
  192. * llist_add() and llist_del_all() in parallel.
  193. */
  194. obj = llist_del_first(&c->free_by_rcu_ttrace);
  195. if (!obj)
  196. break;
  197. add_obj_to_free_list(c, obj);
  198. }
  199. if (i >= cnt)
  200. return;
  201. for (; i < cnt; i++) {
  202. obj = llist_del_first(&c->waiting_for_gp_ttrace);
  203. if (!obj)
  204. break;
  205. add_obj_to_free_list(c, obj);
  206. }
  207. if (i >= cnt)
  208. return;
  209. memcg = get_memcg(c);
  210. old_memcg = set_active_memcg(memcg);
  211. for (; i < cnt; i++) {
  212. /* Allocate, but don't deplete atomic reserves that typical
  213. * GFP_ATOMIC would do. irq_work runs on this cpu and kmalloc
  214. * will allocate from the current numa node which is what we
  215. * want here.
  216. */
  217. obj = __alloc(c, node, gfp);
  218. if (!obj)
  219. break;
  220. add_obj_to_free_list(c, obj);
  221. }
  222. set_active_memcg(old_memcg);
  223. mem_cgroup_put(memcg);
  224. }
  225. static void free_one(void *obj, bool percpu)
  226. {
  227. if (percpu) {
  228. free_percpu(((void __percpu **)obj)[1]);
  229. kfree(obj);
  230. return;
  231. }
  232. kfree(obj);
  233. }
  234. static int free_all(struct llist_node *llnode, bool percpu)
  235. {
  236. struct llist_node *pos, *t;
  237. int cnt = 0;
  238. llist_for_each_safe(pos, t, llnode) {
  239. free_one(pos, percpu);
  240. cnt++;
  241. }
  242. return cnt;
  243. }
  244. static void __free_rcu(struct rcu_head *head)
  245. {
  246. struct bpf_mem_cache *c = container_of(head, struct bpf_mem_cache, rcu_ttrace);
  247. free_all(llist_del_all(&c->waiting_for_gp_ttrace), !!c->percpu_size);
  248. atomic_set(&c->call_rcu_ttrace_in_progress, 0);
  249. }
  250. static void __free_rcu_tasks_trace(struct rcu_head *head)
  251. {
  252. /* If RCU Tasks Trace grace period implies RCU grace period,
  253. * there is no need to invoke call_rcu().
  254. */
  255. if (rcu_trace_implies_rcu_gp())
  256. __free_rcu(head);
  257. else
  258. call_rcu(head, __free_rcu);
  259. }
  260. static void enque_to_free(struct bpf_mem_cache *c, void *obj)
  261. {
  262. struct llist_node *llnode = obj;
  263. /* bpf_mem_cache is a per-cpu object. Freeing happens in irq_work.
  264. * Nothing races to add to free_by_rcu_ttrace list.
  265. */
  266. llist_add(llnode, &c->free_by_rcu_ttrace);
  267. }
  268. static void do_call_rcu_ttrace(struct bpf_mem_cache *c)
  269. {
  270. struct llist_node *llnode, *t;
  271. if (atomic_xchg(&c->call_rcu_ttrace_in_progress, 1)) {
  272. if (unlikely(READ_ONCE(c->draining))) {
  273. llnode = llist_del_all(&c->free_by_rcu_ttrace);
  274. free_all(llnode, !!c->percpu_size);
  275. }
  276. return;
  277. }
  278. WARN_ON_ONCE(!llist_empty(&c->waiting_for_gp_ttrace));
  279. llist_for_each_safe(llnode, t, llist_del_all(&c->free_by_rcu_ttrace))
  280. llist_add(llnode, &c->waiting_for_gp_ttrace);
  281. if (unlikely(READ_ONCE(c->draining))) {
  282. __free_rcu(&c->rcu_ttrace);
  283. return;
  284. }
  285. /* Use call_rcu_tasks_trace() to wait for sleepable progs to finish.
  286. * If RCU Tasks Trace grace period implies RCU grace period, free
  287. * these elements directly, else use call_rcu() to wait for normal
  288. * progs to finish and finally do free_one() on each element.
  289. */
  290. call_rcu_tasks_trace(&c->rcu_ttrace, __free_rcu_tasks_trace);
  291. }
  292. static void free_bulk(struct bpf_mem_cache *c)
  293. {
  294. struct bpf_mem_cache *tgt = c->tgt;
  295. struct llist_node *llnode, *t;
  296. unsigned long flags;
  297. int cnt;
  298. WARN_ON_ONCE(tgt->unit_size != c->unit_size);
  299. WARN_ON_ONCE(tgt->percpu_size != c->percpu_size);
  300. do {
  301. inc_active(c, &flags);
  302. llnode = __llist_del_first(&c->free_llist);
  303. if (llnode)
  304. cnt = --c->free_cnt;
  305. else
  306. cnt = 0;
  307. dec_active(c, &flags);
  308. if (llnode)
  309. enque_to_free(tgt, llnode);
  310. } while (cnt > (c->high_watermark + c->low_watermark) / 2);
  311. /* and drain free_llist_extra */
  312. llist_for_each_safe(llnode, t, llist_del_all(&c->free_llist_extra))
  313. enque_to_free(tgt, llnode);
  314. do_call_rcu_ttrace(tgt);
  315. }
  316. static void __free_by_rcu(struct rcu_head *head)
  317. {
  318. struct bpf_mem_cache *c = container_of(head, struct bpf_mem_cache, rcu);
  319. struct bpf_mem_cache *tgt = c->tgt;
  320. struct llist_node *llnode;
  321. WARN_ON_ONCE(tgt->unit_size != c->unit_size);
  322. WARN_ON_ONCE(tgt->percpu_size != c->percpu_size);
  323. llnode = llist_del_all(&c->waiting_for_gp);
  324. if (!llnode)
  325. goto out;
  326. llist_add_batch(llnode, c->waiting_for_gp_tail, &tgt->free_by_rcu_ttrace);
  327. /* Objects went through regular RCU GP. Send them to RCU tasks trace */
  328. do_call_rcu_ttrace(tgt);
  329. out:
  330. atomic_set(&c->call_rcu_in_progress, 0);
  331. }
  332. static void check_free_by_rcu(struct bpf_mem_cache *c)
  333. {
  334. struct llist_node *llnode, *t;
  335. unsigned long flags;
  336. /* drain free_llist_extra_rcu */
  337. if (unlikely(!llist_empty(&c->free_llist_extra_rcu))) {
  338. inc_active(c, &flags);
  339. llist_for_each_safe(llnode, t, llist_del_all(&c->free_llist_extra_rcu))
  340. if (__llist_add(llnode, &c->free_by_rcu))
  341. c->free_by_rcu_tail = llnode;
  342. dec_active(c, &flags);
  343. }
  344. if (llist_empty(&c->free_by_rcu))
  345. return;
  346. if (atomic_xchg(&c->call_rcu_in_progress, 1)) {
  347. /*
  348. * Instead of kmalloc-ing new rcu_head and triggering 10k
  349. * call_rcu() to hit rcutree.qhimark and force RCU to notice
  350. * the overload just ask RCU to hurry up. There could be many
  351. * objects in free_by_rcu list.
  352. * This hint reduces memory consumption for an artificial
  353. * benchmark from 2 Gbyte to 150 Mbyte.
  354. */
  355. rcu_request_urgent_qs_task(current);
  356. return;
  357. }
  358. WARN_ON_ONCE(!llist_empty(&c->waiting_for_gp));
  359. inc_active(c, &flags);
  360. WRITE_ONCE(c->waiting_for_gp.first, __llist_del_all(&c->free_by_rcu));
  361. c->waiting_for_gp_tail = c->free_by_rcu_tail;
  362. dec_active(c, &flags);
  363. if (unlikely(READ_ONCE(c->draining))) {
  364. free_all(llist_del_all(&c->waiting_for_gp), !!c->percpu_size);
  365. atomic_set(&c->call_rcu_in_progress, 0);
  366. } else {
  367. call_rcu_hurry(&c->rcu, __free_by_rcu);
  368. }
  369. }
  370. static void bpf_mem_refill(struct irq_work *work)
  371. {
  372. struct bpf_mem_cache *c = container_of(work, struct bpf_mem_cache, refill_work);
  373. int cnt;
  374. /* Racy access to free_cnt. It doesn't need to be 100% accurate */
  375. cnt = c->free_cnt;
  376. if (cnt < c->low_watermark)
  377. /* irq_work runs on this cpu and kmalloc will allocate
  378. * from the current numa node which is what we want here.
  379. */
  380. alloc_bulk(c, c->batch, NUMA_NO_NODE, true);
  381. else if (cnt > c->high_watermark)
  382. free_bulk(c);
  383. check_free_by_rcu(c);
  384. }
  385. static void notrace irq_work_raise(struct bpf_mem_cache *c)
  386. {
  387. irq_work_queue(&c->refill_work);
  388. }
  389. /* For typical bpf map case that uses bpf_mem_cache_alloc and single bucket
  390. * the freelist cache will be elem_size * 64 (or less) on each cpu.
  391. *
  392. * For bpf programs that don't have statically known allocation sizes and
  393. * assuming (low_mark + high_mark) / 2 as an average number of elements per
  394. * bucket and all buckets are used the total amount of memory in freelists
  395. * on each cpu will be:
  396. * 64*16 + 64*32 + 64*64 + 64*96 + 64*128 + 64*196 + 64*256 + 32*512 + 16*1024 + 8*2048 + 4*4096
  397. * == ~ 116 Kbyte using below heuristic.
  398. * Initialized, but unused bpf allocator (not bpf map specific one) will
  399. * consume ~ 11 Kbyte per cpu.
  400. * Typical case will be between 11K and 116K closer to 11K.
  401. * bpf progs can and should share bpf_mem_cache when possible.
  402. *
  403. * Percpu allocation is typically rare. To avoid potential unnecessary large
  404. * memory consumption, set low_mark = 1 and high_mark = 3, resulting in c->batch = 1.
  405. */
  406. static void init_refill_work(struct bpf_mem_cache *c)
  407. {
  408. init_irq_work(&c->refill_work, bpf_mem_refill);
  409. if (c->percpu_size) {
  410. c->low_watermark = 1;
  411. c->high_watermark = 3;
  412. } else if (c->unit_size <= 256) {
  413. c->low_watermark = 32;
  414. c->high_watermark = 96;
  415. } else {
  416. /* When page_size == 4k, order-0 cache will have low_mark == 2
  417. * and high_mark == 6 with batch alloc of 3 individual pages at
  418. * a time.
  419. * 8k allocs and above low == 1, high == 3, batch == 1.
  420. */
  421. c->low_watermark = max(32 * 256 / c->unit_size, 1);
  422. c->high_watermark = max(96 * 256 / c->unit_size, 3);
  423. }
  424. c->batch = max((c->high_watermark - c->low_watermark) / 4 * 3, 1);
  425. }
  426. static void prefill_mem_cache(struct bpf_mem_cache *c, int cpu)
  427. {
  428. int cnt = 1;
  429. /* To avoid consuming memory, for non-percpu allocation, assume that
  430. * 1st run of bpf prog won't be doing more than 4 map_update_elem from
  431. * irq disabled region if unit size is less than or equal to 256.
  432. * For all other cases, let us just do one allocation.
  433. */
  434. if (!c->percpu_size && c->unit_size <= 256)
  435. cnt = 4;
  436. alloc_bulk(c, cnt, cpu_to_node(cpu), false);
  437. }
  438. /* When size != 0 bpf_mem_cache for each cpu.
  439. * This is typical bpf hash map use case when all elements have equal size.
  440. *
  441. * When size == 0 allocate 11 bpf_mem_cache-s for each cpu, then rely on
  442. * kmalloc/kfree. Max allocation size is 4096 in this case.
  443. * This is bpf_dynptr and bpf_kptr use case.
  444. */
  445. int bpf_mem_alloc_init(struct bpf_mem_alloc *ma, int size, bool percpu)
  446. {
  447. struct bpf_mem_caches *cc; struct bpf_mem_caches __percpu *pcc;
  448. struct bpf_mem_cache *c; struct bpf_mem_cache __percpu *pc;
  449. struct obj_cgroup *objcg = NULL;
  450. int cpu, i, unit_size, percpu_size = 0;
  451. if (percpu && size == 0)
  452. return -EINVAL;
  453. /* room for llist_node and per-cpu pointer */
  454. if (percpu)
  455. percpu_size = LLIST_NODE_SZ + sizeof(void *);
  456. ma->percpu = percpu;
  457. if (size) {
  458. pc = __alloc_percpu_gfp(sizeof(*pc), 8, GFP_KERNEL);
  459. if (!pc)
  460. return -ENOMEM;
  461. if (!percpu)
  462. size += LLIST_NODE_SZ; /* room for llist_node */
  463. unit_size = size;
  464. #ifdef CONFIG_MEMCG
  465. if (memcg_bpf_enabled())
  466. objcg = get_obj_cgroup_from_current();
  467. #endif
  468. ma->objcg = objcg;
  469. for_each_possible_cpu(cpu) {
  470. c = per_cpu_ptr(pc, cpu);
  471. c->unit_size = unit_size;
  472. c->objcg = objcg;
  473. c->percpu_size = percpu_size;
  474. c->tgt = c;
  475. init_refill_work(c);
  476. prefill_mem_cache(c, cpu);
  477. }
  478. ma->cache = pc;
  479. return 0;
  480. }
  481. pcc = __alloc_percpu_gfp(sizeof(*cc), 8, GFP_KERNEL);
  482. if (!pcc)
  483. return -ENOMEM;
  484. #ifdef CONFIG_MEMCG
  485. objcg = get_obj_cgroup_from_current();
  486. #endif
  487. ma->objcg = objcg;
  488. for_each_possible_cpu(cpu) {
  489. cc = per_cpu_ptr(pcc, cpu);
  490. for (i = 0; i < NUM_CACHES; i++) {
  491. c = &cc->cache[i];
  492. c->unit_size = sizes[i];
  493. c->objcg = objcg;
  494. c->percpu_size = percpu_size;
  495. c->tgt = c;
  496. init_refill_work(c);
  497. prefill_mem_cache(c, cpu);
  498. }
  499. }
  500. ma->caches = pcc;
  501. return 0;
  502. }
  503. int bpf_mem_alloc_percpu_init(struct bpf_mem_alloc *ma, struct obj_cgroup *objcg)
  504. {
  505. struct bpf_mem_caches __percpu *pcc;
  506. pcc = __alloc_percpu_gfp(sizeof(struct bpf_mem_caches), 8, GFP_KERNEL);
  507. if (!pcc)
  508. return -ENOMEM;
  509. ma->caches = pcc;
  510. ma->objcg = objcg;
  511. ma->percpu = true;
  512. return 0;
  513. }
  514. int bpf_mem_alloc_percpu_unit_init(struct bpf_mem_alloc *ma, int size)
  515. {
  516. struct bpf_mem_caches *cc; struct bpf_mem_caches __percpu *pcc;
  517. int cpu, i, unit_size, percpu_size;
  518. struct obj_cgroup *objcg;
  519. struct bpf_mem_cache *c;
  520. i = bpf_mem_cache_idx(size);
  521. if (i < 0)
  522. return -EINVAL;
  523. /* room for llist_node and per-cpu pointer */
  524. percpu_size = LLIST_NODE_SZ + sizeof(void *);
  525. unit_size = sizes[i];
  526. objcg = ma->objcg;
  527. pcc = ma->caches;
  528. for_each_possible_cpu(cpu) {
  529. cc = per_cpu_ptr(pcc, cpu);
  530. c = &cc->cache[i];
  531. if (c->unit_size)
  532. break;
  533. c->unit_size = unit_size;
  534. c->objcg = objcg;
  535. c->percpu_size = percpu_size;
  536. c->tgt = c;
  537. init_refill_work(c);
  538. prefill_mem_cache(c, cpu);
  539. }
  540. return 0;
  541. }
  542. static void drain_mem_cache(struct bpf_mem_cache *c)
  543. {
  544. bool percpu = !!c->percpu_size;
  545. /* No progs are using this bpf_mem_cache, but htab_map_free() called
  546. * bpf_mem_cache_free() for all remaining elements and they can be in
  547. * free_by_rcu_ttrace or in waiting_for_gp_ttrace lists, so drain those lists now.
  548. *
  549. * Except for waiting_for_gp_ttrace list, there are no concurrent operations
  550. * on these lists, so it is safe to use __llist_del_all().
  551. */
  552. free_all(llist_del_all(&c->free_by_rcu_ttrace), percpu);
  553. free_all(llist_del_all(&c->waiting_for_gp_ttrace), percpu);
  554. free_all(__llist_del_all(&c->free_llist), percpu);
  555. free_all(__llist_del_all(&c->free_llist_extra), percpu);
  556. free_all(__llist_del_all(&c->free_by_rcu), percpu);
  557. free_all(__llist_del_all(&c->free_llist_extra_rcu), percpu);
  558. free_all(llist_del_all(&c->waiting_for_gp), percpu);
  559. }
  560. static void check_mem_cache(struct bpf_mem_cache *c)
  561. {
  562. WARN_ON_ONCE(!llist_empty(&c->free_by_rcu_ttrace));
  563. WARN_ON_ONCE(!llist_empty(&c->waiting_for_gp_ttrace));
  564. WARN_ON_ONCE(!llist_empty(&c->free_llist));
  565. WARN_ON_ONCE(!llist_empty(&c->free_llist_extra));
  566. WARN_ON_ONCE(!llist_empty(&c->free_by_rcu));
  567. WARN_ON_ONCE(!llist_empty(&c->free_llist_extra_rcu));
  568. WARN_ON_ONCE(!llist_empty(&c->waiting_for_gp));
  569. }
  570. static void check_leaked_objs(struct bpf_mem_alloc *ma)
  571. {
  572. struct bpf_mem_caches *cc;
  573. struct bpf_mem_cache *c;
  574. int cpu, i;
  575. if (ma->cache) {
  576. for_each_possible_cpu(cpu) {
  577. c = per_cpu_ptr(ma->cache, cpu);
  578. check_mem_cache(c);
  579. }
  580. }
  581. if (ma->caches) {
  582. for_each_possible_cpu(cpu) {
  583. cc = per_cpu_ptr(ma->caches, cpu);
  584. for (i = 0; i < NUM_CACHES; i++) {
  585. c = &cc->cache[i];
  586. check_mem_cache(c);
  587. }
  588. }
  589. }
  590. }
  591. static void free_mem_alloc_no_barrier(struct bpf_mem_alloc *ma)
  592. {
  593. check_leaked_objs(ma);
  594. free_percpu(ma->cache);
  595. free_percpu(ma->caches);
  596. ma->cache = NULL;
  597. ma->caches = NULL;
  598. }
  599. static void free_mem_alloc(struct bpf_mem_alloc *ma)
  600. {
  601. /* waiting_for_gp[_ttrace] lists were drained, but RCU callbacks
  602. * might still execute. Wait for them.
  603. *
  604. * rcu_barrier_tasks_trace() doesn't imply synchronize_rcu_tasks_trace(),
  605. * but rcu_barrier_tasks_trace() and rcu_barrier() below are only used
  606. * to wait for the pending __free_rcu_tasks_trace() and __free_rcu(),
  607. * so if call_rcu(head, __free_rcu) is skipped due to
  608. * rcu_trace_implies_rcu_gp(), it will be OK to skip rcu_barrier() by
  609. * using rcu_trace_implies_rcu_gp() as well.
  610. */
  611. rcu_barrier(); /* wait for __free_by_rcu */
  612. rcu_barrier_tasks_trace(); /* wait for __free_rcu */
  613. if (!rcu_trace_implies_rcu_gp())
  614. rcu_barrier();
  615. free_mem_alloc_no_barrier(ma);
  616. }
  617. static void free_mem_alloc_deferred(struct work_struct *work)
  618. {
  619. struct bpf_mem_alloc *ma = container_of(work, struct bpf_mem_alloc, work);
  620. free_mem_alloc(ma);
  621. kfree(ma);
  622. }
  623. static void destroy_mem_alloc(struct bpf_mem_alloc *ma, int rcu_in_progress)
  624. {
  625. struct bpf_mem_alloc *copy;
  626. if (!rcu_in_progress) {
  627. /* Fast path. No callbacks are pending, hence no need to do
  628. * rcu_barrier-s.
  629. */
  630. free_mem_alloc_no_barrier(ma);
  631. return;
  632. }
  633. copy = kmemdup(ma, sizeof(*ma), GFP_KERNEL);
  634. if (!copy) {
  635. /* Slow path with inline barrier-s */
  636. free_mem_alloc(ma);
  637. return;
  638. }
  639. /* Defer barriers into worker to let the rest of map memory to be freed */
  640. memset(ma, 0, sizeof(*ma));
  641. INIT_WORK(&copy->work, free_mem_alloc_deferred);
  642. queue_work(system_unbound_wq, &copy->work);
  643. }
  644. void bpf_mem_alloc_destroy(struct bpf_mem_alloc *ma)
  645. {
  646. struct bpf_mem_caches *cc;
  647. struct bpf_mem_cache *c;
  648. int cpu, i, rcu_in_progress;
  649. if (ma->cache) {
  650. rcu_in_progress = 0;
  651. for_each_possible_cpu(cpu) {
  652. c = per_cpu_ptr(ma->cache, cpu);
  653. WRITE_ONCE(c->draining, true);
  654. irq_work_sync(&c->refill_work);
  655. drain_mem_cache(c);
  656. rcu_in_progress += atomic_read(&c->call_rcu_ttrace_in_progress);
  657. rcu_in_progress += atomic_read(&c->call_rcu_in_progress);
  658. }
  659. obj_cgroup_put(ma->objcg);
  660. destroy_mem_alloc(ma, rcu_in_progress);
  661. }
  662. if (ma->caches) {
  663. rcu_in_progress = 0;
  664. for_each_possible_cpu(cpu) {
  665. cc = per_cpu_ptr(ma->caches, cpu);
  666. for (i = 0; i < NUM_CACHES; i++) {
  667. c = &cc->cache[i];
  668. WRITE_ONCE(c->draining, true);
  669. irq_work_sync(&c->refill_work);
  670. drain_mem_cache(c);
  671. rcu_in_progress += atomic_read(&c->call_rcu_ttrace_in_progress);
  672. rcu_in_progress += atomic_read(&c->call_rcu_in_progress);
  673. }
  674. }
  675. obj_cgroup_put(ma->objcg);
  676. destroy_mem_alloc(ma, rcu_in_progress);
  677. }
  678. }
  679. /* notrace is necessary here and in other functions to make sure
  680. * bpf programs cannot attach to them and cause llist corruptions.
  681. */
  682. static void notrace *unit_alloc(struct bpf_mem_cache *c)
  683. {
  684. struct llist_node *llnode = NULL;
  685. unsigned long flags;
  686. int cnt = 0;
  687. /* Disable irqs to prevent the following race for majority of prog types:
  688. * prog_A
  689. * bpf_mem_alloc
  690. * preemption or irq -> prog_B
  691. * bpf_mem_alloc
  692. *
  693. * but prog_B could be a perf_event NMI prog.
  694. * Use per-cpu 'active' counter to order free_list access between
  695. * unit_alloc/unit_free/bpf_mem_refill.
  696. */
  697. local_irq_save(flags);
  698. if (local_inc_return(&c->active) == 1) {
  699. llnode = __llist_del_first(&c->free_llist);
  700. if (llnode) {
  701. cnt = --c->free_cnt;
  702. *(struct bpf_mem_cache **)llnode = c;
  703. }
  704. }
  705. local_dec(&c->active);
  706. WARN_ON(cnt < 0);
  707. if (cnt < c->low_watermark)
  708. irq_work_raise(c);
  709. /* Enable IRQ after the enqueue of irq work completes, so irq work
  710. * will run after IRQ is enabled and free_llist may be refilled by
  711. * irq work before other task preempts current task.
  712. */
  713. local_irq_restore(flags);
  714. return llnode;
  715. }
  716. /* Though 'ptr' object could have been allocated on a different cpu
  717. * add it to the free_llist of the current cpu.
  718. * Let kfree() logic deal with it when it's later called from irq_work.
  719. */
  720. static void notrace unit_free(struct bpf_mem_cache *c, void *ptr)
  721. {
  722. struct llist_node *llnode = ptr - LLIST_NODE_SZ;
  723. unsigned long flags;
  724. int cnt = 0;
  725. BUILD_BUG_ON(LLIST_NODE_SZ > 8);
  726. /*
  727. * Remember bpf_mem_cache that allocated this object.
  728. * The hint is not accurate.
  729. */
  730. c->tgt = *(struct bpf_mem_cache **)llnode;
  731. local_irq_save(flags);
  732. if (local_inc_return(&c->active) == 1) {
  733. __llist_add(llnode, &c->free_llist);
  734. cnt = ++c->free_cnt;
  735. } else {
  736. /* unit_free() cannot fail. Therefore add an object to atomic
  737. * llist. free_bulk() will drain it. Though free_llist_extra is
  738. * a per-cpu list we have to use atomic llist_add here, since
  739. * it also can be interrupted by bpf nmi prog that does another
  740. * unit_free() into the same free_llist_extra.
  741. */
  742. llist_add(llnode, &c->free_llist_extra);
  743. }
  744. local_dec(&c->active);
  745. if (cnt > c->high_watermark)
  746. /* free few objects from current cpu into global kmalloc pool */
  747. irq_work_raise(c);
  748. /* Enable IRQ after irq_work_raise() completes, otherwise when current
  749. * task is preempted by task which does unit_alloc(), unit_alloc() may
  750. * return NULL unexpectedly because irq work is already pending but can
  751. * not been triggered and free_llist can not be refilled timely.
  752. */
  753. local_irq_restore(flags);
  754. }
  755. static void notrace unit_free_rcu(struct bpf_mem_cache *c, void *ptr)
  756. {
  757. struct llist_node *llnode = ptr - LLIST_NODE_SZ;
  758. unsigned long flags;
  759. c->tgt = *(struct bpf_mem_cache **)llnode;
  760. local_irq_save(flags);
  761. if (local_inc_return(&c->active) == 1) {
  762. if (__llist_add(llnode, &c->free_by_rcu))
  763. c->free_by_rcu_tail = llnode;
  764. } else {
  765. llist_add(llnode, &c->free_llist_extra_rcu);
  766. }
  767. local_dec(&c->active);
  768. if (!atomic_read(&c->call_rcu_in_progress))
  769. irq_work_raise(c);
  770. local_irq_restore(flags);
  771. }
  772. /* Called from BPF program or from sys_bpf syscall.
  773. * In both cases migration is disabled.
  774. */
  775. void notrace *bpf_mem_alloc(struct bpf_mem_alloc *ma, size_t size)
  776. {
  777. int idx;
  778. void *ret;
  779. if (!size)
  780. return NULL;
  781. if (!ma->percpu)
  782. size += LLIST_NODE_SZ;
  783. idx = bpf_mem_cache_idx(size);
  784. if (idx < 0)
  785. return NULL;
  786. ret = unit_alloc(this_cpu_ptr(ma->caches)->cache + idx);
  787. return !ret ? NULL : ret + LLIST_NODE_SZ;
  788. }
  789. void notrace bpf_mem_free(struct bpf_mem_alloc *ma, void *ptr)
  790. {
  791. struct bpf_mem_cache *c;
  792. int idx;
  793. if (!ptr)
  794. return;
  795. c = *(void **)(ptr - LLIST_NODE_SZ);
  796. idx = bpf_mem_cache_idx(c->unit_size);
  797. if (WARN_ON_ONCE(idx < 0))
  798. return;
  799. unit_free(this_cpu_ptr(ma->caches)->cache + idx, ptr);
  800. }
  801. void notrace bpf_mem_free_rcu(struct bpf_mem_alloc *ma, void *ptr)
  802. {
  803. struct bpf_mem_cache *c;
  804. int idx;
  805. if (!ptr)
  806. return;
  807. c = *(void **)(ptr - LLIST_NODE_SZ);
  808. idx = bpf_mem_cache_idx(c->unit_size);
  809. if (WARN_ON_ONCE(idx < 0))
  810. return;
  811. unit_free_rcu(this_cpu_ptr(ma->caches)->cache + idx, ptr);
  812. }
  813. void notrace *bpf_mem_cache_alloc(struct bpf_mem_alloc *ma)
  814. {
  815. void *ret;
  816. ret = unit_alloc(this_cpu_ptr(ma->cache));
  817. return !ret ? NULL : ret + LLIST_NODE_SZ;
  818. }
  819. void notrace bpf_mem_cache_free(struct bpf_mem_alloc *ma, void *ptr)
  820. {
  821. if (!ptr)
  822. return;
  823. unit_free(this_cpu_ptr(ma->cache), ptr);
  824. }
  825. void notrace bpf_mem_cache_free_rcu(struct bpf_mem_alloc *ma, void *ptr)
  826. {
  827. if (!ptr)
  828. return;
  829. unit_free_rcu(this_cpu_ptr(ma->cache), ptr);
  830. }
  831. /* Directly does a kfree() without putting 'ptr' back to the free_llist
  832. * for reuse and without waiting for a rcu_tasks_trace gp.
  833. * The caller must first go through the rcu_tasks_trace gp for 'ptr'
  834. * before calling bpf_mem_cache_raw_free().
  835. * It could be used when the rcu_tasks_trace callback does not have
  836. * a hold on the original bpf_mem_alloc object that allocated the
  837. * 'ptr'. This should only be used in the uncommon code path.
  838. * Otherwise, the bpf_mem_alloc's free_llist cannot be refilled
  839. * and may affect performance.
  840. */
  841. void bpf_mem_cache_raw_free(void *ptr)
  842. {
  843. if (!ptr)
  844. return;
  845. kfree(ptr - LLIST_NODE_SZ);
  846. }
  847. /* When flags == GFP_KERNEL, it signals that the caller will not cause
  848. * deadlock when using kmalloc. bpf_mem_cache_alloc_flags() will use
  849. * kmalloc if the free_llist is empty.
  850. */
  851. void notrace *bpf_mem_cache_alloc_flags(struct bpf_mem_alloc *ma, gfp_t flags)
  852. {
  853. struct bpf_mem_cache *c;
  854. void *ret;
  855. c = this_cpu_ptr(ma->cache);
  856. ret = unit_alloc(c);
  857. if (!ret && flags == GFP_KERNEL) {
  858. struct mem_cgroup *memcg, *old_memcg;
  859. memcg = get_memcg(c);
  860. old_memcg = set_active_memcg(memcg);
  861. ret = __alloc(c, NUMA_NO_NODE, GFP_KERNEL | __GFP_NOWARN | __GFP_ACCOUNT);
  862. if (ret)
  863. *(struct bpf_mem_cache **)ret = c;
  864. set_active_memcg(old_memcg);
  865. mem_cgroup_put(memcg);
  866. }
  867. return !ret ? NULL : ret + LLIST_NODE_SZ;
  868. }
  869. int bpf_mem_alloc_check_size(bool percpu, size_t size)
  870. {
  871. /* The size of percpu allocation doesn't have LLIST_NODE_SZ overhead */
  872. if ((percpu && size > BPF_MEM_ALLOC_SIZE_MAX) ||
  873. (!percpu && size > BPF_MEM_ALLOC_SIZE_MAX - LLIST_NODE_SZ))
  874. return -E2BIG;
  875. return 0;
  876. }