sockmap.c 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440
  1. /* Copyright (c) 2017 Covalent IO, Inc. http://covalent.io
  2. *
  3. * This program is free software; you can redistribute it and/or
  4. * modify it under the terms of version 2 of the GNU General Public
  5. * License as published by the Free Software Foundation.
  6. *
  7. * This program is distributed in the hope that it will be useful, but
  8. * WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. * General Public License for more details.
  11. */
  12. /* A BPF sock_map is used to store sock objects. This is primarly used
  13. * for doing socket redirect with BPF helper routines.
  14. *
  15. * A sock map may have BPF programs attached to it, currently a program
  16. * used to parse packets and a program to provide a verdict and redirect
  17. * decision on the packet are supported. Any programs attached to a sock
  18. * map are inherited by sock objects when they are added to the map. If
  19. * no BPF programs are attached the sock object may only be used for sock
  20. * redirect.
  21. *
  22. * A sock object may be in multiple maps, but can only inherit a single
  23. * parse or verdict program. If adding a sock object to a map would result
  24. * in having multiple parsing programs the update will return an EBUSY error.
  25. *
  26. * For reference this program is similar to devmap used in XDP context
  27. * reviewing these together may be useful. For an example please review
  28. * ./samples/bpf/sockmap/.
  29. */
  30. #include <linux/bpf.h>
  31. #include <net/sock.h>
  32. #include <linux/filter.h>
  33. #include <linux/errno.h>
  34. #include <linux/file.h>
  35. #include <linux/kernel.h>
  36. #include <linux/net.h>
  37. #include <linux/skbuff.h>
  38. #include <linux/workqueue.h>
  39. #include <linux/list.h>
  40. #include <linux/mm.h>
  41. #include <net/strparser.h>
  42. #include <net/tcp.h>
  43. #include <linux/ptr_ring.h>
  44. #include <net/inet_common.h>
  45. #include <linux/sched/signal.h>
  46. #define SOCK_CREATE_FLAG_MASK \
  47. (BPF_F_NUMA_NODE | BPF_F_RDONLY | BPF_F_WRONLY)
  48. struct bpf_sock_progs {
  49. struct bpf_prog *bpf_tx_msg;
  50. struct bpf_prog *bpf_parse;
  51. struct bpf_prog *bpf_verdict;
  52. };
  53. struct bpf_stab {
  54. struct bpf_map map;
  55. struct sock **sock_map;
  56. struct bpf_sock_progs progs;
  57. };
  58. struct bucket {
  59. struct hlist_head head;
  60. raw_spinlock_t lock;
  61. };
  62. struct bpf_htab {
  63. struct bpf_map map;
  64. struct bucket *buckets;
  65. atomic_t count;
  66. u32 n_buckets;
  67. u32 elem_size;
  68. struct bpf_sock_progs progs;
  69. };
  70. struct htab_elem {
  71. struct rcu_head rcu;
  72. struct hlist_node hash_node;
  73. u32 hash;
  74. struct sock *sk;
  75. char key[0];
  76. };
  77. enum smap_psock_state {
  78. SMAP_TX_RUNNING,
  79. };
  80. struct smap_psock_map_entry {
  81. struct list_head list;
  82. struct sock **entry;
  83. struct htab_elem *hash_link;
  84. struct bpf_htab *htab;
  85. };
  86. struct smap_psock {
  87. struct rcu_head rcu;
  88. refcount_t refcnt;
  89. /* datapath variables */
  90. struct sk_buff_head rxqueue;
  91. bool strp_enabled;
  92. /* datapath error path cache across tx work invocations */
  93. int save_rem;
  94. int save_off;
  95. struct sk_buff *save_skb;
  96. /* datapath variables for tx_msg ULP */
  97. struct sock *sk_redir;
  98. int apply_bytes;
  99. int cork_bytes;
  100. int sg_size;
  101. int eval;
  102. struct sk_msg_buff *cork;
  103. struct list_head ingress;
  104. struct strparser strp;
  105. struct bpf_prog *bpf_tx_msg;
  106. struct bpf_prog *bpf_parse;
  107. struct bpf_prog *bpf_verdict;
  108. struct list_head maps;
  109. /* Back reference used when sock callback trigger sockmap operations */
  110. struct sock *sock;
  111. unsigned long state;
  112. struct work_struct tx_work;
  113. struct work_struct gc_work;
  114. struct proto *sk_proto;
  115. void (*save_close)(struct sock *sk, long timeout);
  116. void (*save_data_ready)(struct sock *sk);
  117. void (*save_write_space)(struct sock *sk);
  118. };
  119. static void smap_release_sock(struct smap_psock *psock, struct sock *sock);
  120. static int bpf_tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
  121. int nonblock, int flags, int *addr_len);
  122. static int bpf_tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size);
  123. static int bpf_tcp_sendpage(struct sock *sk, struct page *page,
  124. int offset, size_t size, int flags);
  125. static inline struct smap_psock *smap_psock_sk(const struct sock *sk)
  126. {
  127. return rcu_dereference_sk_user_data(sk);
  128. }
  129. static bool bpf_tcp_stream_read(const struct sock *sk)
  130. {
  131. struct smap_psock *psock;
  132. bool empty = true;
  133. rcu_read_lock();
  134. psock = smap_psock_sk(sk);
  135. if (unlikely(!psock))
  136. goto out;
  137. empty = list_empty(&psock->ingress);
  138. out:
  139. rcu_read_unlock();
  140. return !empty;
  141. }
  142. static struct proto tcp_bpf_proto;
  143. static int bpf_tcp_init(struct sock *sk)
  144. {
  145. struct smap_psock *psock;
  146. rcu_read_lock();
  147. psock = smap_psock_sk(sk);
  148. if (unlikely(!psock)) {
  149. rcu_read_unlock();
  150. return -EINVAL;
  151. }
  152. if (unlikely(psock->sk_proto)) {
  153. rcu_read_unlock();
  154. return -EBUSY;
  155. }
  156. psock->save_close = sk->sk_prot->close;
  157. psock->sk_proto = sk->sk_prot;
  158. if (psock->bpf_tx_msg) {
  159. tcp_bpf_proto.sendmsg = bpf_tcp_sendmsg;
  160. tcp_bpf_proto.sendpage = bpf_tcp_sendpage;
  161. tcp_bpf_proto.recvmsg = bpf_tcp_recvmsg;
  162. tcp_bpf_proto.stream_memory_read = bpf_tcp_stream_read;
  163. }
  164. sk->sk_prot = &tcp_bpf_proto;
  165. rcu_read_unlock();
  166. return 0;
  167. }
  168. static void smap_release_sock(struct smap_psock *psock, struct sock *sock);
  169. static int free_start_sg(struct sock *sk, struct sk_msg_buff *md);
  170. static void bpf_tcp_release(struct sock *sk)
  171. {
  172. struct smap_psock *psock;
  173. rcu_read_lock();
  174. psock = smap_psock_sk(sk);
  175. if (unlikely(!psock))
  176. goto out;
  177. if (psock->cork) {
  178. free_start_sg(psock->sock, psock->cork);
  179. kfree(psock->cork);
  180. psock->cork = NULL;
  181. }
  182. if (psock->sk_proto) {
  183. sk->sk_prot = psock->sk_proto;
  184. psock->sk_proto = NULL;
  185. }
  186. out:
  187. rcu_read_unlock();
  188. }
  189. static void free_htab_elem(struct bpf_htab *htab, struct htab_elem *l)
  190. {
  191. atomic_dec(&htab->count);
  192. kfree_rcu(l, rcu);
  193. }
  194. static void bpf_tcp_close(struct sock *sk, long timeout)
  195. {
  196. void (*close_fun)(struct sock *sk, long timeout);
  197. struct smap_psock_map_entry *e, *tmp;
  198. struct sk_msg_buff *md, *mtmp;
  199. struct smap_psock *psock;
  200. struct sock *osk;
  201. rcu_read_lock();
  202. psock = smap_psock_sk(sk);
  203. if (unlikely(!psock)) {
  204. rcu_read_unlock();
  205. return sk->sk_prot->close(sk, timeout);
  206. }
  207. /* The psock may be destroyed anytime after exiting the RCU critial
  208. * section so by the time we use close_fun the psock may no longer
  209. * be valid. However, bpf_tcp_close is called with the sock lock
  210. * held so the close hook and sk are still valid.
  211. */
  212. close_fun = psock->save_close;
  213. write_lock_bh(&sk->sk_callback_lock);
  214. if (psock->cork) {
  215. free_start_sg(psock->sock, psock->cork);
  216. kfree(psock->cork);
  217. psock->cork = NULL;
  218. }
  219. list_for_each_entry_safe(md, mtmp, &psock->ingress, list) {
  220. list_del(&md->list);
  221. free_start_sg(psock->sock, md);
  222. kfree(md);
  223. }
  224. list_for_each_entry_safe(e, tmp, &psock->maps, list) {
  225. if (e->entry) {
  226. osk = cmpxchg(e->entry, sk, NULL);
  227. if (osk == sk) {
  228. list_del(&e->list);
  229. smap_release_sock(psock, sk);
  230. }
  231. } else {
  232. hlist_del_rcu(&e->hash_link->hash_node);
  233. smap_release_sock(psock, e->hash_link->sk);
  234. free_htab_elem(e->htab, e->hash_link);
  235. }
  236. }
  237. write_unlock_bh(&sk->sk_callback_lock);
  238. rcu_read_unlock();
  239. close_fun(sk, timeout);
  240. }
  241. enum __sk_action {
  242. __SK_DROP = 0,
  243. __SK_PASS,
  244. __SK_REDIRECT,
  245. __SK_NONE,
  246. };
  247. static struct tcp_ulp_ops bpf_tcp_ulp_ops __read_mostly = {
  248. .name = "bpf_tcp",
  249. .uid = TCP_ULP_BPF,
  250. .user_visible = false,
  251. .owner = NULL,
  252. .init = bpf_tcp_init,
  253. .release = bpf_tcp_release,
  254. };
  255. static int memcopy_from_iter(struct sock *sk,
  256. struct sk_msg_buff *md,
  257. struct iov_iter *from, int bytes)
  258. {
  259. struct scatterlist *sg = md->sg_data;
  260. int i = md->sg_curr, rc = -ENOSPC;
  261. do {
  262. int copy;
  263. char *to;
  264. if (md->sg_copybreak >= sg[i].length) {
  265. md->sg_copybreak = 0;
  266. if (++i == MAX_SKB_FRAGS)
  267. i = 0;
  268. if (i == md->sg_end)
  269. break;
  270. }
  271. copy = sg[i].length - md->sg_copybreak;
  272. to = sg_virt(&sg[i]) + md->sg_copybreak;
  273. md->sg_copybreak += copy;
  274. if (sk->sk_route_caps & NETIF_F_NOCACHE_COPY)
  275. rc = copy_from_iter_nocache(to, copy, from);
  276. else
  277. rc = copy_from_iter(to, copy, from);
  278. if (rc != copy) {
  279. rc = -EFAULT;
  280. goto out;
  281. }
  282. bytes -= copy;
  283. if (!bytes)
  284. break;
  285. md->sg_copybreak = 0;
  286. if (++i == MAX_SKB_FRAGS)
  287. i = 0;
  288. } while (i != md->sg_end);
  289. out:
  290. md->sg_curr = i;
  291. return rc;
  292. }
  293. static int bpf_tcp_push(struct sock *sk, int apply_bytes,
  294. struct sk_msg_buff *md,
  295. int flags, bool uncharge)
  296. {
  297. bool apply = apply_bytes;
  298. struct scatterlist *sg;
  299. int offset, ret = 0;
  300. struct page *p;
  301. size_t size;
  302. while (1) {
  303. sg = md->sg_data + md->sg_start;
  304. size = (apply && apply_bytes < sg->length) ?
  305. apply_bytes : sg->length;
  306. offset = sg->offset;
  307. tcp_rate_check_app_limited(sk);
  308. p = sg_page(sg);
  309. retry:
  310. ret = do_tcp_sendpages(sk, p, offset, size, flags);
  311. if (ret != size) {
  312. if (ret > 0) {
  313. if (apply)
  314. apply_bytes -= ret;
  315. sg->offset += ret;
  316. sg->length -= ret;
  317. size -= ret;
  318. offset += ret;
  319. if (uncharge)
  320. sk_mem_uncharge(sk, ret);
  321. goto retry;
  322. }
  323. return ret;
  324. }
  325. if (apply)
  326. apply_bytes -= ret;
  327. sg->offset += ret;
  328. sg->length -= ret;
  329. if (uncharge)
  330. sk_mem_uncharge(sk, ret);
  331. if (!sg->length) {
  332. put_page(p);
  333. md->sg_start++;
  334. if (md->sg_start == MAX_SKB_FRAGS)
  335. md->sg_start = 0;
  336. sg_init_table(sg, 1);
  337. if (md->sg_start == md->sg_end)
  338. break;
  339. }
  340. if (apply && !apply_bytes)
  341. break;
  342. }
  343. return 0;
  344. }
  345. static inline void bpf_compute_data_pointers_sg(struct sk_msg_buff *md)
  346. {
  347. struct scatterlist *sg = md->sg_data + md->sg_start;
  348. if (md->sg_copy[md->sg_start]) {
  349. md->data = md->data_end = 0;
  350. } else {
  351. md->data = sg_virt(sg);
  352. md->data_end = md->data + sg->length;
  353. }
  354. }
  355. static void return_mem_sg(struct sock *sk, int bytes, struct sk_msg_buff *md)
  356. {
  357. struct scatterlist *sg = md->sg_data;
  358. int i = md->sg_start;
  359. do {
  360. int uncharge = (bytes < sg[i].length) ? bytes : sg[i].length;
  361. sk_mem_uncharge(sk, uncharge);
  362. bytes -= uncharge;
  363. if (!bytes)
  364. break;
  365. i++;
  366. if (i == MAX_SKB_FRAGS)
  367. i = 0;
  368. } while (i != md->sg_end);
  369. }
  370. static void free_bytes_sg(struct sock *sk, int bytes,
  371. struct sk_msg_buff *md, bool charge)
  372. {
  373. struct scatterlist *sg = md->sg_data;
  374. int i = md->sg_start, free;
  375. while (bytes && sg[i].length) {
  376. free = sg[i].length;
  377. if (bytes < free) {
  378. sg[i].length -= bytes;
  379. sg[i].offset += bytes;
  380. if (charge)
  381. sk_mem_uncharge(sk, bytes);
  382. break;
  383. }
  384. if (charge)
  385. sk_mem_uncharge(sk, sg[i].length);
  386. put_page(sg_page(&sg[i]));
  387. bytes -= sg[i].length;
  388. sg[i].length = 0;
  389. sg[i].page_link = 0;
  390. sg[i].offset = 0;
  391. i++;
  392. if (i == MAX_SKB_FRAGS)
  393. i = 0;
  394. }
  395. md->sg_start = i;
  396. }
  397. static int free_sg(struct sock *sk, int start, struct sk_msg_buff *md)
  398. {
  399. struct scatterlist *sg = md->sg_data;
  400. int i = start, free = 0;
  401. while (sg[i].length) {
  402. free += sg[i].length;
  403. sk_mem_uncharge(sk, sg[i].length);
  404. put_page(sg_page(&sg[i]));
  405. sg[i].length = 0;
  406. sg[i].page_link = 0;
  407. sg[i].offset = 0;
  408. i++;
  409. if (i == MAX_SKB_FRAGS)
  410. i = 0;
  411. }
  412. return free;
  413. }
  414. static int free_start_sg(struct sock *sk, struct sk_msg_buff *md)
  415. {
  416. int free = free_sg(sk, md->sg_start, md);
  417. md->sg_start = md->sg_end;
  418. return free;
  419. }
  420. static int free_curr_sg(struct sock *sk, struct sk_msg_buff *md)
  421. {
  422. return free_sg(sk, md->sg_curr, md);
  423. }
  424. static int bpf_map_msg_verdict(int _rc, struct sk_msg_buff *md)
  425. {
  426. return ((_rc == SK_PASS) ?
  427. (md->sk_redir ? __SK_REDIRECT : __SK_PASS) :
  428. __SK_DROP);
  429. }
  430. static unsigned int smap_do_tx_msg(struct sock *sk,
  431. struct smap_psock *psock,
  432. struct sk_msg_buff *md)
  433. {
  434. struct bpf_prog *prog;
  435. unsigned int rc, _rc;
  436. preempt_disable();
  437. rcu_read_lock();
  438. /* If the policy was removed mid-send then default to 'accept' */
  439. prog = READ_ONCE(psock->bpf_tx_msg);
  440. if (unlikely(!prog)) {
  441. _rc = SK_PASS;
  442. goto verdict;
  443. }
  444. bpf_compute_data_pointers_sg(md);
  445. md->sk = sk;
  446. rc = (*prog->bpf_func)(md, prog->insnsi);
  447. psock->apply_bytes = md->apply_bytes;
  448. /* Moving return codes from UAPI namespace into internal namespace */
  449. _rc = bpf_map_msg_verdict(rc, md);
  450. /* The psock has a refcount on the sock but not on the map and because
  451. * we need to drop rcu read lock here its possible the map could be
  452. * removed between here and when we need it to execute the sock
  453. * redirect. So do the map lookup now for future use.
  454. */
  455. if (_rc == __SK_REDIRECT) {
  456. if (psock->sk_redir)
  457. sock_put(psock->sk_redir);
  458. psock->sk_redir = do_msg_redirect_map(md);
  459. if (!psock->sk_redir) {
  460. _rc = __SK_DROP;
  461. goto verdict;
  462. }
  463. sock_hold(psock->sk_redir);
  464. }
  465. verdict:
  466. rcu_read_unlock();
  467. preempt_enable();
  468. return _rc;
  469. }
  470. static int bpf_tcp_ingress(struct sock *sk, int apply_bytes,
  471. struct smap_psock *psock,
  472. struct sk_msg_buff *md, int flags)
  473. {
  474. bool apply = apply_bytes;
  475. size_t size, copied = 0;
  476. struct sk_msg_buff *r;
  477. int err = 0, i;
  478. r = kzalloc(sizeof(struct sk_msg_buff), __GFP_NOWARN | GFP_KERNEL);
  479. if (unlikely(!r))
  480. return -ENOMEM;
  481. lock_sock(sk);
  482. r->sg_start = md->sg_start;
  483. i = md->sg_start;
  484. do {
  485. size = (apply && apply_bytes < md->sg_data[i].length) ?
  486. apply_bytes : md->sg_data[i].length;
  487. if (!sk_wmem_schedule(sk, size)) {
  488. if (!copied)
  489. err = -ENOMEM;
  490. break;
  491. }
  492. sk_mem_charge(sk, size);
  493. r->sg_data[i] = md->sg_data[i];
  494. r->sg_data[i].length = size;
  495. md->sg_data[i].length -= size;
  496. md->sg_data[i].offset += size;
  497. copied += size;
  498. if (md->sg_data[i].length) {
  499. get_page(sg_page(&r->sg_data[i]));
  500. r->sg_end = (i + 1) == MAX_SKB_FRAGS ? 0 : i + 1;
  501. } else {
  502. i++;
  503. if (i == MAX_SKB_FRAGS)
  504. i = 0;
  505. r->sg_end = i;
  506. }
  507. if (apply) {
  508. apply_bytes -= size;
  509. if (!apply_bytes)
  510. break;
  511. }
  512. } while (i != md->sg_end);
  513. md->sg_start = i;
  514. if (!err) {
  515. list_add_tail(&r->list, &psock->ingress);
  516. sk->sk_data_ready(sk);
  517. } else {
  518. free_start_sg(sk, r);
  519. kfree(r);
  520. }
  521. release_sock(sk);
  522. return err;
  523. }
  524. static int bpf_tcp_sendmsg_do_redirect(struct sock *sk, int send,
  525. struct sk_msg_buff *md,
  526. int flags)
  527. {
  528. bool ingress = !!(md->flags & BPF_F_INGRESS);
  529. struct smap_psock *psock;
  530. struct scatterlist *sg;
  531. int err = 0;
  532. sg = md->sg_data;
  533. rcu_read_lock();
  534. psock = smap_psock_sk(sk);
  535. if (unlikely(!psock))
  536. goto out_rcu;
  537. if (!refcount_inc_not_zero(&psock->refcnt))
  538. goto out_rcu;
  539. rcu_read_unlock();
  540. if (ingress) {
  541. err = bpf_tcp_ingress(sk, send, psock, md, flags);
  542. } else {
  543. lock_sock(sk);
  544. err = bpf_tcp_push(sk, send, md, flags, false);
  545. release_sock(sk);
  546. }
  547. smap_release_sock(psock, sk);
  548. if (unlikely(err))
  549. goto out;
  550. return 0;
  551. out_rcu:
  552. rcu_read_unlock();
  553. out:
  554. free_bytes_sg(NULL, send, md, false);
  555. return err;
  556. }
  557. static inline void bpf_md_init(struct smap_psock *psock)
  558. {
  559. if (!psock->apply_bytes) {
  560. psock->eval = __SK_NONE;
  561. if (psock->sk_redir) {
  562. sock_put(psock->sk_redir);
  563. psock->sk_redir = NULL;
  564. }
  565. }
  566. }
  567. static void apply_bytes_dec(struct smap_psock *psock, int i)
  568. {
  569. if (psock->apply_bytes) {
  570. if (psock->apply_bytes < i)
  571. psock->apply_bytes = 0;
  572. else
  573. psock->apply_bytes -= i;
  574. }
  575. }
  576. static int bpf_exec_tx_verdict(struct smap_psock *psock,
  577. struct sk_msg_buff *m,
  578. struct sock *sk,
  579. int *copied, int flags)
  580. {
  581. bool cork = false, enospc = (m->sg_start == m->sg_end);
  582. struct sock *redir;
  583. int err = 0;
  584. int send;
  585. more_data:
  586. if (psock->eval == __SK_NONE)
  587. psock->eval = smap_do_tx_msg(sk, psock, m);
  588. if (m->cork_bytes &&
  589. m->cork_bytes > psock->sg_size && !enospc) {
  590. psock->cork_bytes = m->cork_bytes - psock->sg_size;
  591. if (!psock->cork) {
  592. psock->cork = kcalloc(1,
  593. sizeof(struct sk_msg_buff),
  594. GFP_ATOMIC | __GFP_NOWARN);
  595. if (!psock->cork) {
  596. err = -ENOMEM;
  597. goto out_err;
  598. }
  599. }
  600. memcpy(psock->cork, m, sizeof(*m));
  601. goto out_err;
  602. }
  603. send = psock->sg_size;
  604. if (psock->apply_bytes && psock->apply_bytes < send)
  605. send = psock->apply_bytes;
  606. switch (psock->eval) {
  607. case __SK_PASS:
  608. err = bpf_tcp_push(sk, send, m, flags, true);
  609. if (unlikely(err)) {
  610. *copied -= free_start_sg(sk, m);
  611. break;
  612. }
  613. apply_bytes_dec(psock, send);
  614. psock->sg_size -= send;
  615. break;
  616. case __SK_REDIRECT:
  617. redir = psock->sk_redir;
  618. apply_bytes_dec(psock, send);
  619. if (psock->cork) {
  620. cork = true;
  621. psock->cork = NULL;
  622. }
  623. return_mem_sg(sk, send, m);
  624. release_sock(sk);
  625. err = bpf_tcp_sendmsg_do_redirect(redir, send, m, flags);
  626. lock_sock(sk);
  627. if (unlikely(err < 0)) {
  628. free_start_sg(sk, m);
  629. psock->sg_size = 0;
  630. if (!cork)
  631. *copied -= send;
  632. } else {
  633. psock->sg_size -= send;
  634. }
  635. if (cork) {
  636. free_start_sg(sk, m);
  637. psock->sg_size = 0;
  638. kfree(m);
  639. m = NULL;
  640. err = 0;
  641. }
  642. break;
  643. case __SK_DROP:
  644. default:
  645. free_bytes_sg(sk, send, m, true);
  646. apply_bytes_dec(psock, send);
  647. *copied -= send;
  648. psock->sg_size -= send;
  649. err = -EACCES;
  650. break;
  651. }
  652. if (likely(!err)) {
  653. bpf_md_init(psock);
  654. if (m &&
  655. m->sg_data[m->sg_start].page_link &&
  656. m->sg_data[m->sg_start].length)
  657. goto more_data;
  658. }
  659. out_err:
  660. return err;
  661. }
  662. static int bpf_wait_data(struct sock *sk,
  663. struct smap_psock *psk, int flags,
  664. long timeo, int *err)
  665. {
  666. int rc;
  667. DEFINE_WAIT_FUNC(wait, woken_wake_function);
  668. add_wait_queue(sk_sleep(sk), &wait);
  669. sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
  670. rc = sk_wait_event(sk, &timeo,
  671. !list_empty(&psk->ingress) ||
  672. !skb_queue_empty(&sk->sk_receive_queue),
  673. &wait);
  674. sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
  675. remove_wait_queue(sk_sleep(sk), &wait);
  676. return rc;
  677. }
  678. static int bpf_tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
  679. int nonblock, int flags, int *addr_len)
  680. {
  681. struct iov_iter *iter = &msg->msg_iter;
  682. struct smap_psock *psock;
  683. int copied = 0;
  684. if (unlikely(flags & MSG_ERRQUEUE))
  685. return inet_recv_error(sk, msg, len, addr_len);
  686. rcu_read_lock();
  687. psock = smap_psock_sk(sk);
  688. if (unlikely(!psock))
  689. goto out;
  690. if (unlikely(!refcount_inc_not_zero(&psock->refcnt)))
  691. goto out;
  692. rcu_read_unlock();
  693. if (!skb_queue_empty(&sk->sk_receive_queue))
  694. return tcp_recvmsg(sk, msg, len, nonblock, flags, addr_len);
  695. lock_sock(sk);
  696. bytes_ready:
  697. while (copied != len) {
  698. struct scatterlist *sg;
  699. struct sk_msg_buff *md;
  700. int i;
  701. md = list_first_entry_or_null(&psock->ingress,
  702. struct sk_msg_buff, list);
  703. if (unlikely(!md))
  704. break;
  705. i = md->sg_start;
  706. do {
  707. struct page *page;
  708. int n, copy;
  709. sg = &md->sg_data[i];
  710. copy = sg->length;
  711. page = sg_page(sg);
  712. if (copied + copy > len)
  713. copy = len - copied;
  714. n = copy_page_to_iter(page, sg->offset, copy, iter);
  715. if (n != copy) {
  716. md->sg_start = i;
  717. release_sock(sk);
  718. smap_release_sock(psock, sk);
  719. return -EFAULT;
  720. }
  721. copied += copy;
  722. sg->offset += copy;
  723. sg->length -= copy;
  724. sk_mem_uncharge(sk, copy);
  725. if (!sg->length) {
  726. i++;
  727. if (i == MAX_SKB_FRAGS)
  728. i = 0;
  729. if (!md->skb)
  730. put_page(page);
  731. }
  732. if (copied == len)
  733. break;
  734. } while (i != md->sg_end);
  735. md->sg_start = i;
  736. if (!sg->length && md->sg_start == md->sg_end) {
  737. list_del(&md->list);
  738. if (md->skb)
  739. consume_skb(md->skb);
  740. kfree(md);
  741. }
  742. }
  743. if (!copied) {
  744. long timeo;
  745. int data;
  746. int err = 0;
  747. timeo = sock_rcvtimeo(sk, nonblock);
  748. data = bpf_wait_data(sk, psock, flags, timeo, &err);
  749. if (data) {
  750. if (!skb_queue_empty(&sk->sk_receive_queue)) {
  751. release_sock(sk);
  752. smap_release_sock(psock, sk);
  753. copied = tcp_recvmsg(sk, msg, len, nonblock, flags, addr_len);
  754. return copied;
  755. }
  756. goto bytes_ready;
  757. }
  758. if (err)
  759. copied = err;
  760. }
  761. release_sock(sk);
  762. smap_release_sock(psock, sk);
  763. return copied;
  764. out:
  765. rcu_read_unlock();
  766. return tcp_recvmsg(sk, msg, len, nonblock, flags, addr_len);
  767. }
  768. static int bpf_tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
  769. {
  770. int flags = msg->msg_flags | MSG_NO_SHARED_FRAGS;
  771. struct sk_msg_buff md = {0};
  772. unsigned int sg_copy = 0;
  773. struct smap_psock *psock;
  774. int copied = 0, err = 0;
  775. struct scatterlist *sg;
  776. long timeo;
  777. /* Its possible a sock event or user removed the psock _but_ the ops
  778. * have not been reprogrammed yet so we get here. In this case fallback
  779. * to tcp_sendmsg. Note this only works because we _only_ ever allow
  780. * a single ULP there is no hierarchy here.
  781. */
  782. rcu_read_lock();
  783. psock = smap_psock_sk(sk);
  784. if (unlikely(!psock)) {
  785. rcu_read_unlock();
  786. return tcp_sendmsg(sk, msg, size);
  787. }
  788. /* Increment the psock refcnt to ensure its not released while sending a
  789. * message. Required because sk lookup and bpf programs are used in
  790. * separate rcu critical sections. Its OK if we lose the map entry
  791. * but we can't lose the sock reference.
  792. */
  793. if (!refcount_inc_not_zero(&psock->refcnt)) {
  794. rcu_read_unlock();
  795. return tcp_sendmsg(sk, msg, size);
  796. }
  797. sg = md.sg_data;
  798. sg_init_marker(sg, MAX_SKB_FRAGS);
  799. rcu_read_unlock();
  800. lock_sock(sk);
  801. timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
  802. while (msg_data_left(msg)) {
  803. struct sk_msg_buff *m;
  804. bool enospc = false;
  805. int copy;
  806. if (sk->sk_err) {
  807. err = sk->sk_err;
  808. goto out_err;
  809. }
  810. copy = msg_data_left(msg);
  811. if (!sk_stream_memory_free(sk))
  812. goto wait_for_sndbuf;
  813. m = psock->cork_bytes ? psock->cork : &md;
  814. m->sg_curr = m->sg_copybreak ? m->sg_curr : m->sg_end;
  815. err = sk_alloc_sg(sk, copy, m->sg_data,
  816. m->sg_start, &m->sg_end, &sg_copy,
  817. m->sg_end - 1);
  818. if (err) {
  819. if (err != -ENOSPC)
  820. goto wait_for_memory;
  821. enospc = true;
  822. copy = sg_copy;
  823. }
  824. err = memcopy_from_iter(sk, m, &msg->msg_iter, copy);
  825. if (err < 0) {
  826. free_curr_sg(sk, m);
  827. goto out_err;
  828. }
  829. psock->sg_size += copy;
  830. copied += copy;
  831. sg_copy = 0;
  832. /* When bytes are being corked skip running BPF program and
  833. * applying verdict unless there is no more buffer space. In
  834. * the ENOSPC case simply run BPF prorgram with currently
  835. * accumulated data. We don't have much choice at this point
  836. * we could try extending the page frags or chaining complex
  837. * frags but even in these cases _eventually_ we will hit an
  838. * OOM scenario. More complex recovery schemes may be
  839. * implemented in the future, but BPF programs must handle
  840. * the case where apply_cork requests are not honored. The
  841. * canonical method to verify this is to check data length.
  842. */
  843. if (psock->cork_bytes) {
  844. if (copy > psock->cork_bytes)
  845. psock->cork_bytes = 0;
  846. else
  847. psock->cork_bytes -= copy;
  848. if (psock->cork_bytes && !enospc)
  849. goto out_cork;
  850. /* All cork bytes accounted for re-run filter */
  851. psock->eval = __SK_NONE;
  852. psock->cork_bytes = 0;
  853. }
  854. err = bpf_exec_tx_verdict(psock, m, sk, &copied, flags);
  855. if (unlikely(err < 0))
  856. goto out_err;
  857. continue;
  858. wait_for_sndbuf:
  859. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  860. wait_for_memory:
  861. err = sk_stream_wait_memory(sk, &timeo);
  862. if (err)
  863. goto out_err;
  864. }
  865. out_err:
  866. if (err < 0)
  867. err = sk_stream_error(sk, msg->msg_flags, err);
  868. out_cork:
  869. release_sock(sk);
  870. smap_release_sock(psock, sk);
  871. return copied ? copied : err;
  872. }
  873. static int bpf_tcp_sendpage(struct sock *sk, struct page *page,
  874. int offset, size_t size, int flags)
  875. {
  876. struct sk_msg_buff md = {0}, *m = NULL;
  877. int err = 0, copied = 0;
  878. struct smap_psock *psock;
  879. struct scatterlist *sg;
  880. bool enospc = false;
  881. rcu_read_lock();
  882. psock = smap_psock_sk(sk);
  883. if (unlikely(!psock))
  884. goto accept;
  885. if (!refcount_inc_not_zero(&psock->refcnt))
  886. goto accept;
  887. rcu_read_unlock();
  888. lock_sock(sk);
  889. if (psock->cork_bytes) {
  890. m = psock->cork;
  891. sg = &m->sg_data[m->sg_end];
  892. } else {
  893. m = &md;
  894. sg = m->sg_data;
  895. sg_init_marker(sg, MAX_SKB_FRAGS);
  896. }
  897. /* Catch case where ring is full and sendpage is stalled. */
  898. if (unlikely(m->sg_end == m->sg_start &&
  899. m->sg_data[m->sg_end].length))
  900. goto out_err;
  901. psock->sg_size += size;
  902. sg_set_page(sg, page, size, offset);
  903. get_page(page);
  904. m->sg_copy[m->sg_end] = true;
  905. sk_mem_charge(sk, size);
  906. m->sg_end++;
  907. copied = size;
  908. if (m->sg_end == MAX_SKB_FRAGS)
  909. m->sg_end = 0;
  910. if (m->sg_end == m->sg_start)
  911. enospc = true;
  912. if (psock->cork_bytes) {
  913. if (size > psock->cork_bytes)
  914. psock->cork_bytes = 0;
  915. else
  916. psock->cork_bytes -= size;
  917. if (psock->cork_bytes && !enospc)
  918. goto out_err;
  919. /* All cork bytes accounted for re-run filter */
  920. psock->eval = __SK_NONE;
  921. psock->cork_bytes = 0;
  922. }
  923. err = bpf_exec_tx_verdict(psock, m, sk, &copied, flags);
  924. out_err:
  925. release_sock(sk);
  926. smap_release_sock(psock, sk);
  927. return copied ? copied : err;
  928. accept:
  929. rcu_read_unlock();
  930. return tcp_sendpage(sk, page, offset, size, flags);
  931. }
  932. static void bpf_tcp_msg_add(struct smap_psock *psock,
  933. struct sock *sk,
  934. struct bpf_prog *tx_msg)
  935. {
  936. struct bpf_prog *orig_tx_msg;
  937. orig_tx_msg = xchg(&psock->bpf_tx_msg, tx_msg);
  938. if (orig_tx_msg)
  939. bpf_prog_put(orig_tx_msg);
  940. }
  941. static int bpf_tcp_ulp_register(void)
  942. {
  943. tcp_bpf_proto = tcp_prot;
  944. tcp_bpf_proto.close = bpf_tcp_close;
  945. /* Once BPF TX ULP is registered it is never unregistered. It
  946. * will be in the ULP list for the lifetime of the system. Doing
  947. * duplicate registers is not a problem.
  948. */
  949. return tcp_register_ulp(&bpf_tcp_ulp_ops);
  950. }
  951. static int smap_verdict_func(struct smap_psock *psock, struct sk_buff *skb)
  952. {
  953. struct bpf_prog *prog = READ_ONCE(psock->bpf_verdict);
  954. int rc;
  955. if (unlikely(!prog))
  956. return __SK_DROP;
  957. skb_orphan(skb);
  958. /* We need to ensure that BPF metadata for maps is also cleared
  959. * when we orphan the skb so that we don't have the possibility
  960. * to reference a stale map.
  961. */
  962. TCP_SKB_CB(skb)->bpf.sk_redir = NULL;
  963. skb->sk = psock->sock;
  964. bpf_compute_data_pointers(skb);
  965. preempt_disable();
  966. rc = (*prog->bpf_func)(skb, prog->insnsi);
  967. preempt_enable();
  968. skb->sk = NULL;
  969. /* Moving return codes from UAPI namespace into internal namespace */
  970. return rc == SK_PASS ?
  971. (TCP_SKB_CB(skb)->bpf.sk_redir ? __SK_REDIRECT : __SK_PASS) :
  972. __SK_DROP;
  973. }
  974. static int smap_do_ingress(struct smap_psock *psock, struct sk_buff *skb)
  975. {
  976. struct sock *sk = psock->sock;
  977. int copied = 0, num_sg;
  978. struct sk_msg_buff *r;
  979. r = kzalloc(sizeof(struct sk_msg_buff), __GFP_NOWARN | GFP_ATOMIC);
  980. if (unlikely(!r))
  981. return -EAGAIN;
  982. if (!sk_rmem_schedule(sk, skb, skb->len)) {
  983. kfree(r);
  984. return -EAGAIN;
  985. }
  986. sg_init_table(r->sg_data, MAX_SKB_FRAGS);
  987. num_sg = skb_to_sgvec(skb, r->sg_data, 0, skb->len);
  988. if (unlikely(num_sg < 0)) {
  989. kfree(r);
  990. return num_sg;
  991. }
  992. sk_mem_charge(sk, skb->len);
  993. copied = skb->len;
  994. r->sg_start = 0;
  995. r->sg_end = num_sg == MAX_SKB_FRAGS ? 0 : num_sg;
  996. r->skb = skb;
  997. list_add_tail(&r->list, &psock->ingress);
  998. sk->sk_data_ready(sk);
  999. return copied;
  1000. }
  1001. static void smap_do_verdict(struct smap_psock *psock, struct sk_buff *skb)
  1002. {
  1003. struct smap_psock *peer;
  1004. struct sock *sk;
  1005. __u32 in;
  1006. int rc;
  1007. rc = smap_verdict_func(psock, skb);
  1008. switch (rc) {
  1009. case __SK_REDIRECT:
  1010. sk = do_sk_redirect_map(skb);
  1011. if (!sk) {
  1012. kfree_skb(skb);
  1013. break;
  1014. }
  1015. peer = smap_psock_sk(sk);
  1016. in = (TCP_SKB_CB(skb)->bpf.flags) & BPF_F_INGRESS;
  1017. if (unlikely(!peer || sock_flag(sk, SOCK_DEAD) ||
  1018. !test_bit(SMAP_TX_RUNNING, &peer->state))) {
  1019. kfree_skb(skb);
  1020. break;
  1021. }
  1022. if (!in && sock_writeable(sk)) {
  1023. skb_set_owner_w(skb, sk);
  1024. skb_queue_tail(&peer->rxqueue, skb);
  1025. schedule_work(&peer->tx_work);
  1026. break;
  1027. } else if (in &&
  1028. atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) {
  1029. skb_queue_tail(&peer->rxqueue, skb);
  1030. schedule_work(&peer->tx_work);
  1031. break;
  1032. }
  1033. /* Fall through and free skb otherwise */
  1034. case __SK_DROP:
  1035. default:
  1036. kfree_skb(skb);
  1037. }
  1038. }
  1039. static void smap_report_sk_error(struct smap_psock *psock, int err)
  1040. {
  1041. struct sock *sk = psock->sock;
  1042. sk->sk_err = err;
  1043. sk->sk_error_report(sk);
  1044. }
  1045. static void smap_read_sock_strparser(struct strparser *strp,
  1046. struct sk_buff *skb)
  1047. {
  1048. struct smap_psock *psock;
  1049. rcu_read_lock();
  1050. psock = container_of(strp, struct smap_psock, strp);
  1051. smap_do_verdict(psock, skb);
  1052. rcu_read_unlock();
  1053. }
  1054. /* Called with lock held on socket */
  1055. static void smap_data_ready(struct sock *sk)
  1056. {
  1057. struct smap_psock *psock;
  1058. rcu_read_lock();
  1059. psock = smap_psock_sk(sk);
  1060. if (likely(psock)) {
  1061. write_lock_bh(&sk->sk_callback_lock);
  1062. strp_data_ready(&psock->strp);
  1063. write_unlock_bh(&sk->sk_callback_lock);
  1064. }
  1065. rcu_read_unlock();
  1066. }
  1067. static void smap_tx_work(struct work_struct *w)
  1068. {
  1069. struct smap_psock *psock;
  1070. struct sk_buff *skb;
  1071. int rem, off, n;
  1072. psock = container_of(w, struct smap_psock, tx_work);
  1073. /* lock sock to avoid losing sk_socket at some point during loop */
  1074. lock_sock(psock->sock);
  1075. if (psock->save_skb) {
  1076. skb = psock->save_skb;
  1077. rem = psock->save_rem;
  1078. off = psock->save_off;
  1079. psock->save_skb = NULL;
  1080. goto start;
  1081. }
  1082. while ((skb = skb_dequeue(&psock->rxqueue))) {
  1083. __u32 flags;
  1084. rem = skb->len;
  1085. off = 0;
  1086. start:
  1087. flags = (TCP_SKB_CB(skb)->bpf.flags) & BPF_F_INGRESS;
  1088. do {
  1089. if (likely(psock->sock->sk_socket)) {
  1090. if (flags)
  1091. n = smap_do_ingress(psock, skb);
  1092. else
  1093. n = skb_send_sock_locked(psock->sock,
  1094. skb, off, rem);
  1095. } else {
  1096. n = -EINVAL;
  1097. }
  1098. if (n <= 0) {
  1099. if (n == -EAGAIN) {
  1100. /* Retry when space is available */
  1101. psock->save_skb = skb;
  1102. psock->save_rem = rem;
  1103. psock->save_off = off;
  1104. goto out;
  1105. }
  1106. /* Hard errors break pipe and stop xmit */
  1107. smap_report_sk_error(psock, n ? -n : EPIPE);
  1108. clear_bit(SMAP_TX_RUNNING, &psock->state);
  1109. kfree_skb(skb);
  1110. goto out;
  1111. }
  1112. rem -= n;
  1113. off += n;
  1114. } while (rem);
  1115. if (!flags)
  1116. kfree_skb(skb);
  1117. }
  1118. out:
  1119. release_sock(psock->sock);
  1120. }
  1121. static void smap_write_space(struct sock *sk)
  1122. {
  1123. struct smap_psock *psock;
  1124. rcu_read_lock();
  1125. psock = smap_psock_sk(sk);
  1126. if (likely(psock && test_bit(SMAP_TX_RUNNING, &psock->state)))
  1127. schedule_work(&psock->tx_work);
  1128. rcu_read_unlock();
  1129. }
  1130. static void smap_stop_sock(struct smap_psock *psock, struct sock *sk)
  1131. {
  1132. if (!psock->strp_enabled)
  1133. return;
  1134. sk->sk_data_ready = psock->save_data_ready;
  1135. sk->sk_write_space = psock->save_write_space;
  1136. psock->save_data_ready = NULL;
  1137. psock->save_write_space = NULL;
  1138. strp_stop(&psock->strp);
  1139. psock->strp_enabled = false;
  1140. }
  1141. static void smap_destroy_psock(struct rcu_head *rcu)
  1142. {
  1143. struct smap_psock *psock = container_of(rcu,
  1144. struct smap_psock, rcu);
  1145. /* Now that a grace period has passed there is no longer
  1146. * any reference to this sock in the sockmap so we can
  1147. * destroy the psock, strparser, and bpf programs. But,
  1148. * because we use workqueue sync operations we can not
  1149. * do it in rcu context
  1150. */
  1151. schedule_work(&psock->gc_work);
  1152. }
  1153. static void smap_release_sock(struct smap_psock *psock, struct sock *sock)
  1154. {
  1155. if (refcount_dec_and_test(&psock->refcnt)) {
  1156. tcp_cleanup_ulp(sock);
  1157. smap_stop_sock(psock, sock);
  1158. clear_bit(SMAP_TX_RUNNING, &psock->state);
  1159. rcu_assign_sk_user_data(sock, NULL);
  1160. call_rcu_sched(&psock->rcu, smap_destroy_psock);
  1161. }
  1162. }
  1163. static int smap_parse_func_strparser(struct strparser *strp,
  1164. struct sk_buff *skb)
  1165. {
  1166. struct smap_psock *psock;
  1167. struct bpf_prog *prog;
  1168. int rc;
  1169. rcu_read_lock();
  1170. psock = container_of(strp, struct smap_psock, strp);
  1171. prog = READ_ONCE(psock->bpf_parse);
  1172. if (unlikely(!prog)) {
  1173. rcu_read_unlock();
  1174. return skb->len;
  1175. }
  1176. /* Attach socket for bpf program to use if needed we can do this
  1177. * because strparser clones the skb before handing it to a upper
  1178. * layer, meaning skb_orphan has been called. We NULL sk on the
  1179. * way out to ensure we don't trigger a BUG_ON in skb/sk operations
  1180. * later and because we are not charging the memory of this skb to
  1181. * any socket yet.
  1182. */
  1183. skb->sk = psock->sock;
  1184. bpf_compute_data_pointers(skb);
  1185. rc = (*prog->bpf_func)(skb, prog->insnsi);
  1186. skb->sk = NULL;
  1187. rcu_read_unlock();
  1188. return rc;
  1189. }
  1190. static int smap_read_sock_done(struct strparser *strp, int err)
  1191. {
  1192. return err;
  1193. }
  1194. static int smap_init_sock(struct smap_psock *psock,
  1195. struct sock *sk)
  1196. {
  1197. static const struct strp_callbacks cb = {
  1198. .rcv_msg = smap_read_sock_strparser,
  1199. .parse_msg = smap_parse_func_strparser,
  1200. .read_sock_done = smap_read_sock_done,
  1201. };
  1202. return strp_init(&psock->strp, sk, &cb);
  1203. }
  1204. static void smap_init_progs(struct smap_psock *psock,
  1205. struct bpf_prog *verdict,
  1206. struct bpf_prog *parse)
  1207. {
  1208. struct bpf_prog *orig_parse, *orig_verdict;
  1209. orig_parse = xchg(&psock->bpf_parse, parse);
  1210. orig_verdict = xchg(&psock->bpf_verdict, verdict);
  1211. if (orig_verdict)
  1212. bpf_prog_put(orig_verdict);
  1213. if (orig_parse)
  1214. bpf_prog_put(orig_parse);
  1215. }
  1216. static void smap_start_sock(struct smap_psock *psock, struct sock *sk)
  1217. {
  1218. if (sk->sk_data_ready == smap_data_ready)
  1219. return;
  1220. psock->save_data_ready = sk->sk_data_ready;
  1221. psock->save_write_space = sk->sk_write_space;
  1222. sk->sk_data_ready = smap_data_ready;
  1223. sk->sk_write_space = smap_write_space;
  1224. psock->strp_enabled = true;
  1225. }
  1226. static void sock_map_remove_complete(struct bpf_stab *stab)
  1227. {
  1228. bpf_map_area_free(stab->sock_map);
  1229. kfree(stab);
  1230. }
  1231. static void smap_gc_work(struct work_struct *w)
  1232. {
  1233. struct smap_psock_map_entry *e, *tmp;
  1234. struct sk_msg_buff *md, *mtmp;
  1235. struct smap_psock *psock;
  1236. psock = container_of(w, struct smap_psock, gc_work);
  1237. /* no callback lock needed because we already detached sockmap ops */
  1238. if (psock->strp_enabled)
  1239. strp_done(&psock->strp);
  1240. cancel_work_sync(&psock->tx_work);
  1241. __skb_queue_purge(&psock->rxqueue);
  1242. /* At this point all strparser and xmit work must be complete */
  1243. if (psock->bpf_parse)
  1244. bpf_prog_put(psock->bpf_parse);
  1245. if (psock->bpf_verdict)
  1246. bpf_prog_put(psock->bpf_verdict);
  1247. if (psock->bpf_tx_msg)
  1248. bpf_prog_put(psock->bpf_tx_msg);
  1249. if (psock->cork) {
  1250. free_start_sg(psock->sock, psock->cork);
  1251. kfree(psock->cork);
  1252. }
  1253. list_for_each_entry_safe(md, mtmp, &psock->ingress, list) {
  1254. list_del(&md->list);
  1255. free_start_sg(psock->sock, md);
  1256. kfree(md);
  1257. }
  1258. list_for_each_entry_safe(e, tmp, &psock->maps, list) {
  1259. list_del(&e->list);
  1260. kfree(e);
  1261. }
  1262. if (psock->sk_redir)
  1263. sock_put(psock->sk_redir);
  1264. sock_put(psock->sock);
  1265. kfree(psock);
  1266. }
  1267. static struct smap_psock *smap_init_psock(struct sock *sock, int node)
  1268. {
  1269. struct smap_psock *psock;
  1270. psock = kzalloc_node(sizeof(struct smap_psock),
  1271. GFP_ATOMIC | __GFP_NOWARN,
  1272. node);
  1273. if (!psock)
  1274. return ERR_PTR(-ENOMEM);
  1275. psock->eval = __SK_NONE;
  1276. psock->sock = sock;
  1277. skb_queue_head_init(&psock->rxqueue);
  1278. INIT_WORK(&psock->tx_work, smap_tx_work);
  1279. INIT_WORK(&psock->gc_work, smap_gc_work);
  1280. INIT_LIST_HEAD(&psock->maps);
  1281. INIT_LIST_HEAD(&psock->ingress);
  1282. refcount_set(&psock->refcnt, 1);
  1283. rcu_assign_sk_user_data(sock, psock);
  1284. sock_hold(sock);
  1285. return psock;
  1286. }
  1287. static struct bpf_map *sock_map_alloc(union bpf_attr *attr)
  1288. {
  1289. struct bpf_stab *stab;
  1290. u64 cost;
  1291. int err;
  1292. if (!capable(CAP_NET_ADMIN))
  1293. return ERR_PTR(-EPERM);
  1294. /* check sanity of attributes */
  1295. if (attr->max_entries == 0 || attr->key_size != 4 ||
  1296. attr->value_size != 4 || attr->map_flags & ~SOCK_CREATE_FLAG_MASK)
  1297. return ERR_PTR(-EINVAL);
  1298. err = bpf_tcp_ulp_register();
  1299. if (err && err != -EEXIST)
  1300. return ERR_PTR(err);
  1301. stab = kzalloc(sizeof(*stab), GFP_USER);
  1302. if (!stab)
  1303. return ERR_PTR(-ENOMEM);
  1304. bpf_map_init_from_attr(&stab->map, attr);
  1305. /* make sure page count doesn't overflow */
  1306. cost = (u64) stab->map.max_entries * sizeof(struct sock *);
  1307. err = -EINVAL;
  1308. if (cost >= U32_MAX - PAGE_SIZE)
  1309. goto free_stab;
  1310. stab->map.pages = round_up(cost, PAGE_SIZE) >> PAGE_SHIFT;
  1311. /* if map size is larger than memlock limit, reject it early */
  1312. err = bpf_map_precharge_memlock(stab->map.pages);
  1313. if (err)
  1314. goto free_stab;
  1315. err = -ENOMEM;
  1316. stab->sock_map = bpf_map_area_alloc(stab->map.max_entries *
  1317. sizeof(struct sock *),
  1318. stab->map.numa_node);
  1319. if (!stab->sock_map)
  1320. goto free_stab;
  1321. return &stab->map;
  1322. free_stab:
  1323. kfree(stab);
  1324. return ERR_PTR(err);
  1325. }
  1326. static void smap_list_remove(struct smap_psock *psock,
  1327. struct sock **entry,
  1328. struct htab_elem *hash_link)
  1329. {
  1330. struct smap_psock_map_entry *e, *tmp;
  1331. list_for_each_entry_safe(e, tmp, &psock->maps, list) {
  1332. if (e->entry == entry || e->hash_link == hash_link) {
  1333. list_del(&e->list);
  1334. break;
  1335. }
  1336. }
  1337. }
  1338. static void sock_map_free(struct bpf_map *map)
  1339. {
  1340. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1341. int i;
  1342. synchronize_rcu();
  1343. /* At this point no update, lookup or delete operations can happen.
  1344. * However, be aware we can still get a socket state event updates,
  1345. * and data ready callabacks that reference the psock from sk_user_data
  1346. * Also psock worker threads are still in-flight. So smap_release_sock
  1347. * will only free the psock after cancel_sync on the worker threads
  1348. * and a grace period expire to ensure psock is really safe to remove.
  1349. */
  1350. rcu_read_lock();
  1351. for (i = 0; i < stab->map.max_entries; i++) {
  1352. struct smap_psock *psock;
  1353. struct sock *sock;
  1354. sock = xchg(&stab->sock_map[i], NULL);
  1355. if (!sock)
  1356. continue;
  1357. write_lock_bh(&sock->sk_callback_lock);
  1358. psock = smap_psock_sk(sock);
  1359. /* This check handles a racing sock event that can get the
  1360. * sk_callback_lock before this case but after xchg happens
  1361. * causing the refcnt to hit zero and sock user data (psock)
  1362. * to be null and queued for garbage collection.
  1363. */
  1364. if (likely(psock)) {
  1365. smap_list_remove(psock, &stab->sock_map[i], NULL);
  1366. smap_release_sock(psock, sock);
  1367. }
  1368. write_unlock_bh(&sock->sk_callback_lock);
  1369. }
  1370. rcu_read_unlock();
  1371. sock_map_remove_complete(stab);
  1372. }
  1373. static int sock_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
  1374. {
  1375. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1376. u32 i = key ? *(u32 *)key : U32_MAX;
  1377. u32 *next = (u32 *)next_key;
  1378. if (i >= stab->map.max_entries) {
  1379. *next = 0;
  1380. return 0;
  1381. }
  1382. if (i == stab->map.max_entries - 1)
  1383. return -ENOENT;
  1384. *next = i + 1;
  1385. return 0;
  1386. }
  1387. struct sock *__sock_map_lookup_elem(struct bpf_map *map, u32 key)
  1388. {
  1389. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1390. if (key >= map->max_entries)
  1391. return NULL;
  1392. return READ_ONCE(stab->sock_map[key]);
  1393. }
  1394. static int sock_map_delete_elem(struct bpf_map *map, void *key)
  1395. {
  1396. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1397. struct smap_psock *psock;
  1398. int k = *(u32 *)key;
  1399. struct sock *sock;
  1400. if (k >= map->max_entries)
  1401. return -EINVAL;
  1402. sock = xchg(&stab->sock_map[k], NULL);
  1403. if (!sock)
  1404. return -EINVAL;
  1405. write_lock_bh(&sock->sk_callback_lock);
  1406. psock = smap_psock_sk(sock);
  1407. if (!psock)
  1408. goto out;
  1409. if (psock->bpf_parse)
  1410. smap_stop_sock(psock, sock);
  1411. smap_list_remove(psock, &stab->sock_map[k], NULL);
  1412. smap_release_sock(psock, sock);
  1413. out:
  1414. write_unlock_bh(&sock->sk_callback_lock);
  1415. return 0;
  1416. }
  1417. /* Locking notes: Concurrent updates, deletes, and lookups are allowed and are
  1418. * done inside rcu critical sections. This ensures on updates that the psock
  1419. * will not be released via smap_release_sock() until concurrent updates/deletes
  1420. * complete. All operations operate on sock_map using cmpxchg and xchg
  1421. * operations to ensure we do not get stale references. Any reads into the
  1422. * map must be done with READ_ONCE() because of this.
  1423. *
  1424. * A psock is destroyed via call_rcu and after any worker threads are cancelled
  1425. * and syncd so we are certain all references from the update/lookup/delete
  1426. * operations as well as references in the data path are no longer in use.
  1427. *
  1428. * Psocks may exist in multiple maps, but only a single set of parse/verdict
  1429. * programs may be inherited from the maps it belongs to. A reference count
  1430. * is kept with the total number of references to the psock from all maps. The
  1431. * psock will not be released until this reaches zero. The psock and sock
  1432. * user data data use the sk_callback_lock to protect critical data structures
  1433. * from concurrent access. This allows us to avoid two updates from modifying
  1434. * the user data in sock and the lock is required anyways for modifying
  1435. * callbacks, we simply increase its scope slightly.
  1436. *
  1437. * Rules to follow,
  1438. * - psock must always be read inside RCU critical section
  1439. * - sk_user_data must only be modified inside sk_callback_lock and read
  1440. * inside RCU critical section.
  1441. * - psock->maps list must only be read & modified inside sk_callback_lock
  1442. * - sock_map must use READ_ONCE and (cmp)xchg operations
  1443. * - BPF verdict/parse programs must use READ_ONCE and xchg operations
  1444. */
  1445. static int __sock_map_ctx_update_elem(struct bpf_map *map,
  1446. struct bpf_sock_progs *progs,
  1447. struct sock *sock,
  1448. struct sock **map_link,
  1449. void *key)
  1450. {
  1451. struct bpf_prog *verdict, *parse, *tx_msg;
  1452. struct smap_psock_map_entry *e = NULL;
  1453. struct smap_psock *psock;
  1454. bool new = false;
  1455. int err = 0;
  1456. /* 1. If sock map has BPF programs those will be inherited by the
  1457. * sock being added. If the sock is already attached to BPF programs
  1458. * this results in an error.
  1459. */
  1460. verdict = READ_ONCE(progs->bpf_verdict);
  1461. parse = READ_ONCE(progs->bpf_parse);
  1462. tx_msg = READ_ONCE(progs->bpf_tx_msg);
  1463. if (parse && verdict) {
  1464. /* bpf prog refcnt may be zero if a concurrent attach operation
  1465. * removes the program after the above READ_ONCE() but before
  1466. * we increment the refcnt. If this is the case abort with an
  1467. * error.
  1468. */
  1469. verdict = bpf_prog_inc_not_zero(verdict);
  1470. if (IS_ERR(verdict))
  1471. return PTR_ERR(verdict);
  1472. parse = bpf_prog_inc_not_zero(parse);
  1473. if (IS_ERR(parse)) {
  1474. bpf_prog_put(verdict);
  1475. return PTR_ERR(parse);
  1476. }
  1477. }
  1478. if (tx_msg) {
  1479. tx_msg = bpf_prog_inc_not_zero(tx_msg);
  1480. if (IS_ERR(tx_msg)) {
  1481. if (parse && verdict) {
  1482. bpf_prog_put(parse);
  1483. bpf_prog_put(verdict);
  1484. }
  1485. return PTR_ERR(tx_msg);
  1486. }
  1487. }
  1488. write_lock_bh(&sock->sk_callback_lock);
  1489. psock = smap_psock_sk(sock);
  1490. /* 2. Do not allow inheriting programs if psock exists and has
  1491. * already inherited programs. This would create confusion on
  1492. * which parser/verdict program is running. If no psock exists
  1493. * create one. Inside sk_callback_lock to ensure concurrent create
  1494. * doesn't update user data.
  1495. */
  1496. if (psock) {
  1497. if (READ_ONCE(psock->bpf_parse) && parse) {
  1498. err = -EBUSY;
  1499. goto out_progs;
  1500. }
  1501. if (READ_ONCE(psock->bpf_tx_msg) && tx_msg) {
  1502. err = -EBUSY;
  1503. goto out_progs;
  1504. }
  1505. if (!refcount_inc_not_zero(&psock->refcnt)) {
  1506. err = -EAGAIN;
  1507. goto out_progs;
  1508. }
  1509. } else {
  1510. psock = smap_init_psock(sock, map->numa_node);
  1511. if (IS_ERR(psock)) {
  1512. err = PTR_ERR(psock);
  1513. goto out_progs;
  1514. }
  1515. set_bit(SMAP_TX_RUNNING, &psock->state);
  1516. new = true;
  1517. }
  1518. if (map_link) {
  1519. e = kzalloc(sizeof(*e), GFP_ATOMIC | __GFP_NOWARN);
  1520. if (!e) {
  1521. err = -ENOMEM;
  1522. goto out_progs;
  1523. }
  1524. }
  1525. /* 3. At this point we have a reference to a valid psock that is
  1526. * running. Attach any BPF programs needed.
  1527. */
  1528. if (tx_msg)
  1529. bpf_tcp_msg_add(psock, sock, tx_msg);
  1530. if (new) {
  1531. err = tcp_set_ulp_id(sock, TCP_ULP_BPF);
  1532. if (err)
  1533. goto out_free;
  1534. }
  1535. if (parse && verdict && !psock->strp_enabled) {
  1536. err = smap_init_sock(psock, sock);
  1537. if (err)
  1538. goto out_free;
  1539. smap_init_progs(psock, verdict, parse);
  1540. smap_start_sock(psock, sock);
  1541. }
  1542. /* 4. Place psock in sockmap for use and stop any programs on
  1543. * the old sock assuming its not the same sock we are replacing
  1544. * it with. Because we can only have a single set of programs if
  1545. * old_sock has a strp we can stop it.
  1546. */
  1547. if (map_link) {
  1548. e->entry = map_link;
  1549. list_add_tail(&e->list, &psock->maps);
  1550. }
  1551. write_unlock_bh(&sock->sk_callback_lock);
  1552. return err;
  1553. out_free:
  1554. smap_release_sock(psock, sock);
  1555. out_progs:
  1556. if (parse && verdict) {
  1557. bpf_prog_put(parse);
  1558. bpf_prog_put(verdict);
  1559. }
  1560. if (tx_msg)
  1561. bpf_prog_put(tx_msg);
  1562. write_unlock_bh(&sock->sk_callback_lock);
  1563. kfree(e);
  1564. return err;
  1565. }
  1566. static int sock_map_ctx_update_elem(struct bpf_sock_ops_kern *skops,
  1567. struct bpf_map *map,
  1568. void *key, u64 flags)
  1569. {
  1570. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1571. struct bpf_sock_progs *progs = &stab->progs;
  1572. struct sock *osock, *sock;
  1573. u32 i = *(u32 *)key;
  1574. int err;
  1575. if (unlikely(flags > BPF_EXIST))
  1576. return -EINVAL;
  1577. if (unlikely(i >= stab->map.max_entries))
  1578. return -E2BIG;
  1579. sock = READ_ONCE(stab->sock_map[i]);
  1580. if (flags == BPF_EXIST && !sock)
  1581. return -ENOENT;
  1582. else if (flags == BPF_NOEXIST && sock)
  1583. return -EEXIST;
  1584. sock = skops->sk;
  1585. err = __sock_map_ctx_update_elem(map, progs, sock, &stab->sock_map[i],
  1586. key);
  1587. if (err)
  1588. goto out;
  1589. osock = xchg(&stab->sock_map[i], sock);
  1590. if (osock) {
  1591. struct smap_psock *opsock = smap_psock_sk(osock);
  1592. write_lock_bh(&osock->sk_callback_lock);
  1593. smap_list_remove(opsock, &stab->sock_map[i], NULL);
  1594. smap_release_sock(opsock, osock);
  1595. write_unlock_bh(&osock->sk_callback_lock);
  1596. }
  1597. out:
  1598. return err;
  1599. }
  1600. int sock_map_prog(struct bpf_map *map, struct bpf_prog *prog, u32 type)
  1601. {
  1602. struct bpf_sock_progs *progs;
  1603. struct bpf_prog *orig;
  1604. if (map->map_type == BPF_MAP_TYPE_SOCKMAP) {
  1605. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1606. progs = &stab->progs;
  1607. } else if (map->map_type == BPF_MAP_TYPE_SOCKHASH) {
  1608. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  1609. progs = &htab->progs;
  1610. } else {
  1611. return -EINVAL;
  1612. }
  1613. switch (type) {
  1614. case BPF_SK_MSG_VERDICT:
  1615. orig = xchg(&progs->bpf_tx_msg, prog);
  1616. break;
  1617. case BPF_SK_SKB_STREAM_PARSER:
  1618. orig = xchg(&progs->bpf_parse, prog);
  1619. break;
  1620. case BPF_SK_SKB_STREAM_VERDICT:
  1621. orig = xchg(&progs->bpf_verdict, prog);
  1622. break;
  1623. default:
  1624. return -EOPNOTSUPP;
  1625. }
  1626. if (orig)
  1627. bpf_prog_put(orig);
  1628. return 0;
  1629. }
  1630. int sockmap_get_from_fd(const union bpf_attr *attr, int type,
  1631. struct bpf_prog *prog)
  1632. {
  1633. int ufd = attr->target_fd;
  1634. struct bpf_map *map;
  1635. struct fd f;
  1636. int err;
  1637. f = fdget(ufd);
  1638. map = __bpf_map_get(f);
  1639. if (IS_ERR(map))
  1640. return PTR_ERR(map);
  1641. err = sock_map_prog(map, prog, attr->attach_type);
  1642. fdput(f);
  1643. return err;
  1644. }
  1645. static void *sock_map_lookup(struct bpf_map *map, void *key)
  1646. {
  1647. return NULL;
  1648. }
  1649. static int sock_map_update_elem(struct bpf_map *map,
  1650. void *key, void *value, u64 flags)
  1651. {
  1652. struct bpf_sock_ops_kern skops;
  1653. u32 fd = *(u32 *)value;
  1654. struct socket *socket;
  1655. int err;
  1656. socket = sockfd_lookup(fd, &err);
  1657. if (!socket)
  1658. return err;
  1659. skops.sk = socket->sk;
  1660. if (!skops.sk) {
  1661. fput(socket->file);
  1662. return -EINVAL;
  1663. }
  1664. if (skops.sk->sk_type != SOCK_STREAM ||
  1665. skops.sk->sk_protocol != IPPROTO_TCP) {
  1666. fput(socket->file);
  1667. return -EOPNOTSUPP;
  1668. }
  1669. err = sock_map_ctx_update_elem(&skops, map, key, flags);
  1670. fput(socket->file);
  1671. return err;
  1672. }
  1673. static void sock_map_release(struct bpf_map *map)
  1674. {
  1675. struct bpf_sock_progs *progs;
  1676. struct bpf_prog *orig;
  1677. if (map->map_type == BPF_MAP_TYPE_SOCKMAP) {
  1678. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1679. progs = &stab->progs;
  1680. } else {
  1681. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  1682. progs = &htab->progs;
  1683. }
  1684. orig = xchg(&progs->bpf_parse, NULL);
  1685. if (orig)
  1686. bpf_prog_put(orig);
  1687. orig = xchg(&progs->bpf_verdict, NULL);
  1688. if (orig)
  1689. bpf_prog_put(orig);
  1690. orig = xchg(&progs->bpf_tx_msg, NULL);
  1691. if (orig)
  1692. bpf_prog_put(orig);
  1693. }
  1694. static struct bpf_map *sock_hash_alloc(union bpf_attr *attr)
  1695. {
  1696. struct bpf_htab *htab;
  1697. int i, err;
  1698. u64 cost;
  1699. if (!capable(CAP_NET_ADMIN))
  1700. return ERR_PTR(-EPERM);
  1701. /* check sanity of attributes */
  1702. if (attr->max_entries == 0 || attr->value_size != 4 ||
  1703. attr->map_flags & ~SOCK_CREATE_FLAG_MASK)
  1704. return ERR_PTR(-EINVAL);
  1705. if (attr->key_size > MAX_BPF_STACK)
  1706. /* eBPF programs initialize keys on stack, so they cannot be
  1707. * larger than max stack size
  1708. */
  1709. return ERR_PTR(-E2BIG);
  1710. err = bpf_tcp_ulp_register();
  1711. if (err && err != -EEXIST)
  1712. return ERR_PTR(err);
  1713. htab = kzalloc(sizeof(*htab), GFP_USER);
  1714. if (!htab)
  1715. return ERR_PTR(-ENOMEM);
  1716. bpf_map_init_from_attr(&htab->map, attr);
  1717. htab->n_buckets = roundup_pow_of_two(htab->map.max_entries);
  1718. htab->elem_size = sizeof(struct htab_elem) +
  1719. round_up(htab->map.key_size, 8);
  1720. err = -EINVAL;
  1721. if (htab->n_buckets == 0 ||
  1722. htab->n_buckets > U32_MAX / sizeof(struct bucket))
  1723. goto free_htab;
  1724. cost = (u64) htab->n_buckets * sizeof(struct bucket) +
  1725. (u64) htab->elem_size * htab->map.max_entries;
  1726. if (cost >= U32_MAX - PAGE_SIZE)
  1727. goto free_htab;
  1728. htab->map.pages = round_up(cost, PAGE_SIZE) >> PAGE_SHIFT;
  1729. err = bpf_map_precharge_memlock(htab->map.pages);
  1730. if (err)
  1731. goto free_htab;
  1732. err = -ENOMEM;
  1733. htab->buckets = bpf_map_area_alloc(
  1734. htab->n_buckets * sizeof(struct bucket),
  1735. htab->map.numa_node);
  1736. if (!htab->buckets)
  1737. goto free_htab;
  1738. for (i = 0; i < htab->n_buckets; i++) {
  1739. INIT_HLIST_HEAD(&htab->buckets[i].head);
  1740. raw_spin_lock_init(&htab->buckets[i].lock);
  1741. }
  1742. return &htab->map;
  1743. free_htab:
  1744. kfree(htab);
  1745. return ERR_PTR(err);
  1746. }
  1747. static inline struct bucket *__select_bucket(struct bpf_htab *htab, u32 hash)
  1748. {
  1749. return &htab->buckets[hash & (htab->n_buckets - 1)];
  1750. }
  1751. static inline struct hlist_head *select_bucket(struct bpf_htab *htab, u32 hash)
  1752. {
  1753. return &__select_bucket(htab, hash)->head;
  1754. }
  1755. static void sock_hash_free(struct bpf_map *map)
  1756. {
  1757. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  1758. int i;
  1759. synchronize_rcu();
  1760. /* At this point no update, lookup or delete operations can happen.
  1761. * However, be aware we can still get a socket state event updates,
  1762. * and data ready callabacks that reference the psock from sk_user_data
  1763. * Also psock worker threads are still in-flight. So smap_release_sock
  1764. * will only free the psock after cancel_sync on the worker threads
  1765. * and a grace period expire to ensure psock is really safe to remove.
  1766. */
  1767. rcu_read_lock();
  1768. for (i = 0; i < htab->n_buckets; i++) {
  1769. struct hlist_head *head = select_bucket(htab, i);
  1770. struct hlist_node *n;
  1771. struct htab_elem *l;
  1772. hlist_for_each_entry_safe(l, n, head, hash_node) {
  1773. struct sock *sock = l->sk;
  1774. struct smap_psock *psock;
  1775. hlist_del_rcu(&l->hash_node);
  1776. write_lock_bh(&sock->sk_callback_lock);
  1777. psock = smap_psock_sk(sock);
  1778. /* This check handles a racing sock event that can get
  1779. * the sk_callback_lock before this case but after xchg
  1780. * causing the refcnt to hit zero and sock user data
  1781. * (psock) to be null and queued for garbage collection.
  1782. */
  1783. if (likely(psock)) {
  1784. smap_list_remove(psock, NULL, l);
  1785. smap_release_sock(psock, sock);
  1786. }
  1787. write_unlock_bh(&sock->sk_callback_lock);
  1788. kfree(l);
  1789. }
  1790. }
  1791. rcu_read_unlock();
  1792. bpf_map_area_free(htab->buckets);
  1793. kfree(htab);
  1794. }
  1795. static struct htab_elem *alloc_sock_hash_elem(struct bpf_htab *htab,
  1796. void *key, u32 key_size, u32 hash,
  1797. struct sock *sk,
  1798. struct htab_elem *old_elem)
  1799. {
  1800. struct htab_elem *l_new;
  1801. if (atomic_inc_return(&htab->count) > htab->map.max_entries) {
  1802. if (!old_elem) {
  1803. atomic_dec(&htab->count);
  1804. return ERR_PTR(-E2BIG);
  1805. }
  1806. }
  1807. l_new = kmalloc_node(htab->elem_size, GFP_ATOMIC | __GFP_NOWARN,
  1808. htab->map.numa_node);
  1809. if (!l_new)
  1810. return ERR_PTR(-ENOMEM);
  1811. memcpy(l_new->key, key, key_size);
  1812. l_new->sk = sk;
  1813. l_new->hash = hash;
  1814. return l_new;
  1815. }
  1816. static struct htab_elem *lookup_elem_raw(struct hlist_head *head,
  1817. u32 hash, void *key, u32 key_size)
  1818. {
  1819. struct htab_elem *l;
  1820. hlist_for_each_entry_rcu(l, head, hash_node) {
  1821. if (l->hash == hash && !memcmp(&l->key, key, key_size))
  1822. return l;
  1823. }
  1824. return NULL;
  1825. }
  1826. static inline u32 htab_map_hash(const void *key, u32 key_len)
  1827. {
  1828. return jhash(key, key_len, 0);
  1829. }
  1830. static int sock_hash_get_next_key(struct bpf_map *map,
  1831. void *key, void *next_key)
  1832. {
  1833. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  1834. struct htab_elem *l, *next_l;
  1835. struct hlist_head *h;
  1836. u32 hash, key_size;
  1837. int i = 0;
  1838. WARN_ON_ONCE(!rcu_read_lock_held());
  1839. key_size = map->key_size;
  1840. if (!key)
  1841. goto find_first_elem;
  1842. hash = htab_map_hash(key, key_size);
  1843. h = select_bucket(htab, hash);
  1844. l = lookup_elem_raw(h, hash, key, key_size);
  1845. if (!l)
  1846. goto find_first_elem;
  1847. next_l = hlist_entry_safe(
  1848. rcu_dereference_raw(hlist_next_rcu(&l->hash_node)),
  1849. struct htab_elem, hash_node);
  1850. if (next_l) {
  1851. memcpy(next_key, next_l->key, key_size);
  1852. return 0;
  1853. }
  1854. /* no more elements in this hash list, go to the next bucket */
  1855. i = hash & (htab->n_buckets - 1);
  1856. i++;
  1857. find_first_elem:
  1858. /* iterate over buckets */
  1859. for (; i < htab->n_buckets; i++) {
  1860. h = select_bucket(htab, i);
  1861. /* pick first element in the bucket */
  1862. next_l = hlist_entry_safe(
  1863. rcu_dereference_raw(hlist_first_rcu(h)),
  1864. struct htab_elem, hash_node);
  1865. if (next_l) {
  1866. /* if it's not empty, just return it */
  1867. memcpy(next_key, next_l->key, key_size);
  1868. return 0;
  1869. }
  1870. }
  1871. /* iterated over all buckets and all elements */
  1872. return -ENOENT;
  1873. }
  1874. static int sock_hash_ctx_update_elem(struct bpf_sock_ops_kern *skops,
  1875. struct bpf_map *map,
  1876. void *key, u64 map_flags)
  1877. {
  1878. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  1879. struct bpf_sock_progs *progs = &htab->progs;
  1880. struct htab_elem *l_new = NULL, *l_old;
  1881. struct smap_psock_map_entry *e = NULL;
  1882. struct hlist_head *head;
  1883. struct smap_psock *psock;
  1884. u32 key_size, hash;
  1885. struct sock *sock;
  1886. struct bucket *b;
  1887. int err;
  1888. sock = skops->sk;
  1889. if (sock->sk_type != SOCK_STREAM ||
  1890. sock->sk_protocol != IPPROTO_TCP)
  1891. return -EOPNOTSUPP;
  1892. if (unlikely(map_flags > BPF_EXIST))
  1893. return -EINVAL;
  1894. e = kzalloc(sizeof(*e), GFP_ATOMIC | __GFP_NOWARN);
  1895. if (!e)
  1896. return -ENOMEM;
  1897. WARN_ON_ONCE(!rcu_read_lock_held());
  1898. key_size = map->key_size;
  1899. hash = htab_map_hash(key, key_size);
  1900. b = __select_bucket(htab, hash);
  1901. head = &b->head;
  1902. err = __sock_map_ctx_update_elem(map, progs, sock, NULL, key);
  1903. if (err)
  1904. goto err;
  1905. /* bpf_map_update_elem() can be called in_irq() */
  1906. raw_spin_lock_bh(&b->lock);
  1907. l_old = lookup_elem_raw(head, hash, key, key_size);
  1908. if (l_old && map_flags == BPF_NOEXIST) {
  1909. err = -EEXIST;
  1910. goto bucket_err;
  1911. }
  1912. if (!l_old && map_flags == BPF_EXIST) {
  1913. err = -ENOENT;
  1914. goto bucket_err;
  1915. }
  1916. l_new = alloc_sock_hash_elem(htab, key, key_size, hash, sock, l_old);
  1917. if (IS_ERR(l_new)) {
  1918. err = PTR_ERR(l_new);
  1919. goto bucket_err;
  1920. }
  1921. psock = smap_psock_sk(sock);
  1922. if (unlikely(!psock)) {
  1923. err = -EINVAL;
  1924. goto bucket_err;
  1925. }
  1926. e->hash_link = l_new;
  1927. e->htab = container_of(map, struct bpf_htab, map);
  1928. list_add_tail(&e->list, &psock->maps);
  1929. /* add new element to the head of the list, so that
  1930. * concurrent search will find it before old elem
  1931. */
  1932. hlist_add_head_rcu(&l_new->hash_node, head);
  1933. if (l_old) {
  1934. psock = smap_psock_sk(l_old->sk);
  1935. hlist_del_rcu(&l_old->hash_node);
  1936. smap_list_remove(psock, NULL, l_old);
  1937. smap_release_sock(psock, l_old->sk);
  1938. free_htab_elem(htab, l_old);
  1939. }
  1940. raw_spin_unlock_bh(&b->lock);
  1941. return 0;
  1942. bucket_err:
  1943. raw_spin_unlock_bh(&b->lock);
  1944. err:
  1945. kfree(e);
  1946. psock = smap_psock_sk(sock);
  1947. if (psock)
  1948. smap_release_sock(psock, sock);
  1949. return err;
  1950. }
  1951. static int sock_hash_update_elem(struct bpf_map *map,
  1952. void *key, void *value, u64 flags)
  1953. {
  1954. struct bpf_sock_ops_kern skops;
  1955. u32 fd = *(u32 *)value;
  1956. struct socket *socket;
  1957. int err;
  1958. socket = sockfd_lookup(fd, &err);
  1959. if (!socket)
  1960. return err;
  1961. skops.sk = socket->sk;
  1962. if (!skops.sk) {
  1963. fput(socket->file);
  1964. return -EINVAL;
  1965. }
  1966. err = sock_hash_ctx_update_elem(&skops, map, key, flags);
  1967. fput(socket->file);
  1968. return err;
  1969. }
  1970. static int sock_hash_delete_elem(struct bpf_map *map, void *key)
  1971. {
  1972. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  1973. struct hlist_head *head;
  1974. struct bucket *b;
  1975. struct htab_elem *l;
  1976. u32 hash, key_size;
  1977. int ret = -ENOENT;
  1978. key_size = map->key_size;
  1979. hash = htab_map_hash(key, key_size);
  1980. b = __select_bucket(htab, hash);
  1981. head = &b->head;
  1982. raw_spin_lock_bh(&b->lock);
  1983. l = lookup_elem_raw(head, hash, key, key_size);
  1984. if (l) {
  1985. struct sock *sock = l->sk;
  1986. struct smap_psock *psock;
  1987. hlist_del_rcu(&l->hash_node);
  1988. write_lock_bh(&sock->sk_callback_lock);
  1989. psock = smap_psock_sk(sock);
  1990. /* This check handles a racing sock event that can get the
  1991. * sk_callback_lock before this case but after xchg happens
  1992. * causing the refcnt to hit zero and sock user data (psock)
  1993. * to be null and queued for garbage collection.
  1994. */
  1995. if (likely(psock)) {
  1996. smap_list_remove(psock, NULL, l);
  1997. smap_release_sock(psock, sock);
  1998. }
  1999. write_unlock_bh(&sock->sk_callback_lock);
  2000. free_htab_elem(htab, l);
  2001. ret = 0;
  2002. }
  2003. raw_spin_unlock_bh(&b->lock);
  2004. return ret;
  2005. }
  2006. struct sock *__sock_hash_lookup_elem(struct bpf_map *map, void *key)
  2007. {
  2008. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  2009. struct hlist_head *head;
  2010. struct htab_elem *l;
  2011. u32 key_size, hash;
  2012. struct bucket *b;
  2013. struct sock *sk;
  2014. key_size = map->key_size;
  2015. hash = htab_map_hash(key, key_size);
  2016. b = __select_bucket(htab, hash);
  2017. head = &b->head;
  2018. raw_spin_lock_bh(&b->lock);
  2019. l = lookup_elem_raw(head, hash, key, key_size);
  2020. sk = l ? l->sk : NULL;
  2021. raw_spin_unlock_bh(&b->lock);
  2022. return sk;
  2023. }
  2024. const struct bpf_map_ops sock_map_ops = {
  2025. .map_alloc = sock_map_alloc,
  2026. .map_free = sock_map_free,
  2027. .map_lookup_elem = sock_map_lookup,
  2028. .map_get_next_key = sock_map_get_next_key,
  2029. .map_update_elem = sock_map_update_elem,
  2030. .map_delete_elem = sock_map_delete_elem,
  2031. .map_release_uref = sock_map_release,
  2032. };
  2033. const struct bpf_map_ops sock_hash_ops = {
  2034. .map_alloc = sock_hash_alloc,
  2035. .map_free = sock_hash_free,
  2036. .map_lookup_elem = sock_map_lookup,
  2037. .map_get_next_key = sock_hash_get_next_key,
  2038. .map_update_elem = sock_hash_update_elem,
  2039. .map_delete_elem = sock_hash_delete_elem,
  2040. };
  2041. BPF_CALL_4(bpf_sock_map_update, struct bpf_sock_ops_kern *, bpf_sock,
  2042. struct bpf_map *, map, void *, key, u64, flags)
  2043. {
  2044. WARN_ON_ONCE(!rcu_read_lock_held());
  2045. return sock_map_ctx_update_elem(bpf_sock, map, key, flags);
  2046. }
  2047. const struct bpf_func_proto bpf_sock_map_update_proto = {
  2048. .func = bpf_sock_map_update,
  2049. .gpl_only = false,
  2050. .pkt_access = true,
  2051. .ret_type = RET_INTEGER,
  2052. .arg1_type = ARG_PTR_TO_CTX,
  2053. .arg2_type = ARG_CONST_MAP_PTR,
  2054. .arg3_type = ARG_PTR_TO_MAP_KEY,
  2055. .arg4_type = ARG_ANYTHING,
  2056. };
  2057. BPF_CALL_4(bpf_sock_hash_update, struct bpf_sock_ops_kern *, bpf_sock,
  2058. struct bpf_map *, map, void *, key, u64, flags)
  2059. {
  2060. WARN_ON_ONCE(!rcu_read_lock_held());
  2061. return sock_hash_ctx_update_elem(bpf_sock, map, key, flags);
  2062. }
  2063. const struct bpf_func_proto bpf_sock_hash_update_proto = {
  2064. .func = bpf_sock_hash_update,
  2065. .gpl_only = false,
  2066. .pkt_access = true,
  2067. .ret_type = RET_INTEGER,
  2068. .arg1_type = ARG_PTR_TO_CTX,
  2069. .arg2_type = ARG_CONST_MAP_PTR,
  2070. .arg3_type = ARG_PTR_TO_MAP_KEY,
  2071. .arg4_type = ARG_ANYTHING,
  2072. };