sockmap.c 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421
  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. rc = (*prog->bpf_func)(md, prog->insnsi);
  446. psock->apply_bytes = md->apply_bytes;
  447. /* Moving return codes from UAPI namespace into internal namespace */
  448. _rc = bpf_map_msg_verdict(rc, md);
  449. /* The psock has a refcount on the sock but not on the map and because
  450. * we need to drop rcu read lock here its possible the map could be
  451. * removed between here and when we need it to execute the sock
  452. * redirect. So do the map lookup now for future use.
  453. */
  454. if (_rc == __SK_REDIRECT) {
  455. if (psock->sk_redir)
  456. sock_put(psock->sk_redir);
  457. psock->sk_redir = do_msg_redirect_map(md);
  458. if (!psock->sk_redir) {
  459. _rc = __SK_DROP;
  460. goto verdict;
  461. }
  462. sock_hold(psock->sk_redir);
  463. }
  464. verdict:
  465. rcu_read_unlock();
  466. preempt_enable();
  467. return _rc;
  468. }
  469. static int bpf_tcp_ingress(struct sock *sk, int apply_bytes,
  470. struct smap_psock *psock,
  471. struct sk_msg_buff *md, int flags)
  472. {
  473. bool apply = apply_bytes;
  474. size_t size, copied = 0;
  475. struct sk_msg_buff *r;
  476. int err = 0, i;
  477. r = kzalloc(sizeof(struct sk_msg_buff), __GFP_NOWARN | GFP_KERNEL);
  478. if (unlikely(!r))
  479. return -ENOMEM;
  480. lock_sock(sk);
  481. r->sg_start = md->sg_start;
  482. i = md->sg_start;
  483. do {
  484. size = (apply && apply_bytes < md->sg_data[i].length) ?
  485. apply_bytes : md->sg_data[i].length;
  486. if (!sk_wmem_schedule(sk, size)) {
  487. if (!copied)
  488. err = -ENOMEM;
  489. break;
  490. }
  491. sk_mem_charge(sk, size);
  492. r->sg_data[i] = md->sg_data[i];
  493. r->sg_data[i].length = size;
  494. md->sg_data[i].length -= size;
  495. md->sg_data[i].offset += size;
  496. copied += size;
  497. if (md->sg_data[i].length) {
  498. get_page(sg_page(&r->sg_data[i]));
  499. r->sg_end = (i + 1) == MAX_SKB_FRAGS ? 0 : i + 1;
  500. } else {
  501. i++;
  502. if (i == MAX_SKB_FRAGS)
  503. i = 0;
  504. r->sg_end = i;
  505. }
  506. if (apply) {
  507. apply_bytes -= size;
  508. if (!apply_bytes)
  509. break;
  510. }
  511. } while (i != md->sg_end);
  512. md->sg_start = i;
  513. if (!err) {
  514. list_add_tail(&r->list, &psock->ingress);
  515. sk->sk_data_ready(sk);
  516. } else {
  517. free_start_sg(sk, r);
  518. kfree(r);
  519. }
  520. release_sock(sk);
  521. return err;
  522. }
  523. static int bpf_tcp_sendmsg_do_redirect(struct sock *sk, int send,
  524. struct sk_msg_buff *md,
  525. int flags)
  526. {
  527. bool ingress = !!(md->flags & BPF_F_INGRESS);
  528. struct smap_psock *psock;
  529. struct scatterlist *sg;
  530. int err = 0;
  531. sg = md->sg_data;
  532. rcu_read_lock();
  533. psock = smap_psock_sk(sk);
  534. if (unlikely(!psock))
  535. goto out_rcu;
  536. if (!refcount_inc_not_zero(&psock->refcnt))
  537. goto out_rcu;
  538. rcu_read_unlock();
  539. if (ingress) {
  540. err = bpf_tcp_ingress(sk, send, psock, md, flags);
  541. } else {
  542. lock_sock(sk);
  543. err = bpf_tcp_push(sk, send, md, flags, false);
  544. release_sock(sk);
  545. }
  546. smap_release_sock(psock, sk);
  547. if (unlikely(err))
  548. goto out;
  549. return 0;
  550. out_rcu:
  551. rcu_read_unlock();
  552. out:
  553. free_bytes_sg(NULL, send, md, false);
  554. return err;
  555. }
  556. static inline void bpf_md_init(struct smap_psock *psock)
  557. {
  558. if (!psock->apply_bytes) {
  559. psock->eval = __SK_NONE;
  560. if (psock->sk_redir) {
  561. sock_put(psock->sk_redir);
  562. psock->sk_redir = NULL;
  563. }
  564. }
  565. }
  566. static void apply_bytes_dec(struct smap_psock *psock, int i)
  567. {
  568. if (psock->apply_bytes) {
  569. if (psock->apply_bytes < i)
  570. psock->apply_bytes = 0;
  571. else
  572. psock->apply_bytes -= i;
  573. }
  574. }
  575. static int bpf_exec_tx_verdict(struct smap_psock *psock,
  576. struct sk_msg_buff *m,
  577. struct sock *sk,
  578. int *copied, int flags)
  579. {
  580. bool cork = false, enospc = (m->sg_start == m->sg_end);
  581. struct sock *redir;
  582. int err = 0;
  583. int send;
  584. more_data:
  585. if (psock->eval == __SK_NONE)
  586. psock->eval = smap_do_tx_msg(sk, psock, m);
  587. if (m->cork_bytes &&
  588. m->cork_bytes > psock->sg_size && !enospc) {
  589. psock->cork_bytes = m->cork_bytes - psock->sg_size;
  590. if (!psock->cork) {
  591. psock->cork = kcalloc(1,
  592. sizeof(struct sk_msg_buff),
  593. GFP_ATOMIC | __GFP_NOWARN);
  594. if (!psock->cork) {
  595. err = -ENOMEM;
  596. goto out_err;
  597. }
  598. }
  599. memcpy(psock->cork, m, sizeof(*m));
  600. goto out_err;
  601. }
  602. send = psock->sg_size;
  603. if (psock->apply_bytes && psock->apply_bytes < send)
  604. send = psock->apply_bytes;
  605. switch (psock->eval) {
  606. case __SK_PASS:
  607. err = bpf_tcp_push(sk, send, m, flags, true);
  608. if (unlikely(err)) {
  609. *copied -= free_start_sg(sk, m);
  610. break;
  611. }
  612. apply_bytes_dec(psock, send);
  613. psock->sg_size -= send;
  614. break;
  615. case __SK_REDIRECT:
  616. redir = psock->sk_redir;
  617. apply_bytes_dec(psock, send);
  618. if (psock->cork) {
  619. cork = true;
  620. psock->cork = NULL;
  621. }
  622. return_mem_sg(sk, send, m);
  623. release_sock(sk);
  624. err = bpf_tcp_sendmsg_do_redirect(redir, send, m, flags);
  625. lock_sock(sk);
  626. if (unlikely(err < 0)) {
  627. free_start_sg(sk, m);
  628. psock->sg_size = 0;
  629. if (!cork)
  630. *copied -= send;
  631. } else {
  632. psock->sg_size -= send;
  633. }
  634. if (cork) {
  635. free_start_sg(sk, m);
  636. psock->sg_size = 0;
  637. kfree(m);
  638. m = NULL;
  639. err = 0;
  640. }
  641. break;
  642. case __SK_DROP:
  643. default:
  644. free_bytes_sg(sk, send, m, true);
  645. apply_bytes_dec(psock, send);
  646. *copied -= send;
  647. psock->sg_size -= send;
  648. err = -EACCES;
  649. break;
  650. }
  651. if (likely(!err)) {
  652. bpf_md_init(psock);
  653. if (m &&
  654. m->sg_data[m->sg_start].page_link &&
  655. m->sg_data[m->sg_start].length)
  656. goto more_data;
  657. }
  658. out_err:
  659. return err;
  660. }
  661. static int bpf_wait_data(struct sock *sk,
  662. struct smap_psock *psk, int flags,
  663. long timeo, int *err)
  664. {
  665. int rc;
  666. DEFINE_WAIT_FUNC(wait, woken_wake_function);
  667. add_wait_queue(sk_sleep(sk), &wait);
  668. sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
  669. rc = sk_wait_event(sk, &timeo,
  670. !list_empty(&psk->ingress) ||
  671. !skb_queue_empty(&sk->sk_receive_queue),
  672. &wait);
  673. sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
  674. remove_wait_queue(sk_sleep(sk), &wait);
  675. return rc;
  676. }
  677. static int bpf_tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
  678. int nonblock, int flags, int *addr_len)
  679. {
  680. struct iov_iter *iter = &msg->msg_iter;
  681. struct smap_psock *psock;
  682. int copied = 0;
  683. if (unlikely(flags & MSG_ERRQUEUE))
  684. return inet_recv_error(sk, msg, len, addr_len);
  685. rcu_read_lock();
  686. psock = smap_psock_sk(sk);
  687. if (unlikely(!psock))
  688. goto out;
  689. if (unlikely(!refcount_inc_not_zero(&psock->refcnt)))
  690. goto out;
  691. rcu_read_unlock();
  692. if (!skb_queue_empty(&sk->sk_receive_queue))
  693. return tcp_recvmsg(sk, msg, len, nonblock, flags, addr_len);
  694. lock_sock(sk);
  695. bytes_ready:
  696. while (copied != len) {
  697. struct scatterlist *sg;
  698. struct sk_msg_buff *md;
  699. int i;
  700. md = list_first_entry_or_null(&psock->ingress,
  701. struct sk_msg_buff, list);
  702. if (unlikely(!md))
  703. break;
  704. i = md->sg_start;
  705. do {
  706. struct page *page;
  707. int n, copy;
  708. sg = &md->sg_data[i];
  709. copy = sg->length;
  710. page = sg_page(sg);
  711. if (copied + copy > len)
  712. copy = len - copied;
  713. n = copy_page_to_iter(page, sg->offset, copy, iter);
  714. if (n != copy) {
  715. md->sg_start = i;
  716. release_sock(sk);
  717. smap_release_sock(psock, sk);
  718. return -EFAULT;
  719. }
  720. copied += copy;
  721. sg->offset += copy;
  722. sg->length -= copy;
  723. sk_mem_uncharge(sk, copy);
  724. if (!sg->length) {
  725. i++;
  726. if (i == MAX_SKB_FRAGS)
  727. i = 0;
  728. if (!md->skb)
  729. put_page(page);
  730. }
  731. if (copied == len)
  732. break;
  733. } while (i != md->sg_end);
  734. md->sg_start = i;
  735. if (!sg->length && md->sg_start == md->sg_end) {
  736. list_del(&md->list);
  737. if (md->skb)
  738. consume_skb(md->skb);
  739. kfree(md);
  740. }
  741. }
  742. if (!copied) {
  743. long timeo;
  744. int data;
  745. int err = 0;
  746. timeo = sock_rcvtimeo(sk, nonblock);
  747. data = bpf_wait_data(sk, psock, flags, timeo, &err);
  748. if (data) {
  749. if (!skb_queue_empty(&sk->sk_receive_queue)) {
  750. release_sock(sk);
  751. smap_release_sock(psock, sk);
  752. copied = tcp_recvmsg(sk, msg, len, nonblock, flags, addr_len);
  753. return copied;
  754. }
  755. goto bytes_ready;
  756. }
  757. if (err)
  758. copied = err;
  759. }
  760. release_sock(sk);
  761. smap_release_sock(psock, sk);
  762. return copied;
  763. out:
  764. rcu_read_unlock();
  765. return tcp_recvmsg(sk, msg, len, nonblock, flags, addr_len);
  766. }
  767. static int bpf_tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
  768. {
  769. int flags = msg->msg_flags | MSG_NO_SHARED_FRAGS;
  770. struct sk_msg_buff md = {0};
  771. unsigned int sg_copy = 0;
  772. struct smap_psock *psock;
  773. int copied = 0, err = 0;
  774. struct scatterlist *sg;
  775. long timeo;
  776. /* Its possible a sock event or user removed the psock _but_ the ops
  777. * have not been reprogrammed yet so we get here. In this case fallback
  778. * to tcp_sendmsg. Note this only works because we _only_ ever allow
  779. * a single ULP there is no hierarchy here.
  780. */
  781. rcu_read_lock();
  782. psock = smap_psock_sk(sk);
  783. if (unlikely(!psock)) {
  784. rcu_read_unlock();
  785. return tcp_sendmsg(sk, msg, size);
  786. }
  787. /* Increment the psock refcnt to ensure its not released while sending a
  788. * message. Required because sk lookup and bpf programs are used in
  789. * separate rcu critical sections. Its OK if we lose the map entry
  790. * but we can't lose the sock reference.
  791. */
  792. if (!refcount_inc_not_zero(&psock->refcnt)) {
  793. rcu_read_unlock();
  794. return tcp_sendmsg(sk, msg, size);
  795. }
  796. sg = md.sg_data;
  797. sg_init_marker(sg, MAX_SKB_FRAGS);
  798. rcu_read_unlock();
  799. lock_sock(sk);
  800. timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
  801. while (msg_data_left(msg)) {
  802. struct sk_msg_buff *m;
  803. bool enospc = false;
  804. int copy;
  805. if (sk->sk_err) {
  806. err = sk->sk_err;
  807. goto out_err;
  808. }
  809. copy = msg_data_left(msg);
  810. if (!sk_stream_memory_free(sk))
  811. goto wait_for_sndbuf;
  812. m = psock->cork_bytes ? psock->cork : &md;
  813. m->sg_curr = m->sg_copybreak ? m->sg_curr : m->sg_end;
  814. err = sk_alloc_sg(sk, copy, m->sg_data,
  815. m->sg_start, &m->sg_end, &sg_copy,
  816. m->sg_end - 1);
  817. if (err) {
  818. if (err != -ENOSPC)
  819. goto wait_for_memory;
  820. enospc = true;
  821. copy = sg_copy;
  822. }
  823. err = memcopy_from_iter(sk, m, &msg->msg_iter, copy);
  824. if (err < 0) {
  825. free_curr_sg(sk, m);
  826. goto out_err;
  827. }
  828. psock->sg_size += copy;
  829. copied += copy;
  830. sg_copy = 0;
  831. /* When bytes are being corked skip running BPF program and
  832. * applying verdict unless there is no more buffer space. In
  833. * the ENOSPC case simply run BPF prorgram with currently
  834. * accumulated data. We don't have much choice at this point
  835. * we could try extending the page frags or chaining complex
  836. * frags but even in these cases _eventually_ we will hit an
  837. * OOM scenario. More complex recovery schemes may be
  838. * implemented in the future, but BPF programs must handle
  839. * the case where apply_cork requests are not honored. The
  840. * canonical method to verify this is to check data length.
  841. */
  842. if (psock->cork_bytes) {
  843. if (copy > psock->cork_bytes)
  844. psock->cork_bytes = 0;
  845. else
  846. psock->cork_bytes -= copy;
  847. if (psock->cork_bytes && !enospc)
  848. goto out_cork;
  849. /* All cork bytes accounted for re-run filter */
  850. psock->eval = __SK_NONE;
  851. psock->cork_bytes = 0;
  852. }
  853. err = bpf_exec_tx_verdict(psock, m, sk, &copied, flags);
  854. if (unlikely(err < 0))
  855. goto out_err;
  856. continue;
  857. wait_for_sndbuf:
  858. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  859. wait_for_memory:
  860. err = sk_stream_wait_memory(sk, &timeo);
  861. if (err)
  862. goto out_err;
  863. }
  864. out_err:
  865. if (err < 0)
  866. err = sk_stream_error(sk, msg->msg_flags, err);
  867. out_cork:
  868. release_sock(sk);
  869. smap_release_sock(psock, sk);
  870. return copied ? copied : err;
  871. }
  872. static int bpf_tcp_sendpage(struct sock *sk, struct page *page,
  873. int offset, size_t size, int flags)
  874. {
  875. struct sk_msg_buff md = {0}, *m = NULL;
  876. int err = 0, copied = 0;
  877. struct smap_psock *psock;
  878. struct scatterlist *sg;
  879. bool enospc = false;
  880. rcu_read_lock();
  881. psock = smap_psock_sk(sk);
  882. if (unlikely(!psock))
  883. goto accept;
  884. if (!refcount_inc_not_zero(&psock->refcnt))
  885. goto accept;
  886. rcu_read_unlock();
  887. lock_sock(sk);
  888. if (psock->cork_bytes) {
  889. m = psock->cork;
  890. sg = &m->sg_data[m->sg_end];
  891. } else {
  892. m = &md;
  893. sg = m->sg_data;
  894. sg_init_marker(sg, MAX_SKB_FRAGS);
  895. }
  896. /* Catch case where ring is full and sendpage is stalled. */
  897. if (unlikely(m->sg_end == m->sg_start &&
  898. m->sg_data[m->sg_end].length))
  899. goto out_err;
  900. psock->sg_size += size;
  901. sg_set_page(sg, page, size, offset);
  902. get_page(page);
  903. m->sg_copy[m->sg_end] = true;
  904. sk_mem_charge(sk, size);
  905. m->sg_end++;
  906. copied = size;
  907. if (m->sg_end == MAX_SKB_FRAGS)
  908. m->sg_end = 0;
  909. if (m->sg_end == m->sg_start)
  910. enospc = true;
  911. if (psock->cork_bytes) {
  912. if (size > psock->cork_bytes)
  913. psock->cork_bytes = 0;
  914. else
  915. psock->cork_bytes -= size;
  916. if (psock->cork_bytes && !enospc)
  917. goto out_err;
  918. /* All cork bytes accounted for re-run filter */
  919. psock->eval = __SK_NONE;
  920. psock->cork_bytes = 0;
  921. }
  922. err = bpf_exec_tx_verdict(psock, m, sk, &copied, flags);
  923. out_err:
  924. release_sock(sk);
  925. smap_release_sock(psock, sk);
  926. return copied ? copied : err;
  927. accept:
  928. rcu_read_unlock();
  929. return tcp_sendpage(sk, page, offset, size, flags);
  930. }
  931. static void bpf_tcp_msg_add(struct smap_psock *psock,
  932. struct sock *sk,
  933. struct bpf_prog *tx_msg)
  934. {
  935. struct bpf_prog *orig_tx_msg;
  936. orig_tx_msg = xchg(&psock->bpf_tx_msg, tx_msg);
  937. if (orig_tx_msg)
  938. bpf_prog_put(orig_tx_msg);
  939. }
  940. static int bpf_tcp_ulp_register(void)
  941. {
  942. tcp_bpf_proto = tcp_prot;
  943. tcp_bpf_proto.close = bpf_tcp_close;
  944. /* Once BPF TX ULP is registered it is never unregistered. It
  945. * will be in the ULP list for the lifetime of the system. Doing
  946. * duplicate registers is not a problem.
  947. */
  948. return tcp_register_ulp(&bpf_tcp_ulp_ops);
  949. }
  950. static int smap_verdict_func(struct smap_psock *psock, struct sk_buff *skb)
  951. {
  952. struct bpf_prog *prog = READ_ONCE(psock->bpf_verdict);
  953. int rc;
  954. if (unlikely(!prog))
  955. return __SK_DROP;
  956. skb_orphan(skb);
  957. /* We need to ensure that BPF metadata for maps is also cleared
  958. * when we orphan the skb so that we don't have the possibility
  959. * to reference a stale map.
  960. */
  961. TCP_SKB_CB(skb)->bpf.sk_redir = NULL;
  962. skb->sk = psock->sock;
  963. bpf_compute_data_pointers(skb);
  964. preempt_disable();
  965. rc = (*prog->bpf_func)(skb, prog->insnsi);
  966. preempt_enable();
  967. skb->sk = NULL;
  968. /* Moving return codes from UAPI namespace into internal namespace */
  969. return rc == SK_PASS ?
  970. (TCP_SKB_CB(skb)->bpf.sk_redir ? __SK_REDIRECT : __SK_PASS) :
  971. __SK_DROP;
  972. }
  973. static int smap_do_ingress(struct smap_psock *psock, struct sk_buff *skb)
  974. {
  975. struct sock *sk = psock->sock;
  976. int copied = 0, num_sg;
  977. struct sk_msg_buff *r;
  978. r = kzalloc(sizeof(struct sk_msg_buff), __GFP_NOWARN | GFP_ATOMIC);
  979. if (unlikely(!r))
  980. return -EAGAIN;
  981. if (!sk_rmem_schedule(sk, skb, skb->len)) {
  982. kfree(r);
  983. return -EAGAIN;
  984. }
  985. sg_init_table(r->sg_data, MAX_SKB_FRAGS);
  986. num_sg = skb_to_sgvec(skb, r->sg_data, 0, skb->len);
  987. if (unlikely(num_sg < 0)) {
  988. kfree(r);
  989. return num_sg;
  990. }
  991. sk_mem_charge(sk, skb->len);
  992. copied = skb->len;
  993. r->sg_start = 0;
  994. r->sg_end = num_sg == MAX_SKB_FRAGS ? 0 : num_sg;
  995. r->skb = skb;
  996. list_add_tail(&r->list, &psock->ingress);
  997. sk->sk_data_ready(sk);
  998. return copied;
  999. }
  1000. static void smap_do_verdict(struct smap_psock *psock, struct sk_buff *skb)
  1001. {
  1002. struct smap_psock *peer;
  1003. struct sock *sk;
  1004. __u32 in;
  1005. int rc;
  1006. rc = smap_verdict_func(psock, skb);
  1007. switch (rc) {
  1008. case __SK_REDIRECT:
  1009. sk = do_sk_redirect_map(skb);
  1010. if (!sk) {
  1011. kfree_skb(skb);
  1012. break;
  1013. }
  1014. peer = smap_psock_sk(sk);
  1015. in = (TCP_SKB_CB(skb)->bpf.flags) & BPF_F_INGRESS;
  1016. if (unlikely(!peer || sock_flag(sk, SOCK_DEAD) ||
  1017. !test_bit(SMAP_TX_RUNNING, &peer->state))) {
  1018. kfree_skb(skb);
  1019. break;
  1020. }
  1021. if (!in && sock_writeable(sk)) {
  1022. skb_set_owner_w(skb, sk);
  1023. skb_queue_tail(&peer->rxqueue, skb);
  1024. schedule_work(&peer->tx_work);
  1025. break;
  1026. } else if (in &&
  1027. atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) {
  1028. skb_queue_tail(&peer->rxqueue, skb);
  1029. schedule_work(&peer->tx_work);
  1030. break;
  1031. }
  1032. /* Fall through and free skb otherwise */
  1033. case __SK_DROP:
  1034. default:
  1035. kfree_skb(skb);
  1036. }
  1037. }
  1038. static void smap_report_sk_error(struct smap_psock *psock, int err)
  1039. {
  1040. struct sock *sk = psock->sock;
  1041. sk->sk_err = err;
  1042. sk->sk_error_report(sk);
  1043. }
  1044. static void smap_read_sock_strparser(struct strparser *strp,
  1045. struct sk_buff *skb)
  1046. {
  1047. struct smap_psock *psock;
  1048. rcu_read_lock();
  1049. psock = container_of(strp, struct smap_psock, strp);
  1050. smap_do_verdict(psock, skb);
  1051. rcu_read_unlock();
  1052. }
  1053. /* Called with lock held on socket */
  1054. static void smap_data_ready(struct sock *sk)
  1055. {
  1056. struct smap_psock *psock;
  1057. rcu_read_lock();
  1058. psock = smap_psock_sk(sk);
  1059. if (likely(psock)) {
  1060. write_lock_bh(&sk->sk_callback_lock);
  1061. strp_data_ready(&psock->strp);
  1062. write_unlock_bh(&sk->sk_callback_lock);
  1063. }
  1064. rcu_read_unlock();
  1065. }
  1066. static void smap_tx_work(struct work_struct *w)
  1067. {
  1068. struct smap_psock *psock;
  1069. struct sk_buff *skb;
  1070. int rem, off, n;
  1071. psock = container_of(w, struct smap_psock, tx_work);
  1072. /* lock sock to avoid losing sk_socket at some point during loop */
  1073. lock_sock(psock->sock);
  1074. if (psock->save_skb) {
  1075. skb = psock->save_skb;
  1076. rem = psock->save_rem;
  1077. off = psock->save_off;
  1078. psock->save_skb = NULL;
  1079. goto start;
  1080. }
  1081. while ((skb = skb_dequeue(&psock->rxqueue))) {
  1082. __u32 flags;
  1083. rem = skb->len;
  1084. off = 0;
  1085. start:
  1086. flags = (TCP_SKB_CB(skb)->bpf.flags) & BPF_F_INGRESS;
  1087. do {
  1088. if (likely(psock->sock->sk_socket)) {
  1089. if (flags)
  1090. n = smap_do_ingress(psock, skb);
  1091. else
  1092. n = skb_send_sock_locked(psock->sock,
  1093. skb, off, rem);
  1094. } else {
  1095. n = -EINVAL;
  1096. }
  1097. if (n <= 0) {
  1098. if (n == -EAGAIN) {
  1099. /* Retry when space is available */
  1100. psock->save_skb = skb;
  1101. psock->save_rem = rem;
  1102. psock->save_off = off;
  1103. goto out;
  1104. }
  1105. /* Hard errors break pipe and stop xmit */
  1106. smap_report_sk_error(psock, n ? -n : EPIPE);
  1107. clear_bit(SMAP_TX_RUNNING, &psock->state);
  1108. kfree_skb(skb);
  1109. goto out;
  1110. }
  1111. rem -= n;
  1112. off += n;
  1113. } while (rem);
  1114. if (!flags)
  1115. kfree_skb(skb);
  1116. }
  1117. out:
  1118. release_sock(psock->sock);
  1119. }
  1120. static void smap_write_space(struct sock *sk)
  1121. {
  1122. struct smap_psock *psock;
  1123. rcu_read_lock();
  1124. psock = smap_psock_sk(sk);
  1125. if (likely(psock && test_bit(SMAP_TX_RUNNING, &psock->state)))
  1126. schedule_work(&psock->tx_work);
  1127. rcu_read_unlock();
  1128. }
  1129. static void smap_stop_sock(struct smap_psock *psock, struct sock *sk)
  1130. {
  1131. if (!psock->strp_enabled)
  1132. return;
  1133. sk->sk_data_ready = psock->save_data_ready;
  1134. sk->sk_write_space = psock->save_write_space;
  1135. psock->save_data_ready = NULL;
  1136. psock->save_write_space = NULL;
  1137. strp_stop(&psock->strp);
  1138. psock->strp_enabled = false;
  1139. }
  1140. static void smap_destroy_psock(struct rcu_head *rcu)
  1141. {
  1142. struct smap_psock *psock = container_of(rcu,
  1143. struct smap_psock, rcu);
  1144. /* Now that a grace period has passed there is no longer
  1145. * any reference to this sock in the sockmap so we can
  1146. * destroy the psock, strparser, and bpf programs. But,
  1147. * because we use workqueue sync operations we can not
  1148. * do it in rcu context
  1149. */
  1150. schedule_work(&psock->gc_work);
  1151. }
  1152. static void smap_release_sock(struct smap_psock *psock, struct sock *sock)
  1153. {
  1154. if (refcount_dec_and_test(&psock->refcnt)) {
  1155. tcp_cleanup_ulp(sock);
  1156. smap_stop_sock(psock, sock);
  1157. clear_bit(SMAP_TX_RUNNING, &psock->state);
  1158. rcu_assign_sk_user_data(sock, NULL);
  1159. call_rcu_sched(&psock->rcu, smap_destroy_psock);
  1160. }
  1161. }
  1162. static int smap_parse_func_strparser(struct strparser *strp,
  1163. struct sk_buff *skb)
  1164. {
  1165. struct smap_psock *psock;
  1166. struct bpf_prog *prog;
  1167. int rc;
  1168. rcu_read_lock();
  1169. psock = container_of(strp, struct smap_psock, strp);
  1170. prog = READ_ONCE(psock->bpf_parse);
  1171. if (unlikely(!prog)) {
  1172. rcu_read_unlock();
  1173. return skb->len;
  1174. }
  1175. /* Attach socket for bpf program to use if needed we can do this
  1176. * because strparser clones the skb before handing it to a upper
  1177. * layer, meaning skb_orphan has been called. We NULL sk on the
  1178. * way out to ensure we don't trigger a BUG_ON in skb/sk operations
  1179. * later and because we are not charging the memory of this skb to
  1180. * any socket yet.
  1181. */
  1182. skb->sk = psock->sock;
  1183. bpf_compute_data_pointers(skb);
  1184. rc = (*prog->bpf_func)(skb, prog->insnsi);
  1185. skb->sk = NULL;
  1186. rcu_read_unlock();
  1187. return rc;
  1188. }
  1189. static int smap_read_sock_done(struct strparser *strp, int err)
  1190. {
  1191. return err;
  1192. }
  1193. static int smap_init_sock(struct smap_psock *psock,
  1194. struct sock *sk)
  1195. {
  1196. static const struct strp_callbacks cb = {
  1197. .rcv_msg = smap_read_sock_strparser,
  1198. .parse_msg = smap_parse_func_strparser,
  1199. .read_sock_done = smap_read_sock_done,
  1200. };
  1201. return strp_init(&psock->strp, sk, &cb);
  1202. }
  1203. static void smap_init_progs(struct smap_psock *psock,
  1204. struct bpf_prog *verdict,
  1205. struct bpf_prog *parse)
  1206. {
  1207. struct bpf_prog *orig_parse, *orig_verdict;
  1208. orig_parse = xchg(&psock->bpf_parse, parse);
  1209. orig_verdict = xchg(&psock->bpf_verdict, verdict);
  1210. if (orig_verdict)
  1211. bpf_prog_put(orig_verdict);
  1212. if (orig_parse)
  1213. bpf_prog_put(orig_parse);
  1214. }
  1215. static void smap_start_sock(struct smap_psock *psock, struct sock *sk)
  1216. {
  1217. if (sk->sk_data_ready == smap_data_ready)
  1218. return;
  1219. psock->save_data_ready = sk->sk_data_ready;
  1220. psock->save_write_space = sk->sk_write_space;
  1221. sk->sk_data_ready = smap_data_ready;
  1222. sk->sk_write_space = smap_write_space;
  1223. psock->strp_enabled = true;
  1224. }
  1225. static void sock_map_remove_complete(struct bpf_stab *stab)
  1226. {
  1227. bpf_map_area_free(stab->sock_map);
  1228. kfree(stab);
  1229. }
  1230. static void smap_gc_work(struct work_struct *w)
  1231. {
  1232. struct smap_psock_map_entry *e, *tmp;
  1233. struct sk_msg_buff *md, *mtmp;
  1234. struct smap_psock *psock;
  1235. psock = container_of(w, struct smap_psock, gc_work);
  1236. /* no callback lock needed because we already detached sockmap ops */
  1237. if (psock->strp_enabled)
  1238. strp_done(&psock->strp);
  1239. cancel_work_sync(&psock->tx_work);
  1240. __skb_queue_purge(&psock->rxqueue);
  1241. /* At this point all strparser and xmit work must be complete */
  1242. if (psock->bpf_parse)
  1243. bpf_prog_put(psock->bpf_parse);
  1244. if (psock->bpf_verdict)
  1245. bpf_prog_put(psock->bpf_verdict);
  1246. if (psock->bpf_tx_msg)
  1247. bpf_prog_put(psock->bpf_tx_msg);
  1248. if (psock->cork) {
  1249. free_start_sg(psock->sock, psock->cork);
  1250. kfree(psock->cork);
  1251. }
  1252. list_for_each_entry_safe(md, mtmp, &psock->ingress, list) {
  1253. list_del(&md->list);
  1254. free_start_sg(psock->sock, md);
  1255. kfree(md);
  1256. }
  1257. list_for_each_entry_safe(e, tmp, &psock->maps, list) {
  1258. list_del(&e->list);
  1259. kfree(e);
  1260. }
  1261. if (psock->sk_redir)
  1262. sock_put(psock->sk_redir);
  1263. sock_put(psock->sock);
  1264. kfree(psock);
  1265. }
  1266. static struct smap_psock *smap_init_psock(struct sock *sock, int node)
  1267. {
  1268. struct smap_psock *psock;
  1269. psock = kzalloc_node(sizeof(struct smap_psock),
  1270. GFP_ATOMIC | __GFP_NOWARN,
  1271. node);
  1272. if (!psock)
  1273. return ERR_PTR(-ENOMEM);
  1274. psock->eval = __SK_NONE;
  1275. psock->sock = sock;
  1276. skb_queue_head_init(&psock->rxqueue);
  1277. INIT_WORK(&psock->tx_work, smap_tx_work);
  1278. INIT_WORK(&psock->gc_work, smap_gc_work);
  1279. INIT_LIST_HEAD(&psock->maps);
  1280. INIT_LIST_HEAD(&psock->ingress);
  1281. refcount_set(&psock->refcnt, 1);
  1282. rcu_assign_sk_user_data(sock, psock);
  1283. sock_hold(sock);
  1284. return psock;
  1285. }
  1286. static struct bpf_map *sock_map_alloc(union bpf_attr *attr)
  1287. {
  1288. struct bpf_stab *stab;
  1289. u64 cost;
  1290. int err;
  1291. if (!capable(CAP_NET_ADMIN))
  1292. return ERR_PTR(-EPERM);
  1293. /* check sanity of attributes */
  1294. if (attr->max_entries == 0 || attr->key_size != 4 ||
  1295. attr->value_size != 4 || attr->map_flags & ~SOCK_CREATE_FLAG_MASK)
  1296. return ERR_PTR(-EINVAL);
  1297. err = bpf_tcp_ulp_register();
  1298. if (err && err != -EEXIST)
  1299. return ERR_PTR(err);
  1300. stab = kzalloc(sizeof(*stab), GFP_USER);
  1301. if (!stab)
  1302. return ERR_PTR(-ENOMEM);
  1303. bpf_map_init_from_attr(&stab->map, attr);
  1304. /* make sure page count doesn't overflow */
  1305. cost = (u64) stab->map.max_entries * sizeof(struct sock *);
  1306. err = -EINVAL;
  1307. if (cost >= U32_MAX - PAGE_SIZE)
  1308. goto free_stab;
  1309. stab->map.pages = round_up(cost, PAGE_SIZE) >> PAGE_SHIFT;
  1310. /* if map size is larger than memlock limit, reject it early */
  1311. err = bpf_map_precharge_memlock(stab->map.pages);
  1312. if (err)
  1313. goto free_stab;
  1314. err = -ENOMEM;
  1315. stab->sock_map = bpf_map_area_alloc(stab->map.max_entries *
  1316. sizeof(struct sock *),
  1317. stab->map.numa_node);
  1318. if (!stab->sock_map)
  1319. goto free_stab;
  1320. return &stab->map;
  1321. free_stab:
  1322. kfree(stab);
  1323. return ERR_PTR(err);
  1324. }
  1325. static void smap_list_remove(struct smap_psock *psock,
  1326. struct sock **entry,
  1327. struct htab_elem *hash_link)
  1328. {
  1329. struct smap_psock_map_entry *e, *tmp;
  1330. list_for_each_entry_safe(e, tmp, &psock->maps, list) {
  1331. if (e->entry == entry || e->hash_link == hash_link) {
  1332. list_del(&e->list);
  1333. break;
  1334. }
  1335. }
  1336. }
  1337. static void sock_map_free(struct bpf_map *map)
  1338. {
  1339. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1340. int i;
  1341. synchronize_rcu();
  1342. /* At this point no update, lookup or delete operations can happen.
  1343. * However, be aware we can still get a socket state event updates,
  1344. * and data ready callabacks that reference the psock from sk_user_data
  1345. * Also psock worker threads are still in-flight. So smap_release_sock
  1346. * will only free the psock after cancel_sync on the worker threads
  1347. * and a grace period expire to ensure psock is really safe to remove.
  1348. */
  1349. rcu_read_lock();
  1350. for (i = 0; i < stab->map.max_entries; i++) {
  1351. struct smap_psock *psock;
  1352. struct sock *sock;
  1353. sock = xchg(&stab->sock_map[i], NULL);
  1354. if (!sock)
  1355. continue;
  1356. write_lock_bh(&sock->sk_callback_lock);
  1357. psock = smap_psock_sk(sock);
  1358. /* This check handles a racing sock event that can get the
  1359. * sk_callback_lock before this case but after xchg happens
  1360. * causing the refcnt to hit zero and sock user data (psock)
  1361. * to be null and queued for garbage collection.
  1362. */
  1363. if (likely(psock)) {
  1364. smap_list_remove(psock, &stab->sock_map[i], NULL);
  1365. smap_release_sock(psock, sock);
  1366. }
  1367. write_unlock_bh(&sock->sk_callback_lock);
  1368. }
  1369. rcu_read_unlock();
  1370. sock_map_remove_complete(stab);
  1371. }
  1372. static int sock_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
  1373. {
  1374. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1375. u32 i = key ? *(u32 *)key : U32_MAX;
  1376. u32 *next = (u32 *)next_key;
  1377. if (i >= stab->map.max_entries) {
  1378. *next = 0;
  1379. return 0;
  1380. }
  1381. if (i == stab->map.max_entries - 1)
  1382. return -ENOENT;
  1383. *next = i + 1;
  1384. return 0;
  1385. }
  1386. struct sock *__sock_map_lookup_elem(struct bpf_map *map, u32 key)
  1387. {
  1388. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1389. if (key >= map->max_entries)
  1390. return NULL;
  1391. return READ_ONCE(stab->sock_map[key]);
  1392. }
  1393. static int sock_map_delete_elem(struct bpf_map *map, void *key)
  1394. {
  1395. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1396. struct smap_psock *psock;
  1397. int k = *(u32 *)key;
  1398. struct sock *sock;
  1399. if (k >= map->max_entries)
  1400. return -EINVAL;
  1401. sock = xchg(&stab->sock_map[k], NULL);
  1402. if (!sock)
  1403. return -EINVAL;
  1404. write_lock_bh(&sock->sk_callback_lock);
  1405. psock = smap_psock_sk(sock);
  1406. if (!psock)
  1407. goto out;
  1408. if (psock->bpf_parse)
  1409. smap_stop_sock(psock, sock);
  1410. smap_list_remove(psock, &stab->sock_map[k], NULL);
  1411. smap_release_sock(psock, sock);
  1412. out:
  1413. write_unlock_bh(&sock->sk_callback_lock);
  1414. return 0;
  1415. }
  1416. /* Locking notes: Concurrent updates, deletes, and lookups are allowed and are
  1417. * done inside rcu critical sections. This ensures on updates that the psock
  1418. * will not be released via smap_release_sock() until concurrent updates/deletes
  1419. * complete. All operations operate on sock_map using cmpxchg and xchg
  1420. * operations to ensure we do not get stale references. Any reads into the
  1421. * map must be done with READ_ONCE() because of this.
  1422. *
  1423. * A psock is destroyed via call_rcu and after any worker threads are cancelled
  1424. * and syncd so we are certain all references from the update/lookup/delete
  1425. * operations as well as references in the data path are no longer in use.
  1426. *
  1427. * Psocks may exist in multiple maps, but only a single set of parse/verdict
  1428. * programs may be inherited from the maps it belongs to. A reference count
  1429. * is kept with the total number of references to the psock from all maps. The
  1430. * psock will not be released until this reaches zero. The psock and sock
  1431. * user data data use the sk_callback_lock to protect critical data structures
  1432. * from concurrent access. This allows us to avoid two updates from modifying
  1433. * the user data in sock and the lock is required anyways for modifying
  1434. * callbacks, we simply increase its scope slightly.
  1435. *
  1436. * Rules to follow,
  1437. * - psock must always be read inside RCU critical section
  1438. * - sk_user_data must only be modified inside sk_callback_lock and read
  1439. * inside RCU critical section.
  1440. * - psock->maps list must only be read & modified inside sk_callback_lock
  1441. * - sock_map must use READ_ONCE and (cmp)xchg operations
  1442. * - BPF verdict/parse programs must use READ_ONCE and xchg operations
  1443. */
  1444. static int __sock_map_ctx_update_elem(struct bpf_map *map,
  1445. struct bpf_sock_progs *progs,
  1446. struct sock *sock,
  1447. struct sock **map_link,
  1448. void *key)
  1449. {
  1450. struct bpf_prog *verdict, *parse, *tx_msg;
  1451. struct smap_psock_map_entry *e = NULL;
  1452. struct smap_psock *psock;
  1453. bool new = false;
  1454. int err = 0;
  1455. /* 1. If sock map has BPF programs those will be inherited by the
  1456. * sock being added. If the sock is already attached to BPF programs
  1457. * this results in an error.
  1458. */
  1459. verdict = READ_ONCE(progs->bpf_verdict);
  1460. parse = READ_ONCE(progs->bpf_parse);
  1461. tx_msg = READ_ONCE(progs->bpf_tx_msg);
  1462. if (parse && verdict) {
  1463. /* bpf prog refcnt may be zero if a concurrent attach operation
  1464. * removes the program after the above READ_ONCE() but before
  1465. * we increment the refcnt. If this is the case abort with an
  1466. * error.
  1467. */
  1468. verdict = bpf_prog_inc_not_zero(progs->bpf_verdict);
  1469. if (IS_ERR(verdict))
  1470. return PTR_ERR(verdict);
  1471. parse = bpf_prog_inc_not_zero(progs->bpf_parse);
  1472. if (IS_ERR(parse)) {
  1473. bpf_prog_put(verdict);
  1474. return PTR_ERR(parse);
  1475. }
  1476. }
  1477. if (tx_msg) {
  1478. tx_msg = bpf_prog_inc_not_zero(progs->bpf_tx_msg);
  1479. if (IS_ERR(tx_msg)) {
  1480. if (verdict)
  1481. bpf_prog_put(verdict);
  1482. if (parse)
  1483. bpf_prog_put(parse);
  1484. return PTR_ERR(tx_msg);
  1485. }
  1486. }
  1487. write_lock_bh(&sock->sk_callback_lock);
  1488. psock = smap_psock_sk(sock);
  1489. /* 2. Do not allow inheriting programs if psock exists and has
  1490. * already inherited programs. This would create confusion on
  1491. * which parser/verdict program is running. If no psock exists
  1492. * create one. Inside sk_callback_lock to ensure concurrent create
  1493. * doesn't update user data.
  1494. */
  1495. if (psock) {
  1496. if (READ_ONCE(psock->bpf_parse) && parse) {
  1497. err = -EBUSY;
  1498. goto out_progs;
  1499. }
  1500. if (READ_ONCE(psock->bpf_tx_msg) && tx_msg) {
  1501. err = -EBUSY;
  1502. goto out_progs;
  1503. }
  1504. if (!refcount_inc_not_zero(&psock->refcnt)) {
  1505. err = -EAGAIN;
  1506. goto out_progs;
  1507. }
  1508. } else {
  1509. psock = smap_init_psock(sock, map->numa_node);
  1510. if (IS_ERR(psock)) {
  1511. err = PTR_ERR(psock);
  1512. goto out_progs;
  1513. }
  1514. set_bit(SMAP_TX_RUNNING, &psock->state);
  1515. new = true;
  1516. }
  1517. if (map_link) {
  1518. e = kzalloc(sizeof(*e), GFP_ATOMIC | __GFP_NOWARN);
  1519. if (!e) {
  1520. err = -ENOMEM;
  1521. goto out_progs;
  1522. }
  1523. }
  1524. /* 3. At this point we have a reference to a valid psock that is
  1525. * running. Attach any BPF programs needed.
  1526. */
  1527. if (tx_msg)
  1528. bpf_tcp_msg_add(psock, sock, tx_msg);
  1529. if (new) {
  1530. err = tcp_set_ulp_id(sock, TCP_ULP_BPF);
  1531. if (err)
  1532. goto out_free;
  1533. }
  1534. if (parse && verdict && !psock->strp_enabled) {
  1535. err = smap_init_sock(psock, sock);
  1536. if (err)
  1537. goto out_free;
  1538. smap_init_progs(psock, verdict, parse);
  1539. smap_start_sock(psock, sock);
  1540. }
  1541. /* 4. Place psock in sockmap for use and stop any programs on
  1542. * the old sock assuming its not the same sock we are replacing
  1543. * it with. Because we can only have a single set of programs if
  1544. * old_sock has a strp we can stop it.
  1545. */
  1546. if (map_link) {
  1547. e->entry = map_link;
  1548. list_add_tail(&e->list, &psock->maps);
  1549. }
  1550. write_unlock_bh(&sock->sk_callback_lock);
  1551. return err;
  1552. out_free:
  1553. smap_release_sock(psock, sock);
  1554. out_progs:
  1555. if (verdict)
  1556. bpf_prog_put(verdict);
  1557. if (parse)
  1558. bpf_prog_put(parse);
  1559. if (tx_msg)
  1560. bpf_prog_put(tx_msg);
  1561. write_unlock_bh(&sock->sk_callback_lock);
  1562. kfree(e);
  1563. return err;
  1564. }
  1565. static int sock_map_ctx_update_elem(struct bpf_sock_ops_kern *skops,
  1566. struct bpf_map *map,
  1567. void *key, u64 flags)
  1568. {
  1569. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1570. struct bpf_sock_progs *progs = &stab->progs;
  1571. struct sock *osock, *sock;
  1572. u32 i = *(u32 *)key;
  1573. int err;
  1574. if (unlikely(flags > BPF_EXIST))
  1575. return -EINVAL;
  1576. if (unlikely(i >= stab->map.max_entries))
  1577. return -E2BIG;
  1578. sock = READ_ONCE(stab->sock_map[i]);
  1579. if (flags == BPF_EXIST && !sock)
  1580. return -ENOENT;
  1581. else if (flags == BPF_NOEXIST && sock)
  1582. return -EEXIST;
  1583. sock = skops->sk;
  1584. err = __sock_map_ctx_update_elem(map, progs, sock, &stab->sock_map[i],
  1585. key);
  1586. if (err)
  1587. goto out;
  1588. osock = xchg(&stab->sock_map[i], sock);
  1589. if (osock) {
  1590. struct smap_psock *opsock = smap_psock_sk(osock);
  1591. write_lock_bh(&osock->sk_callback_lock);
  1592. smap_list_remove(opsock, &stab->sock_map[i], NULL);
  1593. smap_release_sock(opsock, osock);
  1594. write_unlock_bh(&osock->sk_callback_lock);
  1595. }
  1596. out:
  1597. return err;
  1598. }
  1599. int sock_map_prog(struct bpf_map *map, struct bpf_prog *prog, u32 type)
  1600. {
  1601. struct bpf_sock_progs *progs;
  1602. struct bpf_prog *orig;
  1603. if (map->map_type == BPF_MAP_TYPE_SOCKMAP) {
  1604. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1605. progs = &stab->progs;
  1606. } else if (map->map_type == BPF_MAP_TYPE_SOCKHASH) {
  1607. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  1608. progs = &htab->progs;
  1609. } else {
  1610. return -EINVAL;
  1611. }
  1612. switch (type) {
  1613. case BPF_SK_MSG_VERDICT:
  1614. orig = xchg(&progs->bpf_tx_msg, prog);
  1615. break;
  1616. case BPF_SK_SKB_STREAM_PARSER:
  1617. orig = xchg(&progs->bpf_parse, prog);
  1618. break;
  1619. case BPF_SK_SKB_STREAM_VERDICT:
  1620. orig = xchg(&progs->bpf_verdict, prog);
  1621. break;
  1622. default:
  1623. return -EOPNOTSUPP;
  1624. }
  1625. if (orig)
  1626. bpf_prog_put(orig);
  1627. return 0;
  1628. }
  1629. static void *sock_map_lookup(struct bpf_map *map, void *key)
  1630. {
  1631. return NULL;
  1632. }
  1633. static int sock_map_update_elem(struct bpf_map *map,
  1634. void *key, void *value, u64 flags)
  1635. {
  1636. struct bpf_sock_ops_kern skops;
  1637. u32 fd = *(u32 *)value;
  1638. struct socket *socket;
  1639. int err;
  1640. socket = sockfd_lookup(fd, &err);
  1641. if (!socket)
  1642. return err;
  1643. skops.sk = socket->sk;
  1644. if (!skops.sk) {
  1645. fput(socket->file);
  1646. return -EINVAL;
  1647. }
  1648. if (skops.sk->sk_type != SOCK_STREAM ||
  1649. skops.sk->sk_protocol != IPPROTO_TCP) {
  1650. fput(socket->file);
  1651. return -EOPNOTSUPP;
  1652. }
  1653. err = sock_map_ctx_update_elem(&skops, map, key, flags);
  1654. fput(socket->file);
  1655. return err;
  1656. }
  1657. static void sock_map_release(struct bpf_map *map)
  1658. {
  1659. struct bpf_sock_progs *progs;
  1660. struct bpf_prog *orig;
  1661. if (map->map_type == BPF_MAP_TYPE_SOCKMAP) {
  1662. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1663. progs = &stab->progs;
  1664. } else {
  1665. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  1666. progs = &htab->progs;
  1667. }
  1668. orig = xchg(&progs->bpf_parse, NULL);
  1669. if (orig)
  1670. bpf_prog_put(orig);
  1671. orig = xchg(&progs->bpf_verdict, NULL);
  1672. if (orig)
  1673. bpf_prog_put(orig);
  1674. orig = xchg(&progs->bpf_tx_msg, NULL);
  1675. if (orig)
  1676. bpf_prog_put(orig);
  1677. }
  1678. static struct bpf_map *sock_hash_alloc(union bpf_attr *attr)
  1679. {
  1680. struct bpf_htab *htab;
  1681. int i, err;
  1682. u64 cost;
  1683. if (!capable(CAP_NET_ADMIN))
  1684. return ERR_PTR(-EPERM);
  1685. /* check sanity of attributes */
  1686. if (attr->max_entries == 0 || attr->value_size != 4 ||
  1687. attr->map_flags & ~SOCK_CREATE_FLAG_MASK)
  1688. return ERR_PTR(-EINVAL);
  1689. if (attr->key_size > MAX_BPF_STACK)
  1690. /* eBPF programs initialize keys on stack, so they cannot be
  1691. * larger than max stack size
  1692. */
  1693. return ERR_PTR(-E2BIG);
  1694. err = bpf_tcp_ulp_register();
  1695. if (err && err != -EEXIST)
  1696. return ERR_PTR(err);
  1697. htab = kzalloc(sizeof(*htab), GFP_USER);
  1698. if (!htab)
  1699. return ERR_PTR(-ENOMEM);
  1700. bpf_map_init_from_attr(&htab->map, attr);
  1701. htab->n_buckets = roundup_pow_of_two(htab->map.max_entries);
  1702. htab->elem_size = sizeof(struct htab_elem) +
  1703. round_up(htab->map.key_size, 8);
  1704. err = -EINVAL;
  1705. if (htab->n_buckets == 0 ||
  1706. htab->n_buckets > U32_MAX / sizeof(struct bucket))
  1707. goto free_htab;
  1708. cost = (u64) htab->n_buckets * sizeof(struct bucket) +
  1709. (u64) htab->elem_size * htab->map.max_entries;
  1710. if (cost >= U32_MAX - PAGE_SIZE)
  1711. goto free_htab;
  1712. htab->map.pages = round_up(cost, PAGE_SIZE) >> PAGE_SHIFT;
  1713. err = bpf_map_precharge_memlock(htab->map.pages);
  1714. if (err)
  1715. goto free_htab;
  1716. err = -ENOMEM;
  1717. htab->buckets = bpf_map_area_alloc(
  1718. htab->n_buckets * sizeof(struct bucket),
  1719. htab->map.numa_node);
  1720. if (!htab->buckets)
  1721. goto free_htab;
  1722. for (i = 0; i < htab->n_buckets; i++) {
  1723. INIT_HLIST_HEAD(&htab->buckets[i].head);
  1724. raw_spin_lock_init(&htab->buckets[i].lock);
  1725. }
  1726. return &htab->map;
  1727. free_htab:
  1728. kfree(htab);
  1729. return ERR_PTR(err);
  1730. }
  1731. static inline struct bucket *__select_bucket(struct bpf_htab *htab, u32 hash)
  1732. {
  1733. return &htab->buckets[hash & (htab->n_buckets - 1)];
  1734. }
  1735. static inline struct hlist_head *select_bucket(struct bpf_htab *htab, u32 hash)
  1736. {
  1737. return &__select_bucket(htab, hash)->head;
  1738. }
  1739. static void sock_hash_free(struct bpf_map *map)
  1740. {
  1741. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  1742. int i;
  1743. synchronize_rcu();
  1744. /* At this point no update, lookup or delete operations can happen.
  1745. * However, be aware we can still get a socket state event updates,
  1746. * and data ready callabacks that reference the psock from sk_user_data
  1747. * Also psock worker threads are still in-flight. So smap_release_sock
  1748. * will only free the psock after cancel_sync on the worker threads
  1749. * and a grace period expire to ensure psock is really safe to remove.
  1750. */
  1751. rcu_read_lock();
  1752. for (i = 0; i < htab->n_buckets; i++) {
  1753. struct hlist_head *head = select_bucket(htab, i);
  1754. struct hlist_node *n;
  1755. struct htab_elem *l;
  1756. hlist_for_each_entry_safe(l, n, head, hash_node) {
  1757. struct sock *sock = l->sk;
  1758. struct smap_psock *psock;
  1759. hlist_del_rcu(&l->hash_node);
  1760. write_lock_bh(&sock->sk_callback_lock);
  1761. psock = smap_psock_sk(sock);
  1762. /* This check handles a racing sock event that can get
  1763. * the sk_callback_lock before this case but after xchg
  1764. * causing the refcnt to hit zero and sock user data
  1765. * (psock) to be null and queued for garbage collection.
  1766. */
  1767. if (likely(psock)) {
  1768. smap_list_remove(psock, NULL, l);
  1769. smap_release_sock(psock, sock);
  1770. }
  1771. write_unlock_bh(&sock->sk_callback_lock);
  1772. kfree(l);
  1773. }
  1774. }
  1775. rcu_read_unlock();
  1776. bpf_map_area_free(htab->buckets);
  1777. kfree(htab);
  1778. }
  1779. static struct htab_elem *alloc_sock_hash_elem(struct bpf_htab *htab,
  1780. void *key, u32 key_size, u32 hash,
  1781. struct sock *sk,
  1782. struct htab_elem *old_elem)
  1783. {
  1784. struct htab_elem *l_new;
  1785. if (atomic_inc_return(&htab->count) > htab->map.max_entries) {
  1786. if (!old_elem) {
  1787. atomic_dec(&htab->count);
  1788. return ERR_PTR(-E2BIG);
  1789. }
  1790. }
  1791. l_new = kmalloc_node(htab->elem_size, GFP_ATOMIC | __GFP_NOWARN,
  1792. htab->map.numa_node);
  1793. if (!l_new)
  1794. return ERR_PTR(-ENOMEM);
  1795. memcpy(l_new->key, key, key_size);
  1796. l_new->sk = sk;
  1797. l_new->hash = hash;
  1798. return l_new;
  1799. }
  1800. static struct htab_elem *lookup_elem_raw(struct hlist_head *head,
  1801. u32 hash, void *key, u32 key_size)
  1802. {
  1803. struct htab_elem *l;
  1804. hlist_for_each_entry_rcu(l, head, hash_node) {
  1805. if (l->hash == hash && !memcmp(&l->key, key, key_size))
  1806. return l;
  1807. }
  1808. return NULL;
  1809. }
  1810. static inline u32 htab_map_hash(const void *key, u32 key_len)
  1811. {
  1812. return jhash(key, key_len, 0);
  1813. }
  1814. static int sock_hash_get_next_key(struct bpf_map *map,
  1815. void *key, void *next_key)
  1816. {
  1817. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  1818. struct htab_elem *l, *next_l;
  1819. struct hlist_head *h;
  1820. u32 hash, key_size;
  1821. int i = 0;
  1822. WARN_ON_ONCE(!rcu_read_lock_held());
  1823. key_size = map->key_size;
  1824. if (!key)
  1825. goto find_first_elem;
  1826. hash = htab_map_hash(key, key_size);
  1827. h = select_bucket(htab, hash);
  1828. l = lookup_elem_raw(h, hash, key, key_size);
  1829. if (!l)
  1830. goto find_first_elem;
  1831. next_l = hlist_entry_safe(
  1832. rcu_dereference_raw(hlist_next_rcu(&l->hash_node)),
  1833. struct htab_elem, hash_node);
  1834. if (next_l) {
  1835. memcpy(next_key, next_l->key, key_size);
  1836. return 0;
  1837. }
  1838. /* no more elements in this hash list, go to the next bucket */
  1839. i = hash & (htab->n_buckets - 1);
  1840. i++;
  1841. find_first_elem:
  1842. /* iterate over buckets */
  1843. for (; i < htab->n_buckets; i++) {
  1844. h = select_bucket(htab, i);
  1845. /* pick first element in the bucket */
  1846. next_l = hlist_entry_safe(
  1847. rcu_dereference_raw(hlist_first_rcu(h)),
  1848. struct htab_elem, hash_node);
  1849. if (next_l) {
  1850. /* if it's not empty, just return it */
  1851. memcpy(next_key, next_l->key, key_size);
  1852. return 0;
  1853. }
  1854. }
  1855. /* iterated over all buckets and all elements */
  1856. return -ENOENT;
  1857. }
  1858. static int sock_hash_ctx_update_elem(struct bpf_sock_ops_kern *skops,
  1859. struct bpf_map *map,
  1860. void *key, u64 map_flags)
  1861. {
  1862. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  1863. struct bpf_sock_progs *progs = &htab->progs;
  1864. struct htab_elem *l_new = NULL, *l_old;
  1865. struct smap_psock_map_entry *e = NULL;
  1866. struct hlist_head *head;
  1867. struct smap_psock *psock;
  1868. u32 key_size, hash;
  1869. struct sock *sock;
  1870. struct bucket *b;
  1871. int err;
  1872. sock = skops->sk;
  1873. if (sock->sk_type != SOCK_STREAM ||
  1874. sock->sk_protocol != IPPROTO_TCP)
  1875. return -EOPNOTSUPP;
  1876. if (unlikely(map_flags > BPF_EXIST))
  1877. return -EINVAL;
  1878. e = kzalloc(sizeof(*e), GFP_ATOMIC | __GFP_NOWARN);
  1879. if (!e)
  1880. return -ENOMEM;
  1881. WARN_ON_ONCE(!rcu_read_lock_held());
  1882. key_size = map->key_size;
  1883. hash = htab_map_hash(key, key_size);
  1884. b = __select_bucket(htab, hash);
  1885. head = &b->head;
  1886. err = __sock_map_ctx_update_elem(map, progs, sock, NULL, key);
  1887. if (err)
  1888. goto err;
  1889. /* bpf_map_update_elem() can be called in_irq() */
  1890. raw_spin_lock_bh(&b->lock);
  1891. l_old = lookup_elem_raw(head, hash, key, key_size);
  1892. if (l_old && map_flags == BPF_NOEXIST) {
  1893. err = -EEXIST;
  1894. goto bucket_err;
  1895. }
  1896. if (!l_old && map_flags == BPF_EXIST) {
  1897. err = -ENOENT;
  1898. goto bucket_err;
  1899. }
  1900. l_new = alloc_sock_hash_elem(htab, key, key_size, hash, sock, l_old);
  1901. if (IS_ERR(l_new)) {
  1902. err = PTR_ERR(l_new);
  1903. goto bucket_err;
  1904. }
  1905. psock = smap_psock_sk(sock);
  1906. if (unlikely(!psock)) {
  1907. err = -EINVAL;
  1908. goto bucket_err;
  1909. }
  1910. e->hash_link = l_new;
  1911. e->htab = container_of(map, struct bpf_htab, map);
  1912. list_add_tail(&e->list, &psock->maps);
  1913. /* add new element to the head of the list, so that
  1914. * concurrent search will find it before old elem
  1915. */
  1916. hlist_add_head_rcu(&l_new->hash_node, head);
  1917. if (l_old) {
  1918. psock = smap_psock_sk(l_old->sk);
  1919. hlist_del_rcu(&l_old->hash_node);
  1920. smap_list_remove(psock, NULL, l_old);
  1921. smap_release_sock(psock, l_old->sk);
  1922. free_htab_elem(htab, l_old);
  1923. }
  1924. raw_spin_unlock_bh(&b->lock);
  1925. return 0;
  1926. bucket_err:
  1927. raw_spin_unlock_bh(&b->lock);
  1928. err:
  1929. kfree(e);
  1930. psock = smap_psock_sk(sock);
  1931. if (psock)
  1932. smap_release_sock(psock, sock);
  1933. return err;
  1934. }
  1935. static int sock_hash_update_elem(struct bpf_map *map,
  1936. void *key, void *value, u64 flags)
  1937. {
  1938. struct bpf_sock_ops_kern skops;
  1939. u32 fd = *(u32 *)value;
  1940. struct socket *socket;
  1941. int err;
  1942. socket = sockfd_lookup(fd, &err);
  1943. if (!socket)
  1944. return err;
  1945. skops.sk = socket->sk;
  1946. if (!skops.sk) {
  1947. fput(socket->file);
  1948. return -EINVAL;
  1949. }
  1950. err = sock_hash_ctx_update_elem(&skops, map, key, flags);
  1951. fput(socket->file);
  1952. return err;
  1953. }
  1954. static int sock_hash_delete_elem(struct bpf_map *map, void *key)
  1955. {
  1956. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  1957. struct hlist_head *head;
  1958. struct bucket *b;
  1959. struct htab_elem *l;
  1960. u32 hash, key_size;
  1961. int ret = -ENOENT;
  1962. key_size = map->key_size;
  1963. hash = htab_map_hash(key, key_size);
  1964. b = __select_bucket(htab, hash);
  1965. head = &b->head;
  1966. raw_spin_lock_bh(&b->lock);
  1967. l = lookup_elem_raw(head, hash, key, key_size);
  1968. if (l) {
  1969. struct sock *sock = l->sk;
  1970. struct smap_psock *psock;
  1971. hlist_del_rcu(&l->hash_node);
  1972. write_lock_bh(&sock->sk_callback_lock);
  1973. psock = smap_psock_sk(sock);
  1974. /* This check handles a racing sock event that can get the
  1975. * sk_callback_lock before this case but after xchg happens
  1976. * causing the refcnt to hit zero and sock user data (psock)
  1977. * to be null and queued for garbage collection.
  1978. */
  1979. if (likely(psock)) {
  1980. smap_list_remove(psock, NULL, l);
  1981. smap_release_sock(psock, sock);
  1982. }
  1983. write_unlock_bh(&sock->sk_callback_lock);
  1984. free_htab_elem(htab, l);
  1985. ret = 0;
  1986. }
  1987. raw_spin_unlock_bh(&b->lock);
  1988. return ret;
  1989. }
  1990. struct sock *__sock_hash_lookup_elem(struct bpf_map *map, void *key)
  1991. {
  1992. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  1993. struct hlist_head *head;
  1994. struct htab_elem *l;
  1995. u32 key_size, hash;
  1996. struct bucket *b;
  1997. struct sock *sk;
  1998. key_size = map->key_size;
  1999. hash = htab_map_hash(key, key_size);
  2000. b = __select_bucket(htab, hash);
  2001. head = &b->head;
  2002. raw_spin_lock_bh(&b->lock);
  2003. l = lookup_elem_raw(head, hash, key, key_size);
  2004. sk = l ? l->sk : NULL;
  2005. raw_spin_unlock_bh(&b->lock);
  2006. return sk;
  2007. }
  2008. const struct bpf_map_ops sock_map_ops = {
  2009. .map_alloc = sock_map_alloc,
  2010. .map_free = sock_map_free,
  2011. .map_lookup_elem = sock_map_lookup,
  2012. .map_get_next_key = sock_map_get_next_key,
  2013. .map_update_elem = sock_map_update_elem,
  2014. .map_delete_elem = sock_map_delete_elem,
  2015. .map_release_uref = sock_map_release,
  2016. };
  2017. const struct bpf_map_ops sock_hash_ops = {
  2018. .map_alloc = sock_hash_alloc,
  2019. .map_free = sock_hash_free,
  2020. .map_lookup_elem = sock_map_lookup,
  2021. .map_get_next_key = sock_hash_get_next_key,
  2022. .map_update_elem = sock_hash_update_elem,
  2023. .map_delete_elem = sock_hash_delete_elem,
  2024. };
  2025. BPF_CALL_4(bpf_sock_map_update, struct bpf_sock_ops_kern *, bpf_sock,
  2026. struct bpf_map *, map, void *, key, u64, flags)
  2027. {
  2028. WARN_ON_ONCE(!rcu_read_lock_held());
  2029. return sock_map_ctx_update_elem(bpf_sock, map, key, flags);
  2030. }
  2031. const struct bpf_func_proto bpf_sock_map_update_proto = {
  2032. .func = bpf_sock_map_update,
  2033. .gpl_only = false,
  2034. .pkt_access = true,
  2035. .ret_type = RET_INTEGER,
  2036. .arg1_type = ARG_PTR_TO_CTX,
  2037. .arg2_type = ARG_CONST_MAP_PTR,
  2038. .arg3_type = ARG_PTR_TO_MAP_KEY,
  2039. .arg4_type = ARG_ANYTHING,
  2040. };
  2041. BPF_CALL_4(bpf_sock_hash_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_hash_ctx_update_elem(bpf_sock, map, key, flags);
  2046. }
  2047. const struct bpf_func_proto bpf_sock_hash_update_proto = {
  2048. .func = bpf_sock_hash_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. };