sockmap.c 59 KB

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