sockmap.c 59 KB

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