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