sockmap.c 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546
  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;
  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. goto out_err;
  951. }
  952. out_err:
  953. if (err < 0)
  954. err = sk_stream_error(sk, msg->msg_flags, err);
  955. out_cork:
  956. release_sock(sk);
  957. smap_release_sock(psock, sk);
  958. return copied ? copied : err;
  959. }
  960. static int bpf_tcp_sendpage(struct sock *sk, struct page *page,
  961. int offset, size_t size, int flags)
  962. {
  963. struct sk_msg_buff md = {0}, *m = NULL;
  964. int err = 0, copied = 0;
  965. struct smap_psock *psock;
  966. struct scatterlist *sg;
  967. bool enospc = false;
  968. rcu_read_lock();
  969. psock = smap_psock_sk(sk);
  970. if (unlikely(!psock))
  971. goto accept;
  972. if (!refcount_inc_not_zero(&psock->refcnt))
  973. goto accept;
  974. rcu_read_unlock();
  975. lock_sock(sk);
  976. if (psock->cork_bytes) {
  977. m = psock->cork;
  978. sg = &m->sg_data[m->sg_end];
  979. } else {
  980. m = &md;
  981. sg = m->sg_data;
  982. sg_init_marker(sg, MAX_SKB_FRAGS);
  983. }
  984. /* Catch case where ring is full and sendpage is stalled. */
  985. if (unlikely(m->sg_end == m->sg_start &&
  986. m->sg_data[m->sg_end].length))
  987. goto out_err;
  988. psock->sg_size += size;
  989. sg_set_page(sg, page, size, offset);
  990. get_page(page);
  991. m->sg_copy[m->sg_end] = true;
  992. sk_mem_charge(sk, size);
  993. m->sg_end++;
  994. copied = size;
  995. if (m->sg_end == MAX_SKB_FRAGS)
  996. m->sg_end = 0;
  997. if (m->sg_end == m->sg_start)
  998. enospc = true;
  999. if (psock->cork_bytes) {
  1000. if (size > psock->cork_bytes)
  1001. psock->cork_bytes = 0;
  1002. else
  1003. psock->cork_bytes -= size;
  1004. if (psock->cork_bytes && !enospc)
  1005. goto out_err;
  1006. /* All cork bytes accounted for re-run filter */
  1007. psock->eval = __SK_NONE;
  1008. psock->cork_bytes = 0;
  1009. }
  1010. err = bpf_exec_tx_verdict(psock, m, sk, &copied, flags);
  1011. out_err:
  1012. release_sock(sk);
  1013. smap_release_sock(psock, sk);
  1014. return copied ? copied : err;
  1015. accept:
  1016. rcu_read_unlock();
  1017. return tcp_sendpage(sk, page, offset, size, flags);
  1018. }
  1019. static void bpf_tcp_msg_add(struct smap_psock *psock,
  1020. struct sock *sk,
  1021. struct bpf_prog *tx_msg)
  1022. {
  1023. struct bpf_prog *orig_tx_msg;
  1024. orig_tx_msg = xchg(&psock->bpf_tx_msg, tx_msg);
  1025. if (orig_tx_msg)
  1026. bpf_prog_put(orig_tx_msg);
  1027. }
  1028. static int bpf_tcp_ulp_register(void)
  1029. {
  1030. build_protos(bpf_tcp_prots[SOCKMAP_IPV4], &tcp_prot);
  1031. /* Once BPF TX ULP is registered it is never unregistered. It
  1032. * will be in the ULP list for the lifetime of the system. Doing
  1033. * duplicate registers is not a problem.
  1034. */
  1035. return tcp_register_ulp(&bpf_tcp_ulp_ops);
  1036. }
  1037. static int smap_verdict_func(struct smap_psock *psock, struct sk_buff *skb)
  1038. {
  1039. struct bpf_prog *prog = READ_ONCE(psock->bpf_verdict);
  1040. int rc;
  1041. if (unlikely(!prog))
  1042. return __SK_DROP;
  1043. skb_orphan(skb);
  1044. /* We need to ensure that BPF metadata for maps is also cleared
  1045. * when we orphan the skb so that we don't have the possibility
  1046. * to reference a stale map.
  1047. */
  1048. TCP_SKB_CB(skb)->bpf.sk_redir = NULL;
  1049. skb->sk = psock->sock;
  1050. bpf_compute_data_end_sk_skb(skb);
  1051. preempt_disable();
  1052. rc = (*prog->bpf_func)(skb, prog->insnsi);
  1053. preempt_enable();
  1054. skb->sk = NULL;
  1055. /* Moving return codes from UAPI namespace into internal namespace */
  1056. return rc == SK_PASS ?
  1057. (TCP_SKB_CB(skb)->bpf.sk_redir ? __SK_REDIRECT : __SK_PASS) :
  1058. __SK_DROP;
  1059. }
  1060. static int smap_do_ingress(struct smap_psock *psock, struct sk_buff *skb)
  1061. {
  1062. struct sock *sk = psock->sock;
  1063. int copied = 0, num_sg;
  1064. struct sk_msg_buff *r;
  1065. r = kzalloc(sizeof(struct sk_msg_buff), __GFP_NOWARN | GFP_ATOMIC);
  1066. if (unlikely(!r))
  1067. return -EAGAIN;
  1068. if (!sk_rmem_schedule(sk, skb, skb->len)) {
  1069. kfree(r);
  1070. return -EAGAIN;
  1071. }
  1072. sg_init_table(r->sg_data, MAX_SKB_FRAGS);
  1073. num_sg = skb_to_sgvec(skb, r->sg_data, 0, skb->len);
  1074. if (unlikely(num_sg < 0)) {
  1075. kfree(r);
  1076. return num_sg;
  1077. }
  1078. sk_mem_charge(sk, skb->len);
  1079. copied = skb->len;
  1080. r->sg_start = 0;
  1081. r->sg_end = num_sg == MAX_SKB_FRAGS ? 0 : num_sg;
  1082. r->skb = skb;
  1083. list_add_tail(&r->list, &psock->ingress);
  1084. sk->sk_data_ready(sk);
  1085. return copied;
  1086. }
  1087. static void smap_do_verdict(struct smap_psock *psock, struct sk_buff *skb)
  1088. {
  1089. struct smap_psock *peer;
  1090. struct sock *sk;
  1091. __u32 in;
  1092. int rc;
  1093. rc = smap_verdict_func(psock, skb);
  1094. switch (rc) {
  1095. case __SK_REDIRECT:
  1096. sk = do_sk_redirect_map(skb);
  1097. if (!sk) {
  1098. kfree_skb(skb);
  1099. break;
  1100. }
  1101. peer = smap_psock_sk(sk);
  1102. in = (TCP_SKB_CB(skb)->bpf.flags) & BPF_F_INGRESS;
  1103. if (unlikely(!peer || sock_flag(sk, SOCK_DEAD) ||
  1104. !test_bit(SMAP_TX_RUNNING, &peer->state))) {
  1105. kfree_skb(skb);
  1106. break;
  1107. }
  1108. if (!in && sock_writeable(sk)) {
  1109. skb_set_owner_w(skb, sk);
  1110. skb_queue_tail(&peer->rxqueue, skb);
  1111. schedule_work(&peer->tx_work);
  1112. break;
  1113. } else if (in &&
  1114. atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) {
  1115. skb_queue_tail(&peer->rxqueue, skb);
  1116. schedule_work(&peer->tx_work);
  1117. break;
  1118. }
  1119. /* Fall through and free skb otherwise */
  1120. case __SK_DROP:
  1121. default:
  1122. kfree_skb(skb);
  1123. }
  1124. }
  1125. static void smap_report_sk_error(struct smap_psock *psock, int err)
  1126. {
  1127. struct sock *sk = psock->sock;
  1128. sk->sk_err = err;
  1129. sk->sk_error_report(sk);
  1130. }
  1131. static void smap_read_sock_strparser(struct strparser *strp,
  1132. struct sk_buff *skb)
  1133. {
  1134. struct smap_psock *psock;
  1135. rcu_read_lock();
  1136. psock = container_of(strp, struct smap_psock, strp);
  1137. smap_do_verdict(psock, skb);
  1138. rcu_read_unlock();
  1139. }
  1140. /* Called with lock held on socket */
  1141. static void smap_data_ready(struct sock *sk)
  1142. {
  1143. struct smap_psock *psock;
  1144. rcu_read_lock();
  1145. psock = smap_psock_sk(sk);
  1146. if (likely(psock)) {
  1147. write_lock_bh(&sk->sk_callback_lock);
  1148. strp_data_ready(&psock->strp);
  1149. write_unlock_bh(&sk->sk_callback_lock);
  1150. }
  1151. rcu_read_unlock();
  1152. }
  1153. static void smap_tx_work(struct work_struct *w)
  1154. {
  1155. struct smap_psock *psock;
  1156. struct sk_buff *skb;
  1157. int rem, off, n;
  1158. psock = container_of(w, struct smap_psock, tx_work);
  1159. /* lock sock to avoid losing sk_socket at some point during loop */
  1160. lock_sock(psock->sock);
  1161. if (psock->save_skb) {
  1162. skb = psock->save_skb;
  1163. rem = psock->save_rem;
  1164. off = psock->save_off;
  1165. psock->save_skb = NULL;
  1166. goto start;
  1167. }
  1168. while ((skb = skb_dequeue(&psock->rxqueue))) {
  1169. __u32 flags;
  1170. rem = skb->len;
  1171. off = 0;
  1172. start:
  1173. flags = (TCP_SKB_CB(skb)->bpf.flags) & BPF_F_INGRESS;
  1174. do {
  1175. if (likely(psock->sock->sk_socket)) {
  1176. if (flags)
  1177. n = smap_do_ingress(psock, skb);
  1178. else
  1179. n = skb_send_sock_locked(psock->sock,
  1180. skb, off, rem);
  1181. } else {
  1182. n = -EINVAL;
  1183. }
  1184. if (n <= 0) {
  1185. if (n == -EAGAIN) {
  1186. /* Retry when space is available */
  1187. psock->save_skb = skb;
  1188. psock->save_rem = rem;
  1189. psock->save_off = off;
  1190. goto out;
  1191. }
  1192. /* Hard errors break pipe and stop xmit */
  1193. smap_report_sk_error(psock, n ? -n : EPIPE);
  1194. clear_bit(SMAP_TX_RUNNING, &psock->state);
  1195. kfree_skb(skb);
  1196. goto out;
  1197. }
  1198. rem -= n;
  1199. off += n;
  1200. } while (rem);
  1201. if (!flags)
  1202. kfree_skb(skb);
  1203. }
  1204. out:
  1205. release_sock(psock->sock);
  1206. }
  1207. static void smap_write_space(struct sock *sk)
  1208. {
  1209. struct smap_psock *psock;
  1210. rcu_read_lock();
  1211. psock = smap_psock_sk(sk);
  1212. if (likely(psock && test_bit(SMAP_TX_RUNNING, &psock->state)))
  1213. schedule_work(&psock->tx_work);
  1214. rcu_read_unlock();
  1215. }
  1216. static void smap_stop_sock(struct smap_psock *psock, struct sock *sk)
  1217. {
  1218. if (!psock->strp_enabled)
  1219. return;
  1220. sk->sk_data_ready = psock->save_data_ready;
  1221. sk->sk_write_space = psock->save_write_space;
  1222. psock->save_data_ready = NULL;
  1223. psock->save_write_space = NULL;
  1224. strp_stop(&psock->strp);
  1225. psock->strp_enabled = false;
  1226. }
  1227. static void smap_destroy_psock(struct rcu_head *rcu)
  1228. {
  1229. struct smap_psock *psock = container_of(rcu,
  1230. struct smap_psock, rcu);
  1231. /* Now that a grace period has passed there is no longer
  1232. * any reference to this sock in the sockmap so we can
  1233. * destroy the psock, strparser, and bpf programs. But,
  1234. * because we use workqueue sync operations we can not
  1235. * do it in rcu context
  1236. */
  1237. schedule_work(&psock->gc_work);
  1238. }
  1239. static void smap_release_sock(struct smap_psock *psock, struct sock *sock)
  1240. {
  1241. if (refcount_dec_and_test(&psock->refcnt)) {
  1242. tcp_cleanup_ulp(sock);
  1243. write_lock_bh(&sock->sk_callback_lock);
  1244. smap_stop_sock(psock, sock);
  1245. write_unlock_bh(&sock->sk_callback_lock);
  1246. clear_bit(SMAP_TX_RUNNING, &psock->state);
  1247. rcu_assign_sk_user_data(sock, NULL);
  1248. call_rcu_sched(&psock->rcu, smap_destroy_psock);
  1249. }
  1250. }
  1251. static int smap_parse_func_strparser(struct strparser *strp,
  1252. struct sk_buff *skb)
  1253. {
  1254. struct smap_psock *psock;
  1255. struct bpf_prog *prog;
  1256. int rc;
  1257. rcu_read_lock();
  1258. psock = container_of(strp, struct smap_psock, strp);
  1259. prog = READ_ONCE(psock->bpf_parse);
  1260. if (unlikely(!prog)) {
  1261. rcu_read_unlock();
  1262. return skb->len;
  1263. }
  1264. /* Attach socket for bpf program to use if needed we can do this
  1265. * because strparser clones the skb before handing it to a upper
  1266. * layer, meaning skb_orphan has been called. We NULL sk on the
  1267. * way out to ensure we don't trigger a BUG_ON in skb/sk operations
  1268. * later and because we are not charging the memory of this skb to
  1269. * any socket yet.
  1270. */
  1271. skb->sk = psock->sock;
  1272. bpf_compute_data_end_sk_skb(skb);
  1273. rc = (*prog->bpf_func)(skb, prog->insnsi);
  1274. skb->sk = NULL;
  1275. rcu_read_unlock();
  1276. return rc;
  1277. }
  1278. static int smap_read_sock_done(struct strparser *strp, int err)
  1279. {
  1280. return err;
  1281. }
  1282. static int smap_init_sock(struct smap_psock *psock,
  1283. struct sock *sk)
  1284. {
  1285. static const struct strp_callbacks cb = {
  1286. .rcv_msg = smap_read_sock_strparser,
  1287. .parse_msg = smap_parse_func_strparser,
  1288. .read_sock_done = smap_read_sock_done,
  1289. };
  1290. return strp_init(&psock->strp, sk, &cb);
  1291. }
  1292. static void smap_init_progs(struct smap_psock *psock,
  1293. struct bpf_prog *verdict,
  1294. struct bpf_prog *parse)
  1295. {
  1296. struct bpf_prog *orig_parse, *orig_verdict;
  1297. orig_parse = xchg(&psock->bpf_parse, parse);
  1298. orig_verdict = xchg(&psock->bpf_verdict, verdict);
  1299. if (orig_verdict)
  1300. bpf_prog_put(orig_verdict);
  1301. if (orig_parse)
  1302. bpf_prog_put(orig_parse);
  1303. }
  1304. static void smap_start_sock(struct smap_psock *psock, struct sock *sk)
  1305. {
  1306. if (sk->sk_data_ready == smap_data_ready)
  1307. return;
  1308. psock->save_data_ready = sk->sk_data_ready;
  1309. psock->save_write_space = sk->sk_write_space;
  1310. sk->sk_data_ready = smap_data_ready;
  1311. sk->sk_write_space = smap_write_space;
  1312. psock->strp_enabled = true;
  1313. }
  1314. static void sock_map_remove_complete(struct bpf_stab *stab)
  1315. {
  1316. bpf_map_area_free(stab->sock_map);
  1317. kfree(stab);
  1318. }
  1319. static void smap_gc_work(struct work_struct *w)
  1320. {
  1321. struct smap_psock_map_entry *e, *tmp;
  1322. struct sk_msg_buff *md, *mtmp;
  1323. struct smap_psock *psock;
  1324. psock = container_of(w, struct smap_psock, gc_work);
  1325. /* no callback lock needed because we already detached sockmap ops */
  1326. if (psock->strp_enabled)
  1327. strp_done(&psock->strp);
  1328. cancel_work_sync(&psock->tx_work);
  1329. __skb_queue_purge(&psock->rxqueue);
  1330. /* At this point all strparser and xmit work must be complete */
  1331. if (psock->bpf_parse)
  1332. bpf_prog_put(psock->bpf_parse);
  1333. if (psock->bpf_verdict)
  1334. bpf_prog_put(psock->bpf_verdict);
  1335. if (psock->bpf_tx_msg)
  1336. bpf_prog_put(psock->bpf_tx_msg);
  1337. if (psock->cork) {
  1338. free_start_sg(psock->sock, psock->cork);
  1339. kfree(psock->cork);
  1340. }
  1341. list_for_each_entry_safe(md, mtmp, &psock->ingress, list) {
  1342. list_del(&md->list);
  1343. free_start_sg(psock->sock, md);
  1344. kfree(md);
  1345. }
  1346. list_for_each_entry_safe(e, tmp, &psock->maps, list) {
  1347. list_del(&e->list);
  1348. kfree(e);
  1349. }
  1350. if (psock->sk_redir)
  1351. sock_put(psock->sk_redir);
  1352. sock_put(psock->sock);
  1353. kfree(psock);
  1354. }
  1355. static struct smap_psock *smap_init_psock(struct sock *sock, int node)
  1356. {
  1357. struct smap_psock *psock;
  1358. psock = kzalloc_node(sizeof(struct smap_psock),
  1359. GFP_ATOMIC | __GFP_NOWARN,
  1360. node);
  1361. if (!psock)
  1362. return ERR_PTR(-ENOMEM);
  1363. psock->eval = __SK_NONE;
  1364. psock->sock = sock;
  1365. skb_queue_head_init(&psock->rxqueue);
  1366. INIT_WORK(&psock->tx_work, smap_tx_work);
  1367. INIT_WORK(&psock->gc_work, smap_gc_work);
  1368. INIT_LIST_HEAD(&psock->maps);
  1369. INIT_LIST_HEAD(&psock->ingress);
  1370. refcount_set(&psock->refcnt, 1);
  1371. spin_lock_init(&psock->maps_lock);
  1372. rcu_assign_sk_user_data(sock, psock);
  1373. sock_hold(sock);
  1374. return psock;
  1375. }
  1376. static struct bpf_map *sock_map_alloc(union bpf_attr *attr)
  1377. {
  1378. struct bpf_stab *stab;
  1379. u64 cost;
  1380. int err;
  1381. if (!capable(CAP_NET_ADMIN))
  1382. return ERR_PTR(-EPERM);
  1383. /* check sanity of attributes */
  1384. if (attr->max_entries == 0 || attr->key_size != 4 ||
  1385. attr->value_size != 4 || attr->map_flags & ~SOCK_CREATE_FLAG_MASK)
  1386. return ERR_PTR(-EINVAL);
  1387. err = bpf_tcp_ulp_register();
  1388. if (err && err != -EEXIST)
  1389. return ERR_PTR(err);
  1390. stab = kzalloc(sizeof(*stab), GFP_USER);
  1391. if (!stab)
  1392. return ERR_PTR(-ENOMEM);
  1393. bpf_map_init_from_attr(&stab->map, attr);
  1394. /* make sure page count doesn't overflow */
  1395. cost = (u64) stab->map.max_entries * sizeof(struct sock *);
  1396. err = -EINVAL;
  1397. if (cost >= U32_MAX - PAGE_SIZE)
  1398. goto free_stab;
  1399. stab->map.pages = round_up(cost, PAGE_SIZE) >> PAGE_SHIFT;
  1400. /* if map size is larger than memlock limit, reject it early */
  1401. err = bpf_map_precharge_memlock(stab->map.pages);
  1402. if (err)
  1403. goto free_stab;
  1404. err = -ENOMEM;
  1405. stab->sock_map = bpf_map_area_alloc(stab->map.max_entries *
  1406. sizeof(struct sock *),
  1407. stab->map.numa_node);
  1408. if (!stab->sock_map)
  1409. goto free_stab;
  1410. return &stab->map;
  1411. free_stab:
  1412. kfree(stab);
  1413. return ERR_PTR(err);
  1414. }
  1415. static void smap_list_map_remove(struct smap_psock *psock,
  1416. struct sock **entry)
  1417. {
  1418. struct smap_psock_map_entry *e, *tmp;
  1419. spin_lock_bh(&psock->maps_lock);
  1420. list_for_each_entry_safe(e, tmp, &psock->maps, list) {
  1421. if (e->entry == entry)
  1422. list_del(&e->list);
  1423. }
  1424. spin_unlock_bh(&psock->maps_lock);
  1425. }
  1426. static void smap_list_hash_remove(struct smap_psock *psock,
  1427. struct htab_elem *hash_link)
  1428. {
  1429. struct smap_psock_map_entry *e, *tmp;
  1430. spin_lock_bh(&psock->maps_lock);
  1431. list_for_each_entry_safe(e, tmp, &psock->maps, list) {
  1432. struct htab_elem *c = rcu_dereference(e->hash_link);
  1433. if (c == hash_link)
  1434. list_del(&e->list);
  1435. }
  1436. spin_unlock_bh(&psock->maps_lock);
  1437. }
  1438. static void sock_map_free(struct bpf_map *map)
  1439. {
  1440. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1441. int i;
  1442. synchronize_rcu();
  1443. /* At this point no update, lookup or delete operations can happen.
  1444. * However, be aware we can still get a socket state event updates,
  1445. * and data ready callabacks that reference the psock from sk_user_data
  1446. * Also psock worker threads are still in-flight. So smap_release_sock
  1447. * will only free the psock after cancel_sync on the worker threads
  1448. * and a grace period expire to ensure psock is really safe to remove.
  1449. */
  1450. rcu_read_lock();
  1451. for (i = 0; i < stab->map.max_entries; i++) {
  1452. struct smap_psock *psock;
  1453. struct sock *sock;
  1454. sock = xchg(&stab->sock_map[i], NULL);
  1455. if (!sock)
  1456. continue;
  1457. psock = smap_psock_sk(sock);
  1458. /* This check handles a racing sock event that can get the
  1459. * sk_callback_lock before this case but after xchg happens
  1460. * causing the refcnt to hit zero and sock user data (psock)
  1461. * to be null and queued for garbage collection.
  1462. */
  1463. if (likely(psock)) {
  1464. smap_list_map_remove(psock, &stab->sock_map[i]);
  1465. smap_release_sock(psock, sock);
  1466. }
  1467. }
  1468. rcu_read_unlock();
  1469. sock_map_remove_complete(stab);
  1470. }
  1471. static int sock_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
  1472. {
  1473. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1474. u32 i = key ? *(u32 *)key : U32_MAX;
  1475. u32 *next = (u32 *)next_key;
  1476. if (i >= stab->map.max_entries) {
  1477. *next = 0;
  1478. return 0;
  1479. }
  1480. if (i == stab->map.max_entries - 1)
  1481. return -ENOENT;
  1482. *next = i + 1;
  1483. return 0;
  1484. }
  1485. struct sock *__sock_map_lookup_elem(struct bpf_map *map, u32 key)
  1486. {
  1487. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1488. if (key >= map->max_entries)
  1489. return NULL;
  1490. return READ_ONCE(stab->sock_map[key]);
  1491. }
  1492. static int sock_map_delete_elem(struct bpf_map *map, void *key)
  1493. {
  1494. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1495. struct smap_psock *psock;
  1496. int k = *(u32 *)key;
  1497. struct sock *sock;
  1498. if (k >= map->max_entries)
  1499. return -EINVAL;
  1500. sock = xchg(&stab->sock_map[k], NULL);
  1501. if (!sock)
  1502. return -EINVAL;
  1503. psock = smap_psock_sk(sock);
  1504. if (!psock)
  1505. goto out;
  1506. if (psock->bpf_parse)
  1507. smap_stop_sock(psock, sock);
  1508. smap_list_map_remove(psock, &stab->sock_map[k]);
  1509. smap_release_sock(psock, sock);
  1510. out:
  1511. return 0;
  1512. }
  1513. /* Locking notes: Concurrent updates, deletes, and lookups are allowed and are
  1514. * done inside rcu critical sections. This ensures on updates that the psock
  1515. * will not be released via smap_release_sock() until concurrent updates/deletes
  1516. * complete. All operations operate on sock_map using cmpxchg and xchg
  1517. * operations to ensure we do not get stale references. Any reads into the
  1518. * map must be done with READ_ONCE() because of this.
  1519. *
  1520. * A psock is destroyed via call_rcu and after any worker threads are cancelled
  1521. * and syncd so we are certain all references from the update/lookup/delete
  1522. * operations as well as references in the data path are no longer in use.
  1523. *
  1524. * Psocks may exist in multiple maps, but only a single set of parse/verdict
  1525. * programs may be inherited from the maps it belongs to. A reference count
  1526. * is kept with the total number of references to the psock from all maps. The
  1527. * psock will not be released until this reaches zero. The psock and sock
  1528. * user data data use the sk_callback_lock to protect critical data structures
  1529. * from concurrent access. This allows us to avoid two updates from modifying
  1530. * the user data in sock and the lock is required anyways for modifying
  1531. * callbacks, we simply increase its scope slightly.
  1532. *
  1533. * Rules to follow,
  1534. * - psock must always be read inside RCU critical section
  1535. * - sk_user_data must only be modified inside sk_callback_lock and read
  1536. * inside RCU critical section.
  1537. * - psock->maps list must only be read & modified inside sk_callback_lock
  1538. * - sock_map must use READ_ONCE and (cmp)xchg operations
  1539. * - BPF verdict/parse programs must use READ_ONCE and xchg operations
  1540. */
  1541. static int __sock_map_ctx_update_elem(struct bpf_map *map,
  1542. struct bpf_sock_progs *progs,
  1543. struct sock *sock,
  1544. struct sock **map_link,
  1545. void *key)
  1546. {
  1547. struct bpf_prog *verdict, *parse, *tx_msg;
  1548. struct smap_psock_map_entry *e = NULL;
  1549. struct smap_psock *psock;
  1550. bool new = false;
  1551. int err = 0;
  1552. /* 1. If sock map has BPF programs those will be inherited by the
  1553. * sock being added. If the sock is already attached to BPF programs
  1554. * this results in an error.
  1555. */
  1556. verdict = READ_ONCE(progs->bpf_verdict);
  1557. parse = READ_ONCE(progs->bpf_parse);
  1558. tx_msg = READ_ONCE(progs->bpf_tx_msg);
  1559. if (parse && verdict) {
  1560. /* bpf prog refcnt may be zero if a concurrent attach operation
  1561. * removes the program after the above READ_ONCE() but before
  1562. * we increment the refcnt. If this is the case abort with an
  1563. * error.
  1564. */
  1565. verdict = bpf_prog_inc_not_zero(verdict);
  1566. if (IS_ERR(verdict))
  1567. return PTR_ERR(verdict);
  1568. parse = bpf_prog_inc_not_zero(parse);
  1569. if (IS_ERR(parse)) {
  1570. bpf_prog_put(verdict);
  1571. return PTR_ERR(parse);
  1572. }
  1573. }
  1574. if (tx_msg) {
  1575. tx_msg = bpf_prog_inc_not_zero(tx_msg);
  1576. if (IS_ERR(tx_msg)) {
  1577. if (parse && verdict) {
  1578. bpf_prog_put(parse);
  1579. bpf_prog_put(verdict);
  1580. }
  1581. return PTR_ERR(tx_msg);
  1582. }
  1583. }
  1584. psock = smap_psock_sk(sock);
  1585. /* 2. Do not allow inheriting programs if psock exists and has
  1586. * already inherited programs. This would create confusion on
  1587. * which parser/verdict program is running. If no psock exists
  1588. * create one. Inside sk_callback_lock to ensure concurrent create
  1589. * doesn't update user data.
  1590. */
  1591. if (psock) {
  1592. if (READ_ONCE(psock->bpf_parse) && parse) {
  1593. err = -EBUSY;
  1594. goto out_progs;
  1595. }
  1596. if (READ_ONCE(psock->bpf_tx_msg) && tx_msg) {
  1597. err = -EBUSY;
  1598. goto out_progs;
  1599. }
  1600. if (!refcount_inc_not_zero(&psock->refcnt)) {
  1601. err = -EAGAIN;
  1602. goto out_progs;
  1603. }
  1604. } else {
  1605. psock = smap_init_psock(sock, map->numa_node);
  1606. if (IS_ERR(psock)) {
  1607. err = PTR_ERR(psock);
  1608. goto out_progs;
  1609. }
  1610. set_bit(SMAP_TX_RUNNING, &psock->state);
  1611. new = true;
  1612. }
  1613. if (map_link) {
  1614. e = kzalloc(sizeof(*e), GFP_ATOMIC | __GFP_NOWARN);
  1615. if (!e) {
  1616. err = -ENOMEM;
  1617. goto out_free;
  1618. }
  1619. }
  1620. /* 3. At this point we have a reference to a valid psock that is
  1621. * running. Attach any BPF programs needed.
  1622. */
  1623. if (tx_msg)
  1624. bpf_tcp_msg_add(psock, sock, tx_msg);
  1625. if (new) {
  1626. err = tcp_set_ulp_id(sock, TCP_ULP_BPF);
  1627. if (err)
  1628. goto out_free;
  1629. }
  1630. if (parse && verdict && !psock->strp_enabled) {
  1631. err = smap_init_sock(psock, sock);
  1632. if (err)
  1633. goto out_free;
  1634. smap_init_progs(psock, verdict, parse);
  1635. write_lock_bh(&sock->sk_callback_lock);
  1636. smap_start_sock(psock, sock);
  1637. write_unlock_bh(&sock->sk_callback_lock);
  1638. }
  1639. /* 4. Place psock in sockmap for use and stop any programs on
  1640. * the old sock assuming its not the same sock we are replacing
  1641. * it with. Because we can only have a single set of programs if
  1642. * old_sock has a strp we can stop it.
  1643. */
  1644. if (map_link) {
  1645. e->entry = map_link;
  1646. spin_lock_bh(&psock->maps_lock);
  1647. list_add_tail(&e->list, &psock->maps);
  1648. spin_unlock_bh(&psock->maps_lock);
  1649. }
  1650. return err;
  1651. out_free:
  1652. smap_release_sock(psock, sock);
  1653. out_progs:
  1654. if (parse && verdict) {
  1655. bpf_prog_put(parse);
  1656. bpf_prog_put(verdict);
  1657. }
  1658. if (tx_msg)
  1659. bpf_prog_put(tx_msg);
  1660. kfree(e);
  1661. return err;
  1662. }
  1663. static int sock_map_ctx_update_elem(struct bpf_sock_ops_kern *skops,
  1664. struct bpf_map *map,
  1665. void *key, u64 flags)
  1666. {
  1667. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1668. struct bpf_sock_progs *progs = &stab->progs;
  1669. struct sock *osock, *sock;
  1670. u32 i = *(u32 *)key;
  1671. int err;
  1672. if (unlikely(flags > BPF_EXIST))
  1673. return -EINVAL;
  1674. if (unlikely(i >= stab->map.max_entries))
  1675. return -E2BIG;
  1676. sock = READ_ONCE(stab->sock_map[i]);
  1677. if (flags == BPF_EXIST && !sock)
  1678. return -ENOENT;
  1679. else if (flags == BPF_NOEXIST && sock)
  1680. return -EEXIST;
  1681. sock = skops->sk;
  1682. err = __sock_map_ctx_update_elem(map, progs, sock, &stab->sock_map[i],
  1683. key);
  1684. if (err)
  1685. goto out;
  1686. osock = xchg(&stab->sock_map[i], sock);
  1687. if (osock) {
  1688. struct smap_psock *opsock = smap_psock_sk(osock);
  1689. smap_list_map_remove(opsock, &stab->sock_map[i]);
  1690. smap_release_sock(opsock, osock);
  1691. }
  1692. out:
  1693. return err;
  1694. }
  1695. int sock_map_prog(struct bpf_map *map, struct bpf_prog *prog, u32 type)
  1696. {
  1697. struct bpf_sock_progs *progs;
  1698. struct bpf_prog *orig;
  1699. if (map->map_type == BPF_MAP_TYPE_SOCKMAP) {
  1700. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1701. progs = &stab->progs;
  1702. } else if (map->map_type == BPF_MAP_TYPE_SOCKHASH) {
  1703. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  1704. progs = &htab->progs;
  1705. } else {
  1706. return -EINVAL;
  1707. }
  1708. switch (type) {
  1709. case BPF_SK_MSG_VERDICT:
  1710. orig = xchg(&progs->bpf_tx_msg, prog);
  1711. break;
  1712. case BPF_SK_SKB_STREAM_PARSER:
  1713. orig = xchg(&progs->bpf_parse, prog);
  1714. break;
  1715. case BPF_SK_SKB_STREAM_VERDICT:
  1716. orig = xchg(&progs->bpf_verdict, prog);
  1717. break;
  1718. default:
  1719. return -EOPNOTSUPP;
  1720. }
  1721. if (orig)
  1722. bpf_prog_put(orig);
  1723. return 0;
  1724. }
  1725. int sockmap_get_from_fd(const union bpf_attr *attr, int type,
  1726. struct bpf_prog *prog)
  1727. {
  1728. int ufd = attr->target_fd;
  1729. struct bpf_map *map;
  1730. struct fd f;
  1731. int err;
  1732. f = fdget(ufd);
  1733. map = __bpf_map_get(f);
  1734. if (IS_ERR(map))
  1735. return PTR_ERR(map);
  1736. err = sock_map_prog(map, prog, attr->attach_type);
  1737. fdput(f);
  1738. return err;
  1739. }
  1740. static void *sock_map_lookup(struct bpf_map *map, void *key)
  1741. {
  1742. return NULL;
  1743. }
  1744. static int sock_map_update_elem(struct bpf_map *map,
  1745. void *key, void *value, u64 flags)
  1746. {
  1747. struct bpf_sock_ops_kern skops;
  1748. u32 fd = *(u32 *)value;
  1749. struct socket *socket;
  1750. int err;
  1751. socket = sockfd_lookup(fd, &err);
  1752. if (!socket)
  1753. return err;
  1754. skops.sk = socket->sk;
  1755. if (!skops.sk) {
  1756. fput(socket->file);
  1757. return -EINVAL;
  1758. }
  1759. if (skops.sk->sk_type != SOCK_STREAM ||
  1760. skops.sk->sk_protocol != IPPROTO_TCP) {
  1761. fput(socket->file);
  1762. return -EOPNOTSUPP;
  1763. }
  1764. lock_sock(skops.sk);
  1765. preempt_disable();
  1766. rcu_read_lock();
  1767. err = sock_map_ctx_update_elem(&skops, map, key, flags);
  1768. rcu_read_unlock();
  1769. preempt_enable();
  1770. release_sock(skops.sk);
  1771. fput(socket->file);
  1772. return err;
  1773. }
  1774. static void sock_map_release(struct bpf_map *map)
  1775. {
  1776. struct bpf_sock_progs *progs;
  1777. struct bpf_prog *orig;
  1778. if (map->map_type == BPF_MAP_TYPE_SOCKMAP) {
  1779. struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
  1780. progs = &stab->progs;
  1781. } else {
  1782. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  1783. progs = &htab->progs;
  1784. }
  1785. orig = xchg(&progs->bpf_parse, NULL);
  1786. if (orig)
  1787. bpf_prog_put(orig);
  1788. orig = xchg(&progs->bpf_verdict, NULL);
  1789. if (orig)
  1790. bpf_prog_put(orig);
  1791. orig = xchg(&progs->bpf_tx_msg, NULL);
  1792. if (orig)
  1793. bpf_prog_put(orig);
  1794. }
  1795. static struct bpf_map *sock_hash_alloc(union bpf_attr *attr)
  1796. {
  1797. struct bpf_htab *htab;
  1798. int i, err;
  1799. u64 cost;
  1800. if (!capable(CAP_NET_ADMIN))
  1801. return ERR_PTR(-EPERM);
  1802. /* check sanity of attributes */
  1803. if (attr->max_entries == 0 || attr->value_size != 4 ||
  1804. attr->map_flags & ~SOCK_CREATE_FLAG_MASK)
  1805. return ERR_PTR(-EINVAL);
  1806. if (attr->key_size > MAX_BPF_STACK)
  1807. /* eBPF programs initialize keys on stack, so they cannot be
  1808. * larger than max stack size
  1809. */
  1810. return ERR_PTR(-E2BIG);
  1811. err = bpf_tcp_ulp_register();
  1812. if (err && err != -EEXIST)
  1813. return ERR_PTR(err);
  1814. htab = kzalloc(sizeof(*htab), GFP_USER);
  1815. if (!htab)
  1816. return ERR_PTR(-ENOMEM);
  1817. bpf_map_init_from_attr(&htab->map, attr);
  1818. htab->n_buckets = roundup_pow_of_two(htab->map.max_entries);
  1819. htab->elem_size = sizeof(struct htab_elem) +
  1820. round_up(htab->map.key_size, 8);
  1821. err = -EINVAL;
  1822. if (htab->n_buckets == 0 ||
  1823. htab->n_buckets > U32_MAX / sizeof(struct bucket))
  1824. goto free_htab;
  1825. cost = (u64) htab->n_buckets * sizeof(struct bucket) +
  1826. (u64) htab->elem_size * htab->map.max_entries;
  1827. if (cost >= U32_MAX - PAGE_SIZE)
  1828. goto free_htab;
  1829. htab->map.pages = round_up(cost, PAGE_SIZE) >> PAGE_SHIFT;
  1830. err = bpf_map_precharge_memlock(htab->map.pages);
  1831. if (err)
  1832. goto free_htab;
  1833. err = -ENOMEM;
  1834. htab->buckets = bpf_map_area_alloc(
  1835. htab->n_buckets * sizeof(struct bucket),
  1836. htab->map.numa_node);
  1837. if (!htab->buckets)
  1838. goto free_htab;
  1839. for (i = 0; i < htab->n_buckets; i++) {
  1840. INIT_HLIST_HEAD(&htab->buckets[i].head);
  1841. raw_spin_lock_init(&htab->buckets[i].lock);
  1842. }
  1843. return &htab->map;
  1844. free_htab:
  1845. kfree(htab);
  1846. return ERR_PTR(err);
  1847. }
  1848. static void __bpf_htab_free(struct rcu_head *rcu)
  1849. {
  1850. struct bpf_htab *htab;
  1851. htab = container_of(rcu, struct bpf_htab, rcu);
  1852. bpf_map_area_free(htab->buckets);
  1853. kfree(htab);
  1854. }
  1855. static void sock_hash_free(struct bpf_map *map)
  1856. {
  1857. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  1858. int i;
  1859. synchronize_rcu();
  1860. /* At this point no update, lookup or delete operations can happen.
  1861. * However, be aware we can still get a socket state event updates,
  1862. * and data ready callabacks that reference the psock from sk_user_data
  1863. * Also psock worker threads are still in-flight. So smap_release_sock
  1864. * will only free the psock after cancel_sync on the worker threads
  1865. * and a grace period expire to ensure psock is really safe to remove.
  1866. */
  1867. rcu_read_lock();
  1868. for (i = 0; i < htab->n_buckets; i++) {
  1869. struct bucket *b = __select_bucket(htab, i);
  1870. struct hlist_head *head;
  1871. struct hlist_node *n;
  1872. struct htab_elem *l;
  1873. raw_spin_lock_bh(&b->lock);
  1874. head = &b->head;
  1875. hlist_for_each_entry_safe(l, n, head, hash_node) {
  1876. struct sock *sock = l->sk;
  1877. struct smap_psock *psock;
  1878. hlist_del_rcu(&l->hash_node);
  1879. psock = smap_psock_sk(sock);
  1880. /* This check handles a racing sock event that can get
  1881. * the sk_callback_lock before this case but after xchg
  1882. * causing the refcnt to hit zero and sock user data
  1883. * (psock) to be null and queued for garbage collection.
  1884. */
  1885. if (likely(psock)) {
  1886. smap_list_hash_remove(psock, l);
  1887. smap_release_sock(psock, sock);
  1888. }
  1889. free_htab_elem(htab, l);
  1890. }
  1891. raw_spin_unlock_bh(&b->lock);
  1892. }
  1893. rcu_read_unlock();
  1894. call_rcu(&htab->rcu, __bpf_htab_free);
  1895. }
  1896. static struct htab_elem *alloc_sock_hash_elem(struct bpf_htab *htab,
  1897. void *key, u32 key_size, u32 hash,
  1898. struct sock *sk,
  1899. struct htab_elem *old_elem)
  1900. {
  1901. struct htab_elem *l_new;
  1902. if (atomic_inc_return(&htab->count) > htab->map.max_entries) {
  1903. if (!old_elem) {
  1904. atomic_dec(&htab->count);
  1905. return ERR_PTR(-E2BIG);
  1906. }
  1907. }
  1908. l_new = kmalloc_node(htab->elem_size, GFP_ATOMIC | __GFP_NOWARN,
  1909. htab->map.numa_node);
  1910. if (!l_new)
  1911. return ERR_PTR(-ENOMEM);
  1912. memcpy(l_new->key, key, key_size);
  1913. l_new->sk = sk;
  1914. l_new->hash = hash;
  1915. return l_new;
  1916. }
  1917. static inline u32 htab_map_hash(const void *key, u32 key_len)
  1918. {
  1919. return jhash(key, key_len, 0);
  1920. }
  1921. static int sock_hash_get_next_key(struct bpf_map *map,
  1922. void *key, void *next_key)
  1923. {
  1924. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  1925. struct htab_elem *l, *next_l;
  1926. struct hlist_head *h;
  1927. u32 hash, key_size;
  1928. int i = 0;
  1929. WARN_ON_ONCE(!rcu_read_lock_held());
  1930. key_size = map->key_size;
  1931. if (!key)
  1932. goto find_first_elem;
  1933. hash = htab_map_hash(key, key_size);
  1934. h = select_bucket(htab, hash);
  1935. l = lookup_elem_raw(h, hash, key, key_size);
  1936. if (!l)
  1937. goto find_first_elem;
  1938. next_l = hlist_entry_safe(
  1939. rcu_dereference_raw(hlist_next_rcu(&l->hash_node)),
  1940. struct htab_elem, hash_node);
  1941. if (next_l) {
  1942. memcpy(next_key, next_l->key, key_size);
  1943. return 0;
  1944. }
  1945. /* no more elements in this hash list, go to the next bucket */
  1946. i = hash & (htab->n_buckets - 1);
  1947. i++;
  1948. find_first_elem:
  1949. /* iterate over buckets */
  1950. for (; i < htab->n_buckets; i++) {
  1951. h = select_bucket(htab, i);
  1952. /* pick first element in the bucket */
  1953. next_l = hlist_entry_safe(
  1954. rcu_dereference_raw(hlist_first_rcu(h)),
  1955. struct htab_elem, hash_node);
  1956. if (next_l) {
  1957. /* if it's not empty, just return it */
  1958. memcpy(next_key, next_l->key, key_size);
  1959. return 0;
  1960. }
  1961. }
  1962. /* iterated over all buckets and all elements */
  1963. return -ENOENT;
  1964. }
  1965. static int sock_hash_ctx_update_elem(struct bpf_sock_ops_kern *skops,
  1966. struct bpf_map *map,
  1967. void *key, u64 map_flags)
  1968. {
  1969. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  1970. struct bpf_sock_progs *progs = &htab->progs;
  1971. struct htab_elem *l_new = NULL, *l_old;
  1972. struct smap_psock_map_entry *e = NULL;
  1973. struct hlist_head *head;
  1974. struct smap_psock *psock;
  1975. u32 key_size, hash;
  1976. struct sock *sock;
  1977. struct bucket *b;
  1978. int err;
  1979. sock = skops->sk;
  1980. if (sock->sk_type != SOCK_STREAM ||
  1981. sock->sk_protocol != IPPROTO_TCP)
  1982. return -EOPNOTSUPP;
  1983. if (unlikely(map_flags > BPF_EXIST))
  1984. return -EINVAL;
  1985. e = kzalloc(sizeof(*e), GFP_ATOMIC | __GFP_NOWARN);
  1986. if (!e)
  1987. return -ENOMEM;
  1988. WARN_ON_ONCE(!rcu_read_lock_held());
  1989. key_size = map->key_size;
  1990. hash = htab_map_hash(key, key_size);
  1991. b = __select_bucket(htab, hash);
  1992. head = &b->head;
  1993. err = __sock_map_ctx_update_elem(map, progs, sock, NULL, key);
  1994. if (err)
  1995. goto err;
  1996. /* psock is valid here because otherwise above *ctx_update_elem would
  1997. * have thrown an error. It is safe to skip error check.
  1998. */
  1999. psock = smap_psock_sk(sock);
  2000. raw_spin_lock_bh(&b->lock);
  2001. l_old = lookup_elem_raw(head, hash, key, key_size);
  2002. if (l_old && map_flags == BPF_NOEXIST) {
  2003. err = -EEXIST;
  2004. goto bucket_err;
  2005. }
  2006. if (!l_old && map_flags == BPF_EXIST) {
  2007. err = -ENOENT;
  2008. goto bucket_err;
  2009. }
  2010. l_new = alloc_sock_hash_elem(htab, key, key_size, hash, sock, l_old);
  2011. if (IS_ERR(l_new)) {
  2012. err = PTR_ERR(l_new);
  2013. goto bucket_err;
  2014. }
  2015. rcu_assign_pointer(e->hash_link, l_new);
  2016. rcu_assign_pointer(e->htab,
  2017. container_of(map, struct bpf_htab, map));
  2018. spin_lock_bh(&psock->maps_lock);
  2019. list_add_tail(&e->list, &psock->maps);
  2020. spin_unlock_bh(&psock->maps_lock);
  2021. /* add new element to the head of the list, so that
  2022. * concurrent search will find it before old elem
  2023. */
  2024. hlist_add_head_rcu(&l_new->hash_node, head);
  2025. if (l_old) {
  2026. psock = smap_psock_sk(l_old->sk);
  2027. hlist_del_rcu(&l_old->hash_node);
  2028. smap_list_hash_remove(psock, l_old);
  2029. smap_release_sock(psock, l_old->sk);
  2030. free_htab_elem(htab, l_old);
  2031. }
  2032. raw_spin_unlock_bh(&b->lock);
  2033. return 0;
  2034. bucket_err:
  2035. smap_release_sock(psock, sock);
  2036. raw_spin_unlock_bh(&b->lock);
  2037. err:
  2038. kfree(e);
  2039. return err;
  2040. }
  2041. static int sock_hash_update_elem(struct bpf_map *map,
  2042. void *key, void *value, u64 flags)
  2043. {
  2044. struct bpf_sock_ops_kern skops;
  2045. u32 fd = *(u32 *)value;
  2046. struct socket *socket;
  2047. int err;
  2048. socket = sockfd_lookup(fd, &err);
  2049. if (!socket)
  2050. return err;
  2051. skops.sk = socket->sk;
  2052. if (!skops.sk) {
  2053. fput(socket->file);
  2054. return -EINVAL;
  2055. }
  2056. lock_sock(skops.sk);
  2057. preempt_disable();
  2058. rcu_read_lock();
  2059. err = sock_hash_ctx_update_elem(&skops, map, key, flags);
  2060. rcu_read_unlock();
  2061. preempt_enable();
  2062. release_sock(skops.sk);
  2063. fput(socket->file);
  2064. return err;
  2065. }
  2066. static int sock_hash_delete_elem(struct bpf_map *map, void *key)
  2067. {
  2068. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  2069. struct hlist_head *head;
  2070. struct bucket *b;
  2071. struct htab_elem *l;
  2072. u32 hash, key_size;
  2073. int ret = -ENOENT;
  2074. key_size = map->key_size;
  2075. hash = htab_map_hash(key, key_size);
  2076. b = __select_bucket(htab, hash);
  2077. head = &b->head;
  2078. raw_spin_lock_bh(&b->lock);
  2079. l = lookup_elem_raw(head, hash, key, key_size);
  2080. if (l) {
  2081. struct sock *sock = l->sk;
  2082. struct smap_psock *psock;
  2083. hlist_del_rcu(&l->hash_node);
  2084. psock = smap_psock_sk(sock);
  2085. /* This check handles a racing sock event that can get the
  2086. * sk_callback_lock before this case but after xchg happens
  2087. * causing the refcnt to hit zero and sock user data (psock)
  2088. * to be null and queued for garbage collection.
  2089. */
  2090. if (likely(psock)) {
  2091. smap_list_hash_remove(psock, l);
  2092. smap_release_sock(psock, sock);
  2093. }
  2094. free_htab_elem(htab, l);
  2095. ret = 0;
  2096. }
  2097. raw_spin_unlock_bh(&b->lock);
  2098. return ret;
  2099. }
  2100. struct sock *__sock_hash_lookup_elem(struct bpf_map *map, void *key)
  2101. {
  2102. struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
  2103. struct hlist_head *head;
  2104. struct htab_elem *l;
  2105. u32 key_size, hash;
  2106. struct bucket *b;
  2107. struct sock *sk;
  2108. key_size = map->key_size;
  2109. hash = htab_map_hash(key, key_size);
  2110. b = __select_bucket(htab, hash);
  2111. head = &b->head;
  2112. l = lookup_elem_raw(head, hash, key, key_size);
  2113. sk = l ? l->sk : NULL;
  2114. return sk;
  2115. }
  2116. const struct bpf_map_ops sock_map_ops = {
  2117. .map_alloc = sock_map_alloc,
  2118. .map_free = sock_map_free,
  2119. .map_lookup_elem = sock_map_lookup,
  2120. .map_get_next_key = sock_map_get_next_key,
  2121. .map_update_elem = sock_map_update_elem,
  2122. .map_delete_elem = sock_map_delete_elem,
  2123. .map_release_uref = sock_map_release,
  2124. .map_check_btf = map_check_no_btf,
  2125. };
  2126. const struct bpf_map_ops sock_hash_ops = {
  2127. .map_alloc = sock_hash_alloc,
  2128. .map_free = sock_hash_free,
  2129. .map_lookup_elem = sock_map_lookup,
  2130. .map_get_next_key = sock_hash_get_next_key,
  2131. .map_update_elem = sock_hash_update_elem,
  2132. .map_delete_elem = sock_hash_delete_elem,
  2133. .map_release_uref = sock_map_release,
  2134. .map_check_btf = map_check_no_btf,
  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. };