helpers.c 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
  3. */
  4. #include <linux/bpf.h>
  5. #include <linux/btf.h>
  6. #include <linux/bpf-cgroup.h>
  7. #include <linux/cgroup.h>
  8. #include <linux/rcupdate.h>
  9. #include <linux/random.h>
  10. #include <linux/smp.h>
  11. #include <linux/topology.h>
  12. #include <linux/ktime.h>
  13. #include <linux/sched.h>
  14. #include <linux/uidgid.h>
  15. #include <linux/filter.h>
  16. #include <linux/ctype.h>
  17. #include <linux/jiffies.h>
  18. #include <linux/pid_namespace.h>
  19. #include <linux/poison.h>
  20. #include <linux/proc_ns.h>
  21. #include <linux/sched/task.h>
  22. #include <linux/security.h>
  23. #include <linux/btf_ids.h>
  24. #include <linux/bpf_mem_alloc.h>
  25. #include <linux/kasan.h>
  26. #include "../../lib/kstrtox.h"
  27. /* If kernel subsystem is allowing eBPF programs to call this function,
  28. * inside its own verifier_ops->get_func_proto() callback it should return
  29. * bpf_map_lookup_elem_proto, so that verifier can properly check the arguments
  30. *
  31. * Different map implementations will rely on rcu in map methods
  32. * lookup/update/delete, therefore eBPF programs must run under rcu lock
  33. * if program is allowed to access maps, so check rcu_read_lock_held() or
  34. * rcu_read_lock_trace_held() in all three functions.
  35. */
  36. BPF_CALL_2(bpf_map_lookup_elem, struct bpf_map *, map, void *, key)
  37. {
  38. WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
  39. !rcu_read_lock_bh_held());
  40. return (unsigned long) map->ops->map_lookup_elem(map, key);
  41. }
  42. const struct bpf_func_proto bpf_map_lookup_elem_proto = {
  43. .func = bpf_map_lookup_elem,
  44. .gpl_only = false,
  45. .pkt_access = true,
  46. .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
  47. .arg1_type = ARG_CONST_MAP_PTR,
  48. .arg2_type = ARG_PTR_TO_MAP_KEY,
  49. };
  50. BPF_CALL_4(bpf_map_update_elem, struct bpf_map *, map, void *, key,
  51. void *, value, u64, flags)
  52. {
  53. WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
  54. !rcu_read_lock_bh_held());
  55. return map->ops->map_update_elem(map, key, value, flags);
  56. }
  57. const struct bpf_func_proto bpf_map_update_elem_proto = {
  58. .func = bpf_map_update_elem,
  59. .gpl_only = false,
  60. .pkt_access = true,
  61. .ret_type = RET_INTEGER,
  62. .arg1_type = ARG_CONST_MAP_PTR,
  63. .arg2_type = ARG_PTR_TO_MAP_KEY,
  64. .arg3_type = ARG_PTR_TO_MAP_VALUE,
  65. .arg4_type = ARG_ANYTHING,
  66. };
  67. BPF_CALL_2(bpf_map_delete_elem, struct bpf_map *, map, void *, key)
  68. {
  69. WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
  70. !rcu_read_lock_bh_held());
  71. return map->ops->map_delete_elem(map, key);
  72. }
  73. const struct bpf_func_proto bpf_map_delete_elem_proto = {
  74. .func = bpf_map_delete_elem,
  75. .gpl_only = false,
  76. .pkt_access = true,
  77. .ret_type = RET_INTEGER,
  78. .arg1_type = ARG_CONST_MAP_PTR,
  79. .arg2_type = ARG_PTR_TO_MAP_KEY,
  80. };
  81. BPF_CALL_3(bpf_map_push_elem, struct bpf_map *, map, void *, value, u64, flags)
  82. {
  83. return map->ops->map_push_elem(map, value, flags);
  84. }
  85. const struct bpf_func_proto bpf_map_push_elem_proto = {
  86. .func = bpf_map_push_elem,
  87. .gpl_only = false,
  88. .pkt_access = true,
  89. .ret_type = RET_INTEGER,
  90. .arg1_type = ARG_CONST_MAP_PTR,
  91. .arg2_type = ARG_PTR_TO_MAP_VALUE,
  92. .arg3_type = ARG_ANYTHING,
  93. };
  94. BPF_CALL_2(bpf_map_pop_elem, struct bpf_map *, map, void *, value)
  95. {
  96. return map->ops->map_pop_elem(map, value);
  97. }
  98. const struct bpf_func_proto bpf_map_pop_elem_proto = {
  99. .func = bpf_map_pop_elem,
  100. .gpl_only = false,
  101. .ret_type = RET_INTEGER,
  102. .arg1_type = ARG_CONST_MAP_PTR,
  103. .arg2_type = ARG_PTR_TO_MAP_VALUE | MEM_UNINIT | MEM_WRITE,
  104. };
  105. BPF_CALL_2(bpf_map_peek_elem, struct bpf_map *, map, void *, value)
  106. {
  107. return map->ops->map_peek_elem(map, value);
  108. }
  109. const struct bpf_func_proto bpf_map_peek_elem_proto = {
  110. .func = bpf_map_peek_elem,
  111. .gpl_only = false,
  112. .ret_type = RET_INTEGER,
  113. .arg1_type = ARG_CONST_MAP_PTR,
  114. .arg2_type = ARG_PTR_TO_MAP_VALUE | MEM_UNINIT | MEM_WRITE,
  115. };
  116. BPF_CALL_3(bpf_map_lookup_percpu_elem, struct bpf_map *, map, void *, key, u32, cpu)
  117. {
  118. WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
  119. !rcu_read_lock_bh_held());
  120. return (unsigned long) map->ops->map_lookup_percpu_elem(map, key, cpu);
  121. }
  122. const struct bpf_func_proto bpf_map_lookup_percpu_elem_proto = {
  123. .func = bpf_map_lookup_percpu_elem,
  124. .gpl_only = false,
  125. .pkt_access = true,
  126. .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
  127. .arg1_type = ARG_CONST_MAP_PTR,
  128. .arg2_type = ARG_PTR_TO_MAP_KEY,
  129. .arg3_type = ARG_ANYTHING,
  130. };
  131. const struct bpf_func_proto bpf_get_prandom_u32_proto = {
  132. .func = bpf_user_rnd_u32,
  133. .gpl_only = false,
  134. .ret_type = RET_INTEGER,
  135. };
  136. BPF_CALL_0(bpf_get_smp_processor_id)
  137. {
  138. return smp_processor_id();
  139. }
  140. const struct bpf_func_proto bpf_get_smp_processor_id_proto = {
  141. .func = bpf_get_smp_processor_id,
  142. .gpl_only = false,
  143. .ret_type = RET_INTEGER,
  144. .allow_fastcall = true,
  145. };
  146. BPF_CALL_0(bpf_get_numa_node_id)
  147. {
  148. return numa_node_id();
  149. }
  150. const struct bpf_func_proto bpf_get_numa_node_id_proto = {
  151. .func = bpf_get_numa_node_id,
  152. .gpl_only = false,
  153. .ret_type = RET_INTEGER,
  154. };
  155. BPF_CALL_0(bpf_ktime_get_ns)
  156. {
  157. /* NMI safe access to clock monotonic */
  158. return ktime_get_mono_fast_ns();
  159. }
  160. const struct bpf_func_proto bpf_ktime_get_ns_proto = {
  161. .func = bpf_ktime_get_ns,
  162. .gpl_only = false,
  163. .ret_type = RET_INTEGER,
  164. };
  165. BPF_CALL_0(bpf_ktime_get_boot_ns)
  166. {
  167. /* NMI safe access to clock boottime */
  168. return ktime_get_boot_fast_ns();
  169. }
  170. const struct bpf_func_proto bpf_ktime_get_boot_ns_proto = {
  171. .func = bpf_ktime_get_boot_ns,
  172. .gpl_only = false,
  173. .ret_type = RET_INTEGER,
  174. };
  175. BPF_CALL_0(bpf_ktime_get_coarse_ns)
  176. {
  177. return ktime_get_coarse_ns();
  178. }
  179. const struct bpf_func_proto bpf_ktime_get_coarse_ns_proto = {
  180. .func = bpf_ktime_get_coarse_ns,
  181. .gpl_only = false,
  182. .ret_type = RET_INTEGER,
  183. };
  184. BPF_CALL_0(bpf_ktime_get_tai_ns)
  185. {
  186. /* NMI safe access to clock tai */
  187. return ktime_get_tai_fast_ns();
  188. }
  189. const struct bpf_func_proto bpf_ktime_get_tai_ns_proto = {
  190. .func = bpf_ktime_get_tai_ns,
  191. .gpl_only = false,
  192. .ret_type = RET_INTEGER,
  193. };
  194. BPF_CALL_0(bpf_get_current_pid_tgid)
  195. {
  196. struct task_struct *task = current;
  197. if (unlikely(!task))
  198. return -EINVAL;
  199. return (u64) task->tgid << 32 | task->pid;
  200. }
  201. const struct bpf_func_proto bpf_get_current_pid_tgid_proto = {
  202. .func = bpf_get_current_pid_tgid,
  203. .gpl_only = false,
  204. .ret_type = RET_INTEGER,
  205. };
  206. BPF_CALL_0(bpf_get_current_uid_gid)
  207. {
  208. struct task_struct *task = current;
  209. kuid_t uid;
  210. kgid_t gid;
  211. if (unlikely(!task))
  212. return -EINVAL;
  213. current_uid_gid(&uid, &gid);
  214. return (u64) from_kgid(&init_user_ns, gid) << 32 |
  215. from_kuid(&init_user_ns, uid);
  216. }
  217. const struct bpf_func_proto bpf_get_current_uid_gid_proto = {
  218. .func = bpf_get_current_uid_gid,
  219. .gpl_only = false,
  220. .ret_type = RET_INTEGER,
  221. };
  222. BPF_CALL_2(bpf_get_current_comm, char *, buf, u32, size)
  223. {
  224. struct task_struct *task = current;
  225. if (unlikely(!task))
  226. goto err_clear;
  227. /* Verifier guarantees that size > 0 */
  228. strscpy_pad(buf, task->comm, size);
  229. return 0;
  230. err_clear:
  231. memset(buf, 0, size);
  232. return -EINVAL;
  233. }
  234. const struct bpf_func_proto bpf_get_current_comm_proto = {
  235. .func = bpf_get_current_comm,
  236. .gpl_only = false,
  237. .ret_type = RET_INTEGER,
  238. .arg1_type = ARG_PTR_TO_UNINIT_MEM,
  239. .arg2_type = ARG_CONST_SIZE,
  240. };
  241. #if defined(CONFIG_QUEUED_SPINLOCKS) || defined(CONFIG_BPF_ARCH_SPINLOCK)
  242. static inline void __bpf_spin_lock(struct bpf_spin_lock *lock)
  243. {
  244. arch_spinlock_t *l = (void *)lock;
  245. union {
  246. __u32 val;
  247. arch_spinlock_t lock;
  248. } u = { .lock = __ARCH_SPIN_LOCK_UNLOCKED };
  249. compiletime_assert(u.val == 0, "__ARCH_SPIN_LOCK_UNLOCKED not 0");
  250. BUILD_BUG_ON(sizeof(*l) != sizeof(__u32));
  251. BUILD_BUG_ON(sizeof(*lock) != sizeof(__u32));
  252. preempt_disable();
  253. arch_spin_lock(l);
  254. }
  255. static inline void __bpf_spin_unlock(struct bpf_spin_lock *lock)
  256. {
  257. arch_spinlock_t *l = (void *)lock;
  258. arch_spin_unlock(l);
  259. preempt_enable();
  260. }
  261. #else
  262. static inline void __bpf_spin_lock(struct bpf_spin_lock *lock)
  263. {
  264. atomic_t *l = (void *)lock;
  265. BUILD_BUG_ON(sizeof(*l) != sizeof(*lock));
  266. do {
  267. atomic_cond_read_relaxed(l, !VAL);
  268. } while (atomic_xchg(l, 1));
  269. }
  270. static inline void __bpf_spin_unlock(struct bpf_spin_lock *lock)
  271. {
  272. atomic_t *l = (void *)lock;
  273. atomic_set_release(l, 0);
  274. }
  275. #endif
  276. static DEFINE_PER_CPU(unsigned long, irqsave_flags);
  277. static inline void __bpf_spin_lock_irqsave(struct bpf_spin_lock *lock)
  278. {
  279. unsigned long flags;
  280. local_irq_save(flags);
  281. __bpf_spin_lock(lock);
  282. __this_cpu_write(irqsave_flags, flags);
  283. }
  284. NOTRACE_BPF_CALL_1(bpf_spin_lock, struct bpf_spin_lock *, lock)
  285. {
  286. __bpf_spin_lock_irqsave(lock);
  287. return 0;
  288. }
  289. const struct bpf_func_proto bpf_spin_lock_proto = {
  290. .func = bpf_spin_lock,
  291. .gpl_only = false,
  292. .ret_type = RET_VOID,
  293. .arg1_type = ARG_PTR_TO_SPIN_LOCK,
  294. .arg1_btf_id = BPF_PTR_POISON,
  295. };
  296. static inline void __bpf_spin_unlock_irqrestore(struct bpf_spin_lock *lock)
  297. {
  298. unsigned long flags;
  299. flags = __this_cpu_read(irqsave_flags);
  300. __bpf_spin_unlock(lock);
  301. local_irq_restore(flags);
  302. }
  303. NOTRACE_BPF_CALL_1(bpf_spin_unlock, struct bpf_spin_lock *, lock)
  304. {
  305. __bpf_spin_unlock_irqrestore(lock);
  306. return 0;
  307. }
  308. const struct bpf_func_proto bpf_spin_unlock_proto = {
  309. .func = bpf_spin_unlock,
  310. .gpl_only = false,
  311. .ret_type = RET_VOID,
  312. .arg1_type = ARG_PTR_TO_SPIN_LOCK,
  313. .arg1_btf_id = BPF_PTR_POISON,
  314. };
  315. void copy_map_value_locked(struct bpf_map *map, void *dst, void *src,
  316. bool lock_src)
  317. {
  318. struct bpf_spin_lock *lock;
  319. if (lock_src)
  320. lock = src + map->record->spin_lock_off;
  321. else
  322. lock = dst + map->record->spin_lock_off;
  323. preempt_disable();
  324. __bpf_spin_lock_irqsave(lock);
  325. copy_map_value(map, dst, src);
  326. __bpf_spin_unlock_irqrestore(lock);
  327. preempt_enable();
  328. }
  329. BPF_CALL_0(bpf_jiffies64)
  330. {
  331. return get_jiffies_64();
  332. }
  333. const struct bpf_func_proto bpf_jiffies64_proto = {
  334. .func = bpf_jiffies64,
  335. .gpl_only = false,
  336. .ret_type = RET_INTEGER,
  337. };
  338. #ifdef CONFIG_CGROUPS
  339. BPF_CALL_0(bpf_get_current_cgroup_id)
  340. {
  341. struct cgroup *cgrp;
  342. u64 cgrp_id;
  343. rcu_read_lock();
  344. cgrp = task_dfl_cgroup(current);
  345. cgrp_id = cgroup_id(cgrp);
  346. rcu_read_unlock();
  347. return cgrp_id;
  348. }
  349. const struct bpf_func_proto bpf_get_current_cgroup_id_proto = {
  350. .func = bpf_get_current_cgroup_id,
  351. .gpl_only = false,
  352. .ret_type = RET_INTEGER,
  353. };
  354. BPF_CALL_1(bpf_get_current_ancestor_cgroup_id, int, ancestor_level)
  355. {
  356. struct cgroup *cgrp;
  357. struct cgroup *ancestor;
  358. u64 cgrp_id;
  359. rcu_read_lock();
  360. cgrp = task_dfl_cgroup(current);
  361. ancestor = cgroup_ancestor(cgrp, ancestor_level);
  362. cgrp_id = ancestor ? cgroup_id(ancestor) : 0;
  363. rcu_read_unlock();
  364. return cgrp_id;
  365. }
  366. const struct bpf_func_proto bpf_get_current_ancestor_cgroup_id_proto = {
  367. .func = bpf_get_current_ancestor_cgroup_id,
  368. .gpl_only = false,
  369. .ret_type = RET_INTEGER,
  370. .arg1_type = ARG_ANYTHING,
  371. };
  372. #endif /* CONFIG_CGROUPS */
  373. #define BPF_STRTOX_BASE_MASK 0x1F
  374. static int __bpf_strtoull(const char *buf, size_t buf_len, u64 flags,
  375. unsigned long long *res, bool *is_negative)
  376. {
  377. unsigned int base = flags & BPF_STRTOX_BASE_MASK;
  378. const char *cur_buf = buf;
  379. size_t cur_len = buf_len;
  380. unsigned int consumed;
  381. size_t val_len;
  382. char str[64];
  383. if (!buf || !buf_len || !res || !is_negative)
  384. return -EINVAL;
  385. if (base != 0 && base != 8 && base != 10 && base != 16)
  386. return -EINVAL;
  387. if (flags & ~BPF_STRTOX_BASE_MASK)
  388. return -EINVAL;
  389. while (cur_buf < buf + buf_len && isspace(*cur_buf))
  390. ++cur_buf;
  391. *is_negative = (cur_buf < buf + buf_len && *cur_buf == '-');
  392. if (*is_negative)
  393. ++cur_buf;
  394. consumed = cur_buf - buf;
  395. cur_len -= consumed;
  396. if (!cur_len)
  397. return -EINVAL;
  398. cur_len = min(cur_len, sizeof(str) - 1);
  399. memcpy(str, cur_buf, cur_len);
  400. str[cur_len] = '\0';
  401. cur_buf = str;
  402. cur_buf = _parse_integer_fixup_radix(cur_buf, &base);
  403. val_len = _parse_integer(cur_buf, base, res);
  404. if (val_len & KSTRTOX_OVERFLOW)
  405. return -ERANGE;
  406. if (val_len == 0)
  407. return -EINVAL;
  408. cur_buf += val_len;
  409. consumed += cur_buf - str;
  410. return consumed;
  411. }
  412. static int __bpf_strtoll(const char *buf, size_t buf_len, u64 flags,
  413. long long *res)
  414. {
  415. unsigned long long _res;
  416. bool is_negative;
  417. int err;
  418. err = __bpf_strtoull(buf, buf_len, flags, &_res, &is_negative);
  419. if (err < 0)
  420. return err;
  421. if (is_negative) {
  422. if ((long long)-_res > 0)
  423. return -ERANGE;
  424. *res = -_res;
  425. } else {
  426. if ((long long)_res < 0)
  427. return -ERANGE;
  428. *res = _res;
  429. }
  430. return err;
  431. }
  432. BPF_CALL_4(bpf_strtol, const char *, buf, size_t, buf_len, u64, flags,
  433. s64 *, res)
  434. {
  435. long long _res;
  436. int err;
  437. *res = 0;
  438. err = __bpf_strtoll(buf, buf_len, flags, &_res);
  439. if (err < 0)
  440. return err;
  441. *res = _res;
  442. return err;
  443. }
  444. const struct bpf_func_proto bpf_strtol_proto = {
  445. .func = bpf_strtol,
  446. .gpl_only = false,
  447. .ret_type = RET_INTEGER,
  448. .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY,
  449. .arg2_type = ARG_CONST_SIZE,
  450. .arg3_type = ARG_ANYTHING,
  451. .arg4_type = ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_WRITE | MEM_ALIGNED,
  452. .arg4_size = sizeof(s64),
  453. };
  454. BPF_CALL_4(bpf_strtoul, const char *, buf, size_t, buf_len, u64, flags,
  455. u64 *, res)
  456. {
  457. unsigned long long _res;
  458. bool is_negative;
  459. int err;
  460. *res = 0;
  461. err = __bpf_strtoull(buf, buf_len, flags, &_res, &is_negative);
  462. if (err < 0)
  463. return err;
  464. if (is_negative)
  465. return -EINVAL;
  466. *res = _res;
  467. return err;
  468. }
  469. const struct bpf_func_proto bpf_strtoul_proto = {
  470. .func = bpf_strtoul,
  471. .gpl_only = false,
  472. .ret_type = RET_INTEGER,
  473. .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY,
  474. .arg2_type = ARG_CONST_SIZE,
  475. .arg3_type = ARG_ANYTHING,
  476. .arg4_type = ARG_PTR_TO_FIXED_SIZE_MEM | MEM_UNINIT | MEM_WRITE | MEM_ALIGNED,
  477. .arg4_size = sizeof(u64),
  478. };
  479. BPF_CALL_3(bpf_strncmp, const char *, s1, u32, s1_sz, const char *, s2)
  480. {
  481. return strncmp(s1, s2, s1_sz);
  482. }
  483. static const struct bpf_func_proto bpf_strncmp_proto = {
  484. .func = bpf_strncmp,
  485. .gpl_only = false,
  486. .ret_type = RET_INTEGER,
  487. .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY,
  488. .arg2_type = ARG_CONST_SIZE,
  489. .arg3_type = ARG_PTR_TO_CONST_STR,
  490. };
  491. BPF_CALL_4(bpf_get_ns_current_pid_tgid, u64, dev, u64, ino,
  492. struct bpf_pidns_info *, nsdata, u32, size)
  493. {
  494. struct task_struct *task = current;
  495. struct pid_namespace *pidns;
  496. int err = -EINVAL;
  497. if (unlikely(size != sizeof(struct bpf_pidns_info)))
  498. goto clear;
  499. if (unlikely((u64)(dev_t)dev != dev))
  500. goto clear;
  501. if (unlikely(!task))
  502. goto clear;
  503. pidns = task_active_pid_ns(task);
  504. if (unlikely(!pidns)) {
  505. err = -ENOENT;
  506. goto clear;
  507. }
  508. if (!ns_match(&pidns->ns, (dev_t)dev, ino))
  509. goto clear;
  510. nsdata->pid = task_pid_nr_ns(task, pidns);
  511. nsdata->tgid = task_tgid_nr_ns(task, pidns);
  512. return 0;
  513. clear:
  514. memset((void *)nsdata, 0, (size_t) size);
  515. return err;
  516. }
  517. const struct bpf_func_proto bpf_get_ns_current_pid_tgid_proto = {
  518. .func = bpf_get_ns_current_pid_tgid,
  519. .gpl_only = false,
  520. .ret_type = RET_INTEGER,
  521. .arg1_type = ARG_ANYTHING,
  522. .arg2_type = ARG_ANYTHING,
  523. .arg3_type = ARG_PTR_TO_UNINIT_MEM,
  524. .arg4_type = ARG_CONST_SIZE,
  525. };
  526. static const struct bpf_func_proto bpf_get_raw_smp_processor_id_proto = {
  527. .func = bpf_get_raw_cpu_id,
  528. .gpl_only = false,
  529. .ret_type = RET_INTEGER,
  530. };
  531. BPF_CALL_5(bpf_event_output_data, void *, ctx, struct bpf_map *, map,
  532. u64, flags, void *, data, u64, size)
  533. {
  534. if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
  535. return -EINVAL;
  536. return bpf_event_output(map, flags, data, size, NULL, 0, NULL);
  537. }
  538. const struct bpf_func_proto bpf_event_output_data_proto = {
  539. .func = bpf_event_output_data,
  540. .gpl_only = true,
  541. .ret_type = RET_INTEGER,
  542. .arg1_type = ARG_PTR_TO_CTX,
  543. .arg2_type = ARG_CONST_MAP_PTR,
  544. .arg3_type = ARG_ANYTHING,
  545. .arg4_type = ARG_PTR_TO_MEM | MEM_RDONLY,
  546. .arg5_type = ARG_CONST_SIZE_OR_ZERO,
  547. };
  548. BPF_CALL_3(bpf_copy_from_user, void *, dst, u32, size,
  549. const void __user *, user_ptr)
  550. {
  551. int ret = copy_from_user(dst, user_ptr, size);
  552. if (unlikely(ret)) {
  553. memset(dst, 0, size);
  554. ret = -EFAULT;
  555. }
  556. return ret;
  557. }
  558. const struct bpf_func_proto bpf_copy_from_user_proto = {
  559. .func = bpf_copy_from_user,
  560. .gpl_only = false,
  561. .might_sleep = true,
  562. .ret_type = RET_INTEGER,
  563. .arg1_type = ARG_PTR_TO_UNINIT_MEM,
  564. .arg2_type = ARG_CONST_SIZE_OR_ZERO,
  565. .arg3_type = ARG_ANYTHING,
  566. };
  567. BPF_CALL_5(bpf_copy_from_user_task, void *, dst, u32, size,
  568. const void __user *, user_ptr, struct task_struct *, tsk, u64, flags)
  569. {
  570. int ret;
  571. /* flags is not used yet */
  572. if (unlikely(flags))
  573. return -EINVAL;
  574. if (unlikely(!size))
  575. return 0;
  576. ret = access_process_vm(tsk, (unsigned long)user_ptr, dst, size, 0);
  577. if (ret == size)
  578. return 0;
  579. memset(dst, 0, size);
  580. /* Return -EFAULT for partial read */
  581. return ret < 0 ? ret : -EFAULT;
  582. }
  583. const struct bpf_func_proto bpf_copy_from_user_task_proto = {
  584. .func = bpf_copy_from_user_task,
  585. .gpl_only = true,
  586. .might_sleep = true,
  587. .ret_type = RET_INTEGER,
  588. .arg1_type = ARG_PTR_TO_UNINIT_MEM,
  589. .arg2_type = ARG_CONST_SIZE_OR_ZERO,
  590. .arg3_type = ARG_ANYTHING,
  591. .arg4_type = ARG_PTR_TO_BTF_ID,
  592. .arg4_btf_id = &btf_tracing_ids[BTF_TRACING_TYPE_TASK],
  593. .arg5_type = ARG_ANYTHING
  594. };
  595. BPF_CALL_2(bpf_per_cpu_ptr, const void *, ptr, u32, cpu)
  596. {
  597. if (cpu >= nr_cpu_ids)
  598. return (unsigned long)NULL;
  599. return (unsigned long)per_cpu_ptr((const void __percpu *)(const uintptr_t)ptr, cpu);
  600. }
  601. const struct bpf_func_proto bpf_per_cpu_ptr_proto = {
  602. .func = bpf_per_cpu_ptr,
  603. .gpl_only = false,
  604. .ret_type = RET_PTR_TO_MEM_OR_BTF_ID | PTR_MAYBE_NULL | MEM_RDONLY,
  605. .arg1_type = ARG_PTR_TO_PERCPU_BTF_ID,
  606. .arg2_type = ARG_ANYTHING,
  607. };
  608. BPF_CALL_1(bpf_this_cpu_ptr, const void *, percpu_ptr)
  609. {
  610. return (unsigned long)this_cpu_ptr((const void __percpu *)(const uintptr_t)percpu_ptr);
  611. }
  612. const struct bpf_func_proto bpf_this_cpu_ptr_proto = {
  613. .func = bpf_this_cpu_ptr,
  614. .gpl_only = false,
  615. .ret_type = RET_PTR_TO_MEM_OR_BTF_ID | MEM_RDONLY,
  616. .arg1_type = ARG_PTR_TO_PERCPU_BTF_ID,
  617. };
  618. static int bpf_trace_copy_string(char *buf, void *unsafe_ptr, char fmt_ptype,
  619. size_t bufsz)
  620. {
  621. void __user *user_ptr = (__force void __user *)unsafe_ptr;
  622. buf[0] = 0;
  623. switch (fmt_ptype) {
  624. case 's':
  625. #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
  626. if ((unsigned long)unsafe_ptr < TASK_SIZE)
  627. return strncpy_from_user_nofault(buf, user_ptr, bufsz);
  628. fallthrough;
  629. #endif
  630. case 'k':
  631. return strncpy_from_kernel_nofault(buf, unsafe_ptr, bufsz);
  632. case 'u':
  633. return strncpy_from_user_nofault(buf, user_ptr, bufsz);
  634. }
  635. return -EINVAL;
  636. }
  637. /* Per-cpu temp buffers used by printf-like helpers to store the bprintf binary
  638. * arguments representation.
  639. */
  640. #define MAX_BPRINTF_BIN_ARGS 512
  641. /* Support executing three nested bprintf helper calls on a given CPU */
  642. #define MAX_BPRINTF_NEST_LEVEL 3
  643. struct bpf_bprintf_buffers {
  644. char bin_args[MAX_BPRINTF_BIN_ARGS];
  645. char buf[MAX_BPRINTF_BUF];
  646. };
  647. static DEFINE_PER_CPU(struct bpf_bprintf_buffers[MAX_BPRINTF_NEST_LEVEL], bpf_bprintf_bufs);
  648. static DEFINE_PER_CPU(int, bpf_bprintf_nest_level);
  649. static int try_get_buffers(struct bpf_bprintf_buffers **bufs)
  650. {
  651. int nest_level;
  652. preempt_disable();
  653. nest_level = this_cpu_inc_return(bpf_bprintf_nest_level);
  654. if (WARN_ON_ONCE(nest_level > MAX_BPRINTF_NEST_LEVEL)) {
  655. this_cpu_dec(bpf_bprintf_nest_level);
  656. preempt_enable();
  657. return -EBUSY;
  658. }
  659. *bufs = this_cpu_ptr(&bpf_bprintf_bufs[nest_level - 1]);
  660. return 0;
  661. }
  662. void bpf_bprintf_cleanup(struct bpf_bprintf_data *data)
  663. {
  664. if (!data->bin_args && !data->buf)
  665. return;
  666. if (WARN_ON_ONCE(this_cpu_read(bpf_bprintf_nest_level) == 0))
  667. return;
  668. this_cpu_dec(bpf_bprintf_nest_level);
  669. preempt_enable();
  670. }
  671. /*
  672. * bpf_bprintf_prepare - Generic pass on format strings for bprintf-like helpers
  673. *
  674. * Returns a negative value if fmt is an invalid format string or 0 otherwise.
  675. *
  676. * This can be used in two ways:
  677. * - Format string verification only: when data->get_bin_args is false
  678. * - Arguments preparation: in addition to the above verification, it writes in
  679. * data->bin_args a binary representation of arguments usable by bstr_printf
  680. * where pointers from BPF have been sanitized.
  681. *
  682. * In argument preparation mode, if 0 is returned, safe temporary buffers are
  683. * allocated and bpf_bprintf_cleanup should be called to free them after use.
  684. */
  685. int bpf_bprintf_prepare(char *fmt, u32 fmt_size, const u64 *raw_args,
  686. u32 num_args, struct bpf_bprintf_data *data)
  687. {
  688. bool get_buffers = (data->get_bin_args && num_args) || data->get_buf;
  689. char *unsafe_ptr = NULL, *tmp_buf = NULL, *tmp_buf_end, *fmt_end;
  690. struct bpf_bprintf_buffers *buffers = NULL;
  691. size_t sizeof_cur_arg, sizeof_cur_ip;
  692. int err, i, num_spec = 0;
  693. u64 cur_arg;
  694. char fmt_ptype, cur_ip[16], ip_spec[] = "%pXX";
  695. fmt_end = strnchr(fmt, fmt_size, 0);
  696. if (!fmt_end)
  697. return -EINVAL;
  698. fmt_size = fmt_end - fmt;
  699. if (get_buffers && try_get_buffers(&buffers))
  700. return -EBUSY;
  701. if (data->get_bin_args) {
  702. if (num_args)
  703. tmp_buf = buffers->bin_args;
  704. tmp_buf_end = tmp_buf + MAX_BPRINTF_BIN_ARGS;
  705. data->bin_args = (u32 *)tmp_buf;
  706. }
  707. if (data->get_buf)
  708. data->buf = buffers->buf;
  709. for (i = 0; i < fmt_size; i++) {
  710. if ((!isprint(fmt[i]) && !isspace(fmt[i])) || !isascii(fmt[i])) {
  711. err = -EINVAL;
  712. goto out;
  713. }
  714. if (fmt[i] != '%')
  715. continue;
  716. if (fmt[i + 1] == '%') {
  717. i++;
  718. continue;
  719. }
  720. if (num_spec >= num_args) {
  721. err = -EINVAL;
  722. goto out;
  723. }
  724. /* The string is zero-terminated so if fmt[i] != 0, we can
  725. * always access fmt[i + 1], in the worst case it will be a 0
  726. */
  727. i++;
  728. /* skip optional "[0 +-][num]" width formatting field */
  729. while (fmt[i] == '0' || fmt[i] == '+' || fmt[i] == '-' ||
  730. fmt[i] == ' ')
  731. i++;
  732. if (fmt[i] >= '1' && fmt[i] <= '9') {
  733. i++;
  734. while (fmt[i] >= '0' && fmt[i] <= '9')
  735. i++;
  736. }
  737. if (fmt[i] == 'p') {
  738. sizeof_cur_arg = sizeof(long);
  739. if (fmt[i + 1] == 0 || isspace(fmt[i + 1]) ||
  740. ispunct(fmt[i + 1])) {
  741. if (tmp_buf)
  742. cur_arg = raw_args[num_spec];
  743. goto nocopy_fmt;
  744. }
  745. if ((fmt[i + 1] == 'k' || fmt[i + 1] == 'u') &&
  746. fmt[i + 2] == 's') {
  747. fmt_ptype = fmt[i + 1];
  748. i += 2;
  749. goto fmt_str;
  750. }
  751. if (fmt[i + 1] == 'K' ||
  752. fmt[i + 1] == 'x' || fmt[i + 1] == 's' ||
  753. fmt[i + 1] == 'S') {
  754. if (tmp_buf)
  755. cur_arg = raw_args[num_spec];
  756. i++;
  757. goto nocopy_fmt;
  758. }
  759. if (fmt[i + 1] == 'B') {
  760. if (tmp_buf) {
  761. err = snprintf(tmp_buf,
  762. (tmp_buf_end - tmp_buf),
  763. "%pB",
  764. (void *)(long)raw_args[num_spec]);
  765. tmp_buf += (err + 1);
  766. }
  767. i++;
  768. num_spec++;
  769. continue;
  770. }
  771. /* only support "%pI4", "%pi4", "%pI6" and "%pi6". */
  772. if ((fmt[i + 1] != 'i' && fmt[i + 1] != 'I') ||
  773. (fmt[i + 2] != '4' && fmt[i + 2] != '6')) {
  774. err = -EINVAL;
  775. goto out;
  776. }
  777. i += 2;
  778. if (!tmp_buf)
  779. goto nocopy_fmt;
  780. sizeof_cur_ip = (fmt[i] == '4') ? 4 : 16;
  781. if (tmp_buf_end - tmp_buf < sizeof_cur_ip) {
  782. err = -ENOSPC;
  783. goto out;
  784. }
  785. unsafe_ptr = (char *)(long)raw_args[num_spec];
  786. err = copy_from_kernel_nofault(cur_ip, unsafe_ptr,
  787. sizeof_cur_ip);
  788. if (err < 0)
  789. memset(cur_ip, 0, sizeof_cur_ip);
  790. /* hack: bstr_printf expects IP addresses to be
  791. * pre-formatted as strings, ironically, the easiest way
  792. * to do that is to call snprintf.
  793. */
  794. ip_spec[2] = fmt[i - 1];
  795. ip_spec[3] = fmt[i];
  796. err = snprintf(tmp_buf, tmp_buf_end - tmp_buf,
  797. ip_spec, &cur_ip);
  798. tmp_buf += err + 1;
  799. num_spec++;
  800. continue;
  801. } else if (fmt[i] == 's') {
  802. fmt_ptype = fmt[i];
  803. fmt_str:
  804. if (fmt[i + 1] != 0 &&
  805. !isspace(fmt[i + 1]) &&
  806. !ispunct(fmt[i + 1])) {
  807. err = -EINVAL;
  808. goto out;
  809. }
  810. if (!tmp_buf)
  811. goto nocopy_fmt;
  812. if (tmp_buf_end == tmp_buf) {
  813. err = -ENOSPC;
  814. goto out;
  815. }
  816. unsafe_ptr = (char *)(long)raw_args[num_spec];
  817. err = bpf_trace_copy_string(tmp_buf, unsafe_ptr,
  818. fmt_ptype,
  819. tmp_buf_end - tmp_buf);
  820. if (err < 0) {
  821. tmp_buf[0] = '\0';
  822. err = 1;
  823. }
  824. tmp_buf += err;
  825. num_spec++;
  826. continue;
  827. } else if (fmt[i] == 'c') {
  828. if (!tmp_buf)
  829. goto nocopy_fmt;
  830. if (tmp_buf_end == tmp_buf) {
  831. err = -ENOSPC;
  832. goto out;
  833. }
  834. *tmp_buf = raw_args[num_spec];
  835. tmp_buf++;
  836. num_spec++;
  837. continue;
  838. }
  839. sizeof_cur_arg = sizeof(int);
  840. if (fmt[i] == 'l') {
  841. sizeof_cur_arg = sizeof(long);
  842. i++;
  843. }
  844. if (fmt[i] == 'l') {
  845. sizeof_cur_arg = sizeof(long long);
  846. i++;
  847. }
  848. if (fmt[i] != 'i' && fmt[i] != 'd' && fmt[i] != 'u' &&
  849. fmt[i] != 'x' && fmt[i] != 'X') {
  850. err = -EINVAL;
  851. goto out;
  852. }
  853. if (tmp_buf)
  854. cur_arg = raw_args[num_spec];
  855. nocopy_fmt:
  856. if (tmp_buf) {
  857. tmp_buf = PTR_ALIGN(tmp_buf, sizeof(u32));
  858. if (tmp_buf_end - tmp_buf < sizeof_cur_arg) {
  859. err = -ENOSPC;
  860. goto out;
  861. }
  862. if (sizeof_cur_arg == 8) {
  863. *(u32 *)tmp_buf = *(u32 *)&cur_arg;
  864. *(u32 *)(tmp_buf + 4) = *((u32 *)&cur_arg + 1);
  865. } else {
  866. *(u32 *)tmp_buf = (u32)(long)cur_arg;
  867. }
  868. tmp_buf += sizeof_cur_arg;
  869. }
  870. num_spec++;
  871. }
  872. err = 0;
  873. out:
  874. if (err)
  875. bpf_bprintf_cleanup(data);
  876. return err;
  877. }
  878. BPF_CALL_5(bpf_snprintf, char *, str, u32, str_size, char *, fmt,
  879. const void *, args, u32, data_len)
  880. {
  881. struct bpf_bprintf_data data = {
  882. .get_bin_args = true,
  883. };
  884. int err, num_args;
  885. if (data_len % 8 || data_len > MAX_BPRINTF_VARARGS * 8 ||
  886. (data_len && !args))
  887. return -EINVAL;
  888. num_args = data_len / 8;
  889. /* ARG_PTR_TO_CONST_STR guarantees that fmt is zero-terminated so we
  890. * can safely give an unbounded size.
  891. */
  892. err = bpf_bprintf_prepare(fmt, UINT_MAX, args, num_args, &data);
  893. if (err < 0)
  894. return err;
  895. err = bstr_printf(str, str_size, fmt, data.bin_args);
  896. bpf_bprintf_cleanup(&data);
  897. return err + 1;
  898. }
  899. const struct bpf_func_proto bpf_snprintf_proto = {
  900. .func = bpf_snprintf,
  901. .gpl_only = true,
  902. .ret_type = RET_INTEGER,
  903. .arg1_type = ARG_PTR_TO_MEM_OR_NULL,
  904. .arg2_type = ARG_CONST_SIZE_OR_ZERO,
  905. .arg3_type = ARG_PTR_TO_CONST_STR,
  906. .arg4_type = ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
  907. .arg5_type = ARG_CONST_SIZE_OR_ZERO,
  908. };
  909. struct bpf_async_cb {
  910. struct bpf_map *map;
  911. struct bpf_prog *prog;
  912. void __rcu *callback_fn;
  913. void *value;
  914. union {
  915. struct rcu_head rcu;
  916. struct work_struct delete_work;
  917. };
  918. u64 flags;
  919. };
  920. /* BPF map elements can contain 'struct bpf_timer'.
  921. * Such map owns all of its BPF timers.
  922. * 'struct bpf_timer' is allocated as part of map element allocation
  923. * and it's zero initialized.
  924. * That space is used to keep 'struct bpf_async_kern'.
  925. * bpf_timer_init() allocates 'struct bpf_hrtimer', inits hrtimer, and
  926. * remembers 'struct bpf_map *' pointer it's part of.
  927. * bpf_timer_set_callback() increments prog refcnt and assign bpf callback_fn.
  928. * bpf_timer_start() arms the timer.
  929. * If user space reference to a map goes to zero at this point
  930. * ops->map_release_uref callback is responsible for cancelling the timers,
  931. * freeing their memory, and decrementing prog's refcnts.
  932. * bpf_timer_cancel() cancels the timer and decrements prog's refcnt.
  933. * Inner maps can contain bpf timers as well. ops->map_release_uref is
  934. * freeing the timers when inner map is replaced or deleted by user space.
  935. */
  936. struct bpf_hrtimer {
  937. struct bpf_async_cb cb;
  938. struct hrtimer timer;
  939. atomic_t cancelling;
  940. };
  941. struct bpf_work {
  942. struct bpf_async_cb cb;
  943. struct work_struct work;
  944. struct work_struct delete_work;
  945. };
  946. /* the actual struct hidden inside uapi struct bpf_timer and bpf_wq */
  947. struct bpf_async_kern {
  948. union {
  949. struct bpf_async_cb *cb;
  950. struct bpf_hrtimer *timer;
  951. struct bpf_work *work;
  952. };
  953. /* bpf_spin_lock is used here instead of spinlock_t to make
  954. * sure that it always fits into space reserved by struct bpf_timer
  955. * regardless of LOCKDEP and spinlock debug flags.
  956. */
  957. struct bpf_spin_lock lock;
  958. } __attribute__((aligned(8)));
  959. enum bpf_async_type {
  960. BPF_ASYNC_TYPE_TIMER = 0,
  961. BPF_ASYNC_TYPE_WQ,
  962. };
  963. static DEFINE_PER_CPU(struct bpf_hrtimer *, hrtimer_running);
  964. static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer)
  965. {
  966. struct bpf_hrtimer *t = container_of(hrtimer, struct bpf_hrtimer, timer);
  967. struct bpf_map *map = t->cb.map;
  968. void *value = t->cb.value;
  969. bpf_callback_t callback_fn;
  970. void *key;
  971. u32 idx;
  972. BTF_TYPE_EMIT(struct bpf_timer);
  973. callback_fn = rcu_dereference_check(t->cb.callback_fn, rcu_read_lock_bh_held());
  974. if (!callback_fn)
  975. goto out;
  976. /* bpf_timer_cb() runs in hrtimer_run_softirq. It doesn't migrate and
  977. * cannot be preempted by another bpf_timer_cb() on the same cpu.
  978. * Remember the timer this callback is servicing to prevent
  979. * deadlock if callback_fn() calls bpf_timer_cancel() or
  980. * bpf_map_delete_elem() on the same timer.
  981. */
  982. this_cpu_write(hrtimer_running, t);
  983. if (map->map_type == BPF_MAP_TYPE_ARRAY) {
  984. struct bpf_array *array = container_of(map, struct bpf_array, map);
  985. /* compute the key */
  986. idx = ((char *)value - array->value) / array->elem_size;
  987. key = &idx;
  988. } else { /* hash or lru */
  989. key = value - round_up(map->key_size, 8);
  990. }
  991. callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
  992. /* The verifier checked that return value is zero. */
  993. this_cpu_write(hrtimer_running, NULL);
  994. out:
  995. return HRTIMER_NORESTART;
  996. }
  997. static void bpf_wq_work(struct work_struct *work)
  998. {
  999. struct bpf_work *w = container_of(work, struct bpf_work, work);
  1000. struct bpf_async_cb *cb = &w->cb;
  1001. struct bpf_map *map = cb->map;
  1002. bpf_callback_t callback_fn;
  1003. void *value = cb->value;
  1004. void *key;
  1005. u32 idx;
  1006. BTF_TYPE_EMIT(struct bpf_wq);
  1007. callback_fn = READ_ONCE(cb->callback_fn);
  1008. if (!callback_fn)
  1009. return;
  1010. if (map->map_type == BPF_MAP_TYPE_ARRAY) {
  1011. struct bpf_array *array = container_of(map, struct bpf_array, map);
  1012. /* compute the key */
  1013. idx = ((char *)value - array->value) / array->elem_size;
  1014. key = &idx;
  1015. } else { /* hash or lru */
  1016. key = value - round_up(map->key_size, 8);
  1017. }
  1018. rcu_read_lock_trace();
  1019. migrate_disable();
  1020. callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
  1021. migrate_enable();
  1022. rcu_read_unlock_trace();
  1023. }
  1024. static void bpf_wq_delete_work(struct work_struct *work)
  1025. {
  1026. struct bpf_work *w = container_of(work, struct bpf_work, delete_work);
  1027. cancel_work_sync(&w->work);
  1028. kfree_rcu(w, cb.rcu);
  1029. }
  1030. static void bpf_timer_delete_work(struct work_struct *work)
  1031. {
  1032. struct bpf_hrtimer *t = container_of(work, struct bpf_hrtimer, cb.delete_work);
  1033. /* Cancel the timer and wait for callback to complete if it was running.
  1034. * If hrtimer_cancel() can be safely called it's safe to call
  1035. * kfree_rcu(t) right after for both preallocated and non-preallocated
  1036. * maps. The async->cb = NULL was already done and no code path can see
  1037. * address 't' anymore. Timer if armed for existing bpf_hrtimer before
  1038. * bpf_timer_cancel_and_free will have been cancelled.
  1039. */
  1040. hrtimer_cancel(&t->timer);
  1041. kfree_rcu(t, cb.rcu);
  1042. }
  1043. static int __bpf_async_init(struct bpf_async_kern *async, struct bpf_map *map, u64 flags,
  1044. enum bpf_async_type type)
  1045. {
  1046. struct bpf_async_cb *cb;
  1047. struct bpf_hrtimer *t;
  1048. struct bpf_work *w;
  1049. clockid_t clockid;
  1050. size_t size;
  1051. int ret = 0;
  1052. if (in_nmi())
  1053. return -EOPNOTSUPP;
  1054. switch (type) {
  1055. case BPF_ASYNC_TYPE_TIMER:
  1056. size = sizeof(struct bpf_hrtimer);
  1057. break;
  1058. case BPF_ASYNC_TYPE_WQ:
  1059. size = sizeof(struct bpf_work);
  1060. break;
  1061. default:
  1062. return -EINVAL;
  1063. }
  1064. __bpf_spin_lock_irqsave(&async->lock);
  1065. t = async->timer;
  1066. if (t) {
  1067. ret = -EBUSY;
  1068. goto out;
  1069. }
  1070. /* Allocate via bpf_map_kmalloc_node() for memcg accounting. Until
  1071. * kmalloc_nolock() is available, avoid locking issues by using
  1072. * __GFP_HIGH (GFP_ATOMIC & ~__GFP_RECLAIM).
  1073. */
  1074. cb = bpf_map_kmalloc_node(map, size, __GFP_HIGH, map->numa_node);
  1075. if (!cb) {
  1076. ret = -ENOMEM;
  1077. goto out;
  1078. }
  1079. switch (type) {
  1080. case BPF_ASYNC_TYPE_TIMER:
  1081. clockid = flags & (MAX_CLOCKS - 1);
  1082. t = (struct bpf_hrtimer *)cb;
  1083. atomic_set(&t->cancelling, 0);
  1084. INIT_WORK(&t->cb.delete_work, bpf_timer_delete_work);
  1085. hrtimer_init(&t->timer, clockid, HRTIMER_MODE_REL_SOFT);
  1086. t->timer.function = bpf_timer_cb;
  1087. cb->value = (void *)async - map->record->timer_off;
  1088. break;
  1089. case BPF_ASYNC_TYPE_WQ:
  1090. w = (struct bpf_work *)cb;
  1091. INIT_WORK(&w->work, bpf_wq_work);
  1092. INIT_WORK(&w->delete_work, bpf_wq_delete_work);
  1093. cb->value = (void *)async - map->record->wq_off;
  1094. break;
  1095. }
  1096. cb->map = map;
  1097. cb->prog = NULL;
  1098. cb->flags = flags;
  1099. rcu_assign_pointer(cb->callback_fn, NULL);
  1100. WRITE_ONCE(async->cb, cb);
  1101. /* Guarantee the order between async->cb and map->usercnt. So
  1102. * when there are concurrent uref release and bpf timer init, either
  1103. * bpf_timer_cancel_and_free() called by uref release reads a no-NULL
  1104. * timer or atomic64_read() below returns a zero usercnt.
  1105. */
  1106. smp_mb();
  1107. if (!atomic64_read(&map->usercnt)) {
  1108. /* maps with timers must be either held by user space
  1109. * or pinned in bpffs.
  1110. */
  1111. WRITE_ONCE(async->cb, NULL);
  1112. kfree(cb);
  1113. ret = -EPERM;
  1114. }
  1115. out:
  1116. __bpf_spin_unlock_irqrestore(&async->lock);
  1117. return ret;
  1118. }
  1119. BPF_CALL_3(bpf_timer_init, struct bpf_async_kern *, timer, struct bpf_map *, map,
  1120. u64, flags)
  1121. {
  1122. clock_t clockid = flags & (MAX_CLOCKS - 1);
  1123. BUILD_BUG_ON(MAX_CLOCKS != 16);
  1124. BUILD_BUG_ON(sizeof(struct bpf_async_kern) > sizeof(struct bpf_timer));
  1125. BUILD_BUG_ON(__alignof__(struct bpf_async_kern) != __alignof__(struct bpf_timer));
  1126. if (flags >= MAX_CLOCKS ||
  1127. /* similar to timerfd except _ALARM variants are not supported */
  1128. (clockid != CLOCK_MONOTONIC &&
  1129. clockid != CLOCK_REALTIME &&
  1130. clockid != CLOCK_BOOTTIME))
  1131. return -EINVAL;
  1132. return __bpf_async_init(timer, map, flags, BPF_ASYNC_TYPE_TIMER);
  1133. }
  1134. static const struct bpf_func_proto bpf_timer_init_proto = {
  1135. .func = bpf_timer_init,
  1136. .gpl_only = true,
  1137. .ret_type = RET_INTEGER,
  1138. .arg1_type = ARG_PTR_TO_TIMER,
  1139. .arg2_type = ARG_CONST_MAP_PTR,
  1140. .arg3_type = ARG_ANYTHING,
  1141. };
  1142. static int __bpf_async_set_callback(struct bpf_async_kern *async, void *callback_fn,
  1143. struct bpf_prog_aux *aux, unsigned int flags,
  1144. enum bpf_async_type type)
  1145. {
  1146. struct bpf_prog *prev, *prog = aux->prog;
  1147. struct bpf_async_cb *cb;
  1148. int ret = 0;
  1149. if (in_nmi())
  1150. return -EOPNOTSUPP;
  1151. __bpf_spin_lock_irqsave(&async->lock);
  1152. cb = async->cb;
  1153. if (!cb) {
  1154. ret = -EINVAL;
  1155. goto out;
  1156. }
  1157. if (!atomic64_read(&cb->map->usercnt)) {
  1158. /* maps with timers must be either held by user space
  1159. * or pinned in bpffs. Otherwise timer might still be
  1160. * running even when bpf prog is detached and user space
  1161. * is gone, since map_release_uref won't ever be called.
  1162. */
  1163. ret = -EPERM;
  1164. goto out;
  1165. }
  1166. prev = cb->prog;
  1167. if (prev != prog) {
  1168. /* Bump prog refcnt once. Every bpf_timer_set_callback()
  1169. * can pick different callback_fn-s within the same prog.
  1170. */
  1171. prog = bpf_prog_inc_not_zero(prog);
  1172. if (IS_ERR(prog)) {
  1173. ret = PTR_ERR(prog);
  1174. goto out;
  1175. }
  1176. if (prev)
  1177. /* Drop prev prog refcnt when swapping with new prog */
  1178. bpf_prog_put(prev);
  1179. cb->prog = prog;
  1180. }
  1181. rcu_assign_pointer(cb->callback_fn, callback_fn);
  1182. out:
  1183. __bpf_spin_unlock_irqrestore(&async->lock);
  1184. return ret;
  1185. }
  1186. BPF_CALL_3(bpf_timer_set_callback, struct bpf_async_kern *, timer, void *, callback_fn,
  1187. struct bpf_prog_aux *, aux)
  1188. {
  1189. return __bpf_async_set_callback(timer, callback_fn, aux, 0, BPF_ASYNC_TYPE_TIMER);
  1190. }
  1191. static const struct bpf_func_proto bpf_timer_set_callback_proto = {
  1192. .func = bpf_timer_set_callback,
  1193. .gpl_only = true,
  1194. .ret_type = RET_INTEGER,
  1195. .arg1_type = ARG_PTR_TO_TIMER,
  1196. .arg2_type = ARG_PTR_TO_FUNC,
  1197. };
  1198. BPF_CALL_3(bpf_timer_start, struct bpf_async_kern *, timer, u64, nsecs, u64, flags)
  1199. {
  1200. struct bpf_hrtimer *t;
  1201. int ret = 0;
  1202. enum hrtimer_mode mode;
  1203. if (in_nmi())
  1204. return -EOPNOTSUPP;
  1205. if (flags & ~(BPF_F_TIMER_ABS | BPF_F_TIMER_CPU_PIN))
  1206. return -EINVAL;
  1207. __bpf_spin_lock_irqsave(&timer->lock);
  1208. t = timer->timer;
  1209. if (!t || !t->cb.prog) {
  1210. ret = -EINVAL;
  1211. goto out;
  1212. }
  1213. if (flags & BPF_F_TIMER_ABS)
  1214. mode = HRTIMER_MODE_ABS_SOFT;
  1215. else
  1216. mode = HRTIMER_MODE_REL_SOFT;
  1217. if (flags & BPF_F_TIMER_CPU_PIN)
  1218. mode |= HRTIMER_MODE_PINNED;
  1219. hrtimer_start(&t->timer, ns_to_ktime(nsecs), mode);
  1220. out:
  1221. __bpf_spin_unlock_irqrestore(&timer->lock);
  1222. return ret;
  1223. }
  1224. static const struct bpf_func_proto bpf_timer_start_proto = {
  1225. .func = bpf_timer_start,
  1226. .gpl_only = true,
  1227. .ret_type = RET_INTEGER,
  1228. .arg1_type = ARG_PTR_TO_TIMER,
  1229. .arg2_type = ARG_ANYTHING,
  1230. .arg3_type = ARG_ANYTHING,
  1231. };
  1232. static void drop_prog_refcnt(struct bpf_async_cb *async)
  1233. {
  1234. struct bpf_prog *prog = async->prog;
  1235. if (prog) {
  1236. bpf_prog_put(prog);
  1237. async->prog = NULL;
  1238. rcu_assign_pointer(async->callback_fn, NULL);
  1239. }
  1240. }
  1241. BPF_CALL_1(bpf_timer_cancel, struct bpf_async_kern *, timer)
  1242. {
  1243. struct bpf_hrtimer *t, *cur_t;
  1244. bool inc = false;
  1245. int ret = 0;
  1246. if (in_nmi())
  1247. return -EOPNOTSUPP;
  1248. rcu_read_lock();
  1249. __bpf_spin_lock_irqsave(&timer->lock);
  1250. t = timer->timer;
  1251. if (!t) {
  1252. ret = -EINVAL;
  1253. goto out;
  1254. }
  1255. cur_t = this_cpu_read(hrtimer_running);
  1256. if (cur_t == t) {
  1257. /* If bpf callback_fn is trying to bpf_timer_cancel()
  1258. * its own timer the hrtimer_cancel() will deadlock
  1259. * since it waits for callback_fn to finish.
  1260. */
  1261. ret = -EDEADLK;
  1262. goto out;
  1263. }
  1264. /* Only account in-flight cancellations when invoked from a timer
  1265. * callback, since we want to avoid waiting only if other _callbacks_
  1266. * are waiting on us, to avoid introducing lockups. Non-callback paths
  1267. * are ok, since nobody would synchronously wait for their completion.
  1268. */
  1269. if (!cur_t)
  1270. goto drop;
  1271. atomic_inc(&t->cancelling);
  1272. /* Need full barrier after relaxed atomic_inc */
  1273. smp_mb__after_atomic();
  1274. inc = true;
  1275. if (atomic_read(&cur_t->cancelling)) {
  1276. /* We're cancelling timer t, while some other timer callback is
  1277. * attempting to cancel us. In such a case, it might be possible
  1278. * that timer t belongs to the other callback, or some other
  1279. * callback waiting upon it (creating transitive dependencies
  1280. * upon us), and we will enter a deadlock if we continue
  1281. * cancelling and waiting for it synchronously, since it might
  1282. * do the same. Bail!
  1283. */
  1284. ret = -EDEADLK;
  1285. goto out;
  1286. }
  1287. drop:
  1288. drop_prog_refcnt(&t->cb);
  1289. out:
  1290. __bpf_spin_unlock_irqrestore(&timer->lock);
  1291. /* Cancel the timer and wait for associated callback to finish
  1292. * if it was running.
  1293. */
  1294. ret = ret ?: hrtimer_cancel(&t->timer);
  1295. if (inc)
  1296. atomic_dec(&t->cancelling);
  1297. rcu_read_unlock();
  1298. return ret;
  1299. }
  1300. static const struct bpf_func_proto bpf_timer_cancel_proto = {
  1301. .func = bpf_timer_cancel,
  1302. .gpl_only = true,
  1303. .ret_type = RET_INTEGER,
  1304. .arg1_type = ARG_PTR_TO_TIMER,
  1305. };
  1306. static struct bpf_async_cb *__bpf_async_cancel_and_free(struct bpf_async_kern *async)
  1307. {
  1308. struct bpf_async_cb *cb;
  1309. /* Performance optimization: read async->cb without lock first. */
  1310. if (!READ_ONCE(async->cb))
  1311. return NULL;
  1312. __bpf_spin_lock_irqsave(&async->lock);
  1313. /* re-read it under lock */
  1314. cb = async->cb;
  1315. if (!cb)
  1316. goto out;
  1317. drop_prog_refcnt(cb);
  1318. /* The subsequent bpf_timer_start/cancel() helpers won't be able to use
  1319. * this timer, since it won't be initialized.
  1320. */
  1321. WRITE_ONCE(async->cb, NULL);
  1322. out:
  1323. __bpf_spin_unlock_irqrestore(&async->lock);
  1324. return cb;
  1325. }
  1326. /* This function is called by map_delete/update_elem for individual element and
  1327. * by ops->map_release_uref when the user space reference to a map reaches zero.
  1328. */
  1329. void bpf_timer_cancel_and_free(void *val)
  1330. {
  1331. struct bpf_hrtimer *t;
  1332. t = (struct bpf_hrtimer *)__bpf_async_cancel_and_free(val);
  1333. if (!t)
  1334. return;
  1335. /* We check that bpf_map_delete/update_elem() was called from timer
  1336. * callback_fn. In such case we don't call hrtimer_cancel() (since it
  1337. * will deadlock) and don't call hrtimer_try_to_cancel() (since it will
  1338. * just return -1). Though callback_fn is still running on this cpu it's
  1339. * safe to do kfree(t) because bpf_timer_cb() read everything it needed
  1340. * from 't'. The bpf subprog callback_fn won't be able to access 't',
  1341. * since async->cb = NULL was already done. The timer will be
  1342. * effectively cancelled because bpf_timer_cb() will return
  1343. * HRTIMER_NORESTART.
  1344. *
  1345. * However, it is possible the timer callback_fn calling us armed the
  1346. * timer _before_ calling us, such that failing to cancel it here will
  1347. * cause it to possibly use struct hrtimer after freeing bpf_hrtimer.
  1348. * Therefore, we _need_ to cancel any outstanding timers before we do
  1349. * kfree_rcu, even though no more timers can be armed.
  1350. *
  1351. * Moreover, we need to schedule work even if timer does not belong to
  1352. * the calling callback_fn, as on two different CPUs, we can end up in a
  1353. * situation where both sides run in parallel, try to cancel one
  1354. * another, and we end up waiting on both sides in hrtimer_cancel
  1355. * without making forward progress, since timer1 depends on time2
  1356. * callback to finish, and vice versa.
  1357. *
  1358. * CPU 1 (timer1_cb) CPU 2 (timer2_cb)
  1359. * bpf_timer_cancel_and_free(timer2) bpf_timer_cancel_and_free(timer1)
  1360. *
  1361. * To avoid these issues, punt to workqueue context when we are in a
  1362. * timer callback.
  1363. */
  1364. if (this_cpu_read(hrtimer_running)) {
  1365. queue_work(system_unbound_wq, &t->cb.delete_work);
  1366. return;
  1367. }
  1368. if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
  1369. /* If the timer is running on other CPU, also use a kworker to
  1370. * wait for the completion of the timer instead of trying to
  1371. * acquire a sleepable lock in hrtimer_cancel() to wait for its
  1372. * completion.
  1373. */
  1374. if (hrtimer_try_to_cancel(&t->timer) >= 0)
  1375. kfree_rcu(t, cb.rcu);
  1376. else
  1377. queue_work(system_unbound_wq, &t->cb.delete_work);
  1378. } else {
  1379. bpf_timer_delete_work(&t->cb.delete_work);
  1380. }
  1381. }
  1382. /* This function is called by map_delete/update_elem for individual element and
  1383. * by ops->map_release_uref when the user space reference to a map reaches zero.
  1384. */
  1385. void bpf_wq_cancel_and_free(void *val)
  1386. {
  1387. struct bpf_work *work;
  1388. BTF_TYPE_EMIT(struct bpf_wq);
  1389. work = (struct bpf_work *)__bpf_async_cancel_and_free(val);
  1390. if (!work)
  1391. return;
  1392. /* Trigger cancel of the sleepable work, but *do not* wait for
  1393. * it to finish if it was running as we might not be in a
  1394. * sleepable context.
  1395. * kfree will be called once the work has finished.
  1396. */
  1397. schedule_work(&work->delete_work);
  1398. }
  1399. BPF_CALL_2(bpf_kptr_xchg, void *, dst, void *, ptr)
  1400. {
  1401. unsigned long *kptr = dst;
  1402. /* This helper may be inlined by verifier. */
  1403. return xchg(kptr, (unsigned long)ptr);
  1404. }
  1405. /* Unlike other PTR_TO_BTF_ID helpers the btf_id in bpf_kptr_xchg()
  1406. * helper is determined dynamically by the verifier. Use BPF_PTR_POISON to
  1407. * denote type that verifier will determine.
  1408. */
  1409. static const struct bpf_func_proto bpf_kptr_xchg_proto = {
  1410. .func = bpf_kptr_xchg,
  1411. .gpl_only = false,
  1412. .ret_type = RET_PTR_TO_BTF_ID_OR_NULL,
  1413. .ret_btf_id = BPF_PTR_POISON,
  1414. .arg1_type = ARG_KPTR_XCHG_DEST,
  1415. .arg2_type = ARG_PTR_TO_BTF_ID_OR_NULL | OBJ_RELEASE,
  1416. .arg2_btf_id = BPF_PTR_POISON,
  1417. };
  1418. /* Since the upper 8 bits of dynptr->size is reserved, the
  1419. * maximum supported size is 2^24 - 1.
  1420. */
  1421. #define DYNPTR_MAX_SIZE ((1UL << 24) - 1)
  1422. #define DYNPTR_TYPE_SHIFT 28
  1423. #define DYNPTR_SIZE_MASK 0xFFFFFF
  1424. #define DYNPTR_RDONLY_BIT BIT(31)
  1425. bool __bpf_dynptr_is_rdonly(const struct bpf_dynptr_kern *ptr)
  1426. {
  1427. return ptr->size & DYNPTR_RDONLY_BIT;
  1428. }
  1429. void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr)
  1430. {
  1431. ptr->size |= DYNPTR_RDONLY_BIT;
  1432. }
  1433. static void bpf_dynptr_set_type(struct bpf_dynptr_kern *ptr, enum bpf_dynptr_type type)
  1434. {
  1435. ptr->size |= type << DYNPTR_TYPE_SHIFT;
  1436. }
  1437. static enum bpf_dynptr_type bpf_dynptr_get_type(const struct bpf_dynptr_kern *ptr)
  1438. {
  1439. return (ptr->size & ~(DYNPTR_RDONLY_BIT)) >> DYNPTR_TYPE_SHIFT;
  1440. }
  1441. u32 __bpf_dynptr_size(const struct bpf_dynptr_kern *ptr)
  1442. {
  1443. return ptr->size & DYNPTR_SIZE_MASK;
  1444. }
  1445. static void bpf_dynptr_set_size(struct bpf_dynptr_kern *ptr, u32 new_size)
  1446. {
  1447. u32 metadata = ptr->size & ~DYNPTR_SIZE_MASK;
  1448. ptr->size = new_size | metadata;
  1449. }
  1450. int bpf_dynptr_check_size(u32 size)
  1451. {
  1452. return size > DYNPTR_MAX_SIZE ? -E2BIG : 0;
  1453. }
  1454. void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
  1455. enum bpf_dynptr_type type, u32 offset, u32 size)
  1456. {
  1457. ptr->data = data;
  1458. ptr->offset = offset;
  1459. ptr->size = size;
  1460. bpf_dynptr_set_type(ptr, type);
  1461. }
  1462. void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr)
  1463. {
  1464. memset(ptr, 0, sizeof(*ptr));
  1465. }
  1466. static int bpf_dynptr_check_off_len(const struct bpf_dynptr_kern *ptr, u32 offset, u32 len)
  1467. {
  1468. u32 size = __bpf_dynptr_size(ptr);
  1469. if (len > size || offset > size - len)
  1470. return -E2BIG;
  1471. return 0;
  1472. }
  1473. BPF_CALL_4(bpf_dynptr_from_mem, void *, data, u32, size, u64, flags, struct bpf_dynptr_kern *, ptr)
  1474. {
  1475. int err;
  1476. BTF_TYPE_EMIT(struct bpf_dynptr);
  1477. err = bpf_dynptr_check_size(size);
  1478. if (err)
  1479. goto error;
  1480. /* flags is currently unsupported */
  1481. if (flags) {
  1482. err = -EINVAL;
  1483. goto error;
  1484. }
  1485. bpf_dynptr_init(ptr, data, BPF_DYNPTR_TYPE_LOCAL, 0, size);
  1486. return 0;
  1487. error:
  1488. bpf_dynptr_set_null(ptr);
  1489. return err;
  1490. }
  1491. static const struct bpf_func_proto bpf_dynptr_from_mem_proto = {
  1492. .func = bpf_dynptr_from_mem,
  1493. .gpl_only = false,
  1494. .ret_type = RET_INTEGER,
  1495. .arg1_type = ARG_PTR_TO_UNINIT_MEM,
  1496. .arg2_type = ARG_CONST_SIZE_OR_ZERO,
  1497. .arg3_type = ARG_ANYTHING,
  1498. .arg4_type = ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL | MEM_UNINIT | MEM_WRITE,
  1499. };
  1500. BPF_CALL_5(bpf_dynptr_read, void *, dst, u32, len, const struct bpf_dynptr_kern *, src,
  1501. u32, offset, u64, flags)
  1502. {
  1503. enum bpf_dynptr_type type;
  1504. int err;
  1505. if (!src->data || flags)
  1506. return -EINVAL;
  1507. err = bpf_dynptr_check_off_len(src, offset, len);
  1508. if (err)
  1509. return err;
  1510. type = bpf_dynptr_get_type(src);
  1511. switch (type) {
  1512. case BPF_DYNPTR_TYPE_LOCAL:
  1513. case BPF_DYNPTR_TYPE_RINGBUF:
  1514. /* Source and destination may possibly overlap, hence use memmove to
  1515. * copy the data. E.g. bpf_dynptr_from_mem may create two dynptr
  1516. * pointing to overlapping PTR_TO_MAP_VALUE regions.
  1517. */
  1518. memmove(dst, src->data + src->offset + offset, len);
  1519. return 0;
  1520. case BPF_DYNPTR_TYPE_SKB:
  1521. return __bpf_skb_load_bytes(src->data, src->offset + offset, dst, len);
  1522. case BPF_DYNPTR_TYPE_XDP:
  1523. return __bpf_xdp_load_bytes(src->data, src->offset + offset, dst, len);
  1524. default:
  1525. WARN_ONCE(true, "bpf_dynptr_read: unknown dynptr type %d\n", type);
  1526. return -EFAULT;
  1527. }
  1528. }
  1529. static const struct bpf_func_proto bpf_dynptr_read_proto = {
  1530. .func = bpf_dynptr_read,
  1531. .gpl_only = false,
  1532. .ret_type = RET_INTEGER,
  1533. .arg1_type = ARG_PTR_TO_UNINIT_MEM,
  1534. .arg2_type = ARG_CONST_SIZE_OR_ZERO,
  1535. .arg3_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY,
  1536. .arg4_type = ARG_ANYTHING,
  1537. .arg5_type = ARG_ANYTHING,
  1538. };
  1539. BPF_CALL_5(bpf_dynptr_write, const struct bpf_dynptr_kern *, dst, u32, offset, void *, src,
  1540. u32, len, u64, flags)
  1541. {
  1542. enum bpf_dynptr_type type;
  1543. int err;
  1544. if (!dst->data || __bpf_dynptr_is_rdonly(dst))
  1545. return -EINVAL;
  1546. err = bpf_dynptr_check_off_len(dst, offset, len);
  1547. if (err)
  1548. return err;
  1549. type = bpf_dynptr_get_type(dst);
  1550. switch (type) {
  1551. case BPF_DYNPTR_TYPE_LOCAL:
  1552. case BPF_DYNPTR_TYPE_RINGBUF:
  1553. if (flags)
  1554. return -EINVAL;
  1555. /* Source and destination may possibly overlap, hence use memmove to
  1556. * copy the data. E.g. bpf_dynptr_from_mem may create two dynptr
  1557. * pointing to overlapping PTR_TO_MAP_VALUE regions.
  1558. */
  1559. memmove(dst->data + dst->offset + offset, src, len);
  1560. return 0;
  1561. case BPF_DYNPTR_TYPE_SKB:
  1562. return __bpf_skb_store_bytes(dst->data, dst->offset + offset, src, len,
  1563. flags);
  1564. case BPF_DYNPTR_TYPE_XDP:
  1565. if (flags)
  1566. return -EINVAL;
  1567. return __bpf_xdp_store_bytes(dst->data, dst->offset + offset, src, len);
  1568. default:
  1569. WARN_ONCE(true, "bpf_dynptr_write: unknown dynptr type %d\n", type);
  1570. return -EFAULT;
  1571. }
  1572. }
  1573. static const struct bpf_func_proto bpf_dynptr_write_proto = {
  1574. .func = bpf_dynptr_write,
  1575. .gpl_only = false,
  1576. .ret_type = RET_INTEGER,
  1577. .arg1_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY,
  1578. .arg2_type = ARG_ANYTHING,
  1579. .arg3_type = ARG_PTR_TO_MEM | MEM_RDONLY,
  1580. .arg4_type = ARG_CONST_SIZE_OR_ZERO,
  1581. .arg5_type = ARG_ANYTHING,
  1582. };
  1583. BPF_CALL_3(bpf_dynptr_data, const struct bpf_dynptr_kern *, ptr, u32, offset, u32, len)
  1584. {
  1585. enum bpf_dynptr_type type;
  1586. int err;
  1587. if (!ptr->data)
  1588. return 0;
  1589. err = bpf_dynptr_check_off_len(ptr, offset, len);
  1590. if (err)
  1591. return 0;
  1592. if (__bpf_dynptr_is_rdonly(ptr))
  1593. return 0;
  1594. type = bpf_dynptr_get_type(ptr);
  1595. switch (type) {
  1596. case BPF_DYNPTR_TYPE_LOCAL:
  1597. case BPF_DYNPTR_TYPE_RINGBUF:
  1598. return (unsigned long)(ptr->data + ptr->offset + offset);
  1599. case BPF_DYNPTR_TYPE_SKB:
  1600. case BPF_DYNPTR_TYPE_XDP:
  1601. /* skb and xdp dynptrs should use bpf_dynptr_slice / bpf_dynptr_slice_rdwr */
  1602. return 0;
  1603. default:
  1604. WARN_ONCE(true, "bpf_dynptr_data: unknown dynptr type %d\n", type);
  1605. return 0;
  1606. }
  1607. }
  1608. static const struct bpf_func_proto bpf_dynptr_data_proto = {
  1609. .func = bpf_dynptr_data,
  1610. .gpl_only = false,
  1611. .ret_type = RET_PTR_TO_DYNPTR_MEM_OR_NULL,
  1612. .arg1_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY,
  1613. .arg2_type = ARG_ANYTHING,
  1614. .arg3_type = ARG_CONST_ALLOC_SIZE_OR_ZERO,
  1615. };
  1616. const struct bpf_func_proto bpf_get_current_task_proto __weak;
  1617. const struct bpf_func_proto bpf_get_current_task_btf_proto __weak;
  1618. const struct bpf_func_proto bpf_probe_read_user_proto __weak;
  1619. const struct bpf_func_proto bpf_probe_read_user_str_proto __weak;
  1620. const struct bpf_func_proto bpf_probe_read_kernel_proto __weak;
  1621. const struct bpf_func_proto bpf_probe_read_kernel_str_proto __weak;
  1622. const struct bpf_func_proto bpf_task_pt_regs_proto __weak;
  1623. const struct bpf_func_proto *
  1624. bpf_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
  1625. {
  1626. switch (func_id) {
  1627. case BPF_FUNC_map_lookup_elem:
  1628. return &bpf_map_lookup_elem_proto;
  1629. case BPF_FUNC_map_update_elem:
  1630. return &bpf_map_update_elem_proto;
  1631. case BPF_FUNC_map_delete_elem:
  1632. return &bpf_map_delete_elem_proto;
  1633. case BPF_FUNC_map_push_elem:
  1634. return &bpf_map_push_elem_proto;
  1635. case BPF_FUNC_map_pop_elem:
  1636. return &bpf_map_pop_elem_proto;
  1637. case BPF_FUNC_map_peek_elem:
  1638. return &bpf_map_peek_elem_proto;
  1639. case BPF_FUNC_map_lookup_percpu_elem:
  1640. return &bpf_map_lookup_percpu_elem_proto;
  1641. case BPF_FUNC_get_prandom_u32:
  1642. return &bpf_get_prandom_u32_proto;
  1643. case BPF_FUNC_get_smp_processor_id:
  1644. return &bpf_get_raw_smp_processor_id_proto;
  1645. case BPF_FUNC_get_numa_node_id:
  1646. return &bpf_get_numa_node_id_proto;
  1647. case BPF_FUNC_tail_call:
  1648. return &bpf_tail_call_proto;
  1649. case BPF_FUNC_ktime_get_ns:
  1650. return &bpf_ktime_get_ns_proto;
  1651. case BPF_FUNC_ktime_get_boot_ns:
  1652. return &bpf_ktime_get_boot_ns_proto;
  1653. case BPF_FUNC_ktime_get_tai_ns:
  1654. return &bpf_ktime_get_tai_ns_proto;
  1655. case BPF_FUNC_ringbuf_output:
  1656. return &bpf_ringbuf_output_proto;
  1657. case BPF_FUNC_ringbuf_reserve:
  1658. return &bpf_ringbuf_reserve_proto;
  1659. case BPF_FUNC_ringbuf_submit:
  1660. return &bpf_ringbuf_submit_proto;
  1661. case BPF_FUNC_ringbuf_discard:
  1662. return &bpf_ringbuf_discard_proto;
  1663. case BPF_FUNC_ringbuf_query:
  1664. return &bpf_ringbuf_query_proto;
  1665. case BPF_FUNC_strncmp:
  1666. return &bpf_strncmp_proto;
  1667. case BPF_FUNC_strtol:
  1668. return &bpf_strtol_proto;
  1669. case BPF_FUNC_strtoul:
  1670. return &bpf_strtoul_proto;
  1671. case BPF_FUNC_get_current_pid_tgid:
  1672. return &bpf_get_current_pid_tgid_proto;
  1673. case BPF_FUNC_get_ns_current_pid_tgid:
  1674. return &bpf_get_ns_current_pid_tgid_proto;
  1675. default:
  1676. break;
  1677. }
  1678. if (!bpf_token_capable(prog->aux->token, CAP_BPF))
  1679. return NULL;
  1680. switch (func_id) {
  1681. case BPF_FUNC_spin_lock:
  1682. return &bpf_spin_lock_proto;
  1683. case BPF_FUNC_spin_unlock:
  1684. return &bpf_spin_unlock_proto;
  1685. case BPF_FUNC_jiffies64:
  1686. return &bpf_jiffies64_proto;
  1687. case BPF_FUNC_per_cpu_ptr:
  1688. return &bpf_per_cpu_ptr_proto;
  1689. case BPF_FUNC_this_cpu_ptr:
  1690. return &bpf_this_cpu_ptr_proto;
  1691. case BPF_FUNC_timer_init:
  1692. return &bpf_timer_init_proto;
  1693. case BPF_FUNC_timer_set_callback:
  1694. return &bpf_timer_set_callback_proto;
  1695. case BPF_FUNC_timer_start:
  1696. return &bpf_timer_start_proto;
  1697. case BPF_FUNC_timer_cancel:
  1698. return &bpf_timer_cancel_proto;
  1699. case BPF_FUNC_kptr_xchg:
  1700. return &bpf_kptr_xchg_proto;
  1701. case BPF_FUNC_for_each_map_elem:
  1702. return &bpf_for_each_map_elem_proto;
  1703. case BPF_FUNC_loop:
  1704. return &bpf_loop_proto;
  1705. case BPF_FUNC_user_ringbuf_drain:
  1706. return &bpf_user_ringbuf_drain_proto;
  1707. case BPF_FUNC_ringbuf_reserve_dynptr:
  1708. return &bpf_ringbuf_reserve_dynptr_proto;
  1709. case BPF_FUNC_ringbuf_submit_dynptr:
  1710. return &bpf_ringbuf_submit_dynptr_proto;
  1711. case BPF_FUNC_ringbuf_discard_dynptr:
  1712. return &bpf_ringbuf_discard_dynptr_proto;
  1713. case BPF_FUNC_dynptr_from_mem:
  1714. return &bpf_dynptr_from_mem_proto;
  1715. case BPF_FUNC_dynptr_read:
  1716. return &bpf_dynptr_read_proto;
  1717. case BPF_FUNC_dynptr_write:
  1718. return &bpf_dynptr_write_proto;
  1719. case BPF_FUNC_dynptr_data:
  1720. return &bpf_dynptr_data_proto;
  1721. #ifdef CONFIG_CGROUPS
  1722. case BPF_FUNC_cgrp_storage_get:
  1723. return &bpf_cgrp_storage_get_proto;
  1724. case BPF_FUNC_cgrp_storage_delete:
  1725. return &bpf_cgrp_storage_delete_proto;
  1726. case BPF_FUNC_get_current_cgroup_id:
  1727. return &bpf_get_current_cgroup_id_proto;
  1728. case BPF_FUNC_get_current_ancestor_cgroup_id:
  1729. return &bpf_get_current_ancestor_cgroup_id_proto;
  1730. #endif
  1731. default:
  1732. break;
  1733. }
  1734. if (!bpf_token_capable(prog->aux->token, CAP_PERFMON))
  1735. return NULL;
  1736. switch (func_id) {
  1737. case BPF_FUNC_trace_printk:
  1738. return bpf_get_trace_printk_proto();
  1739. case BPF_FUNC_get_current_task:
  1740. return &bpf_get_current_task_proto;
  1741. case BPF_FUNC_get_current_task_btf:
  1742. return &bpf_get_current_task_btf_proto;
  1743. case BPF_FUNC_probe_read_user:
  1744. return &bpf_probe_read_user_proto;
  1745. case BPF_FUNC_probe_read_kernel:
  1746. return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
  1747. NULL : &bpf_probe_read_kernel_proto;
  1748. case BPF_FUNC_probe_read_user_str:
  1749. return &bpf_probe_read_user_str_proto;
  1750. case BPF_FUNC_probe_read_kernel_str:
  1751. return security_locked_down(LOCKDOWN_BPF_READ_KERNEL) < 0 ?
  1752. NULL : &bpf_probe_read_kernel_str_proto;
  1753. case BPF_FUNC_snprintf_btf:
  1754. return &bpf_snprintf_btf_proto;
  1755. case BPF_FUNC_snprintf:
  1756. return &bpf_snprintf_proto;
  1757. case BPF_FUNC_task_pt_regs:
  1758. return &bpf_task_pt_regs_proto;
  1759. case BPF_FUNC_trace_vprintk:
  1760. return bpf_get_trace_vprintk_proto();
  1761. default:
  1762. return NULL;
  1763. }
  1764. }
  1765. EXPORT_SYMBOL_GPL(bpf_base_func_proto);
  1766. void bpf_list_head_free(const struct btf_field *field, void *list_head,
  1767. struct bpf_spin_lock *spin_lock)
  1768. {
  1769. struct list_head *head = list_head, *orig_head = list_head;
  1770. BUILD_BUG_ON(sizeof(struct list_head) > sizeof(struct bpf_list_head));
  1771. BUILD_BUG_ON(__alignof__(struct list_head) > __alignof__(struct bpf_list_head));
  1772. /* Do the actual list draining outside the lock to not hold the lock for
  1773. * too long, and also prevent deadlocks if tracing programs end up
  1774. * executing on entry/exit of functions called inside the critical
  1775. * section, and end up doing map ops that call bpf_list_head_free for
  1776. * the same map value again.
  1777. */
  1778. __bpf_spin_lock_irqsave(spin_lock);
  1779. if (!head->next || list_empty(head))
  1780. goto unlock;
  1781. head = head->next;
  1782. unlock:
  1783. INIT_LIST_HEAD(orig_head);
  1784. __bpf_spin_unlock_irqrestore(spin_lock);
  1785. while (head != orig_head) {
  1786. void *obj = head;
  1787. obj -= field->graph_root.node_offset;
  1788. head = head->next;
  1789. /* The contained type can also have resources, including a
  1790. * bpf_list_head which needs to be freed.
  1791. */
  1792. migrate_disable();
  1793. __bpf_obj_drop_impl(obj, field->graph_root.value_rec, false);
  1794. migrate_enable();
  1795. }
  1796. }
  1797. /* Like rbtree_postorder_for_each_entry_safe, but 'pos' and 'n' are
  1798. * 'rb_node *', so field name of rb_node within containing struct is not
  1799. * needed.
  1800. *
  1801. * Since bpf_rb_tree's node type has a corresponding struct btf_field with
  1802. * graph_root.node_offset, it's not necessary to know field name
  1803. * or type of node struct
  1804. */
  1805. #define bpf_rbtree_postorder_for_each_entry_safe(pos, n, root) \
  1806. for (pos = rb_first_postorder(root); \
  1807. pos && ({ n = rb_next_postorder(pos); 1; }); \
  1808. pos = n)
  1809. void bpf_rb_root_free(const struct btf_field *field, void *rb_root,
  1810. struct bpf_spin_lock *spin_lock)
  1811. {
  1812. struct rb_root_cached orig_root, *root = rb_root;
  1813. struct rb_node *pos, *n;
  1814. void *obj;
  1815. BUILD_BUG_ON(sizeof(struct rb_root_cached) > sizeof(struct bpf_rb_root));
  1816. BUILD_BUG_ON(__alignof__(struct rb_root_cached) > __alignof__(struct bpf_rb_root));
  1817. __bpf_spin_lock_irqsave(spin_lock);
  1818. orig_root = *root;
  1819. *root = RB_ROOT_CACHED;
  1820. __bpf_spin_unlock_irqrestore(spin_lock);
  1821. bpf_rbtree_postorder_for_each_entry_safe(pos, n, &orig_root.rb_root) {
  1822. obj = pos;
  1823. obj -= field->graph_root.node_offset;
  1824. migrate_disable();
  1825. __bpf_obj_drop_impl(obj, field->graph_root.value_rec, false);
  1826. migrate_enable();
  1827. }
  1828. }
  1829. __bpf_kfunc_start_defs();
  1830. __bpf_kfunc void *bpf_obj_new_impl(u64 local_type_id__k, void *meta__ign)
  1831. {
  1832. struct btf_struct_meta *meta = meta__ign;
  1833. u64 size = local_type_id__k;
  1834. void *p;
  1835. p = bpf_mem_alloc(&bpf_global_ma, size);
  1836. if (!p)
  1837. return NULL;
  1838. if (meta)
  1839. bpf_obj_init(meta->record, p);
  1840. return p;
  1841. }
  1842. __bpf_kfunc void *bpf_percpu_obj_new_impl(u64 local_type_id__k, void *meta__ign)
  1843. {
  1844. u64 size = local_type_id__k;
  1845. /* The verifier has ensured that meta__ign must be NULL */
  1846. return bpf_mem_alloc(&bpf_global_percpu_ma, size);
  1847. }
  1848. /* Must be called under migrate_disable(), as required by bpf_mem_free */
  1849. void __bpf_obj_drop_impl(void *p, const struct btf_record *rec, bool percpu)
  1850. {
  1851. struct bpf_mem_alloc *ma;
  1852. if (rec && rec->refcount_off >= 0 &&
  1853. !refcount_dec_and_test((refcount_t *)(p + rec->refcount_off))) {
  1854. /* Object is refcounted and refcount_dec didn't result in 0
  1855. * refcount. Return without freeing the object
  1856. */
  1857. return;
  1858. }
  1859. if (rec)
  1860. bpf_obj_free_fields(rec, p);
  1861. if (percpu)
  1862. ma = &bpf_global_percpu_ma;
  1863. else
  1864. ma = &bpf_global_ma;
  1865. bpf_mem_free_rcu(ma, p);
  1866. }
  1867. __bpf_kfunc void bpf_obj_drop_impl(void *p__alloc, void *meta__ign)
  1868. {
  1869. struct btf_struct_meta *meta = meta__ign;
  1870. void *p = p__alloc;
  1871. __bpf_obj_drop_impl(p, meta ? meta->record : NULL, false);
  1872. }
  1873. __bpf_kfunc void bpf_percpu_obj_drop_impl(void *p__alloc, void *meta__ign)
  1874. {
  1875. /* The verifier has ensured that meta__ign must be NULL */
  1876. bpf_mem_free_rcu(&bpf_global_percpu_ma, p__alloc);
  1877. }
  1878. __bpf_kfunc void *bpf_refcount_acquire_impl(void *p__refcounted_kptr, void *meta__ign)
  1879. {
  1880. struct btf_struct_meta *meta = meta__ign;
  1881. struct bpf_refcount *ref;
  1882. /* Could just cast directly to refcount_t *, but need some code using
  1883. * bpf_refcount type so that it is emitted in vmlinux BTF
  1884. */
  1885. ref = (struct bpf_refcount *)(p__refcounted_kptr + meta->record->refcount_off);
  1886. if (!refcount_inc_not_zero((refcount_t *)ref))
  1887. return NULL;
  1888. /* Verifier strips KF_RET_NULL if input is owned ref, see is_kfunc_ret_null
  1889. * in verifier.c
  1890. */
  1891. return (void *)p__refcounted_kptr;
  1892. }
  1893. static int __bpf_list_add(struct bpf_list_node_kern *node,
  1894. struct bpf_list_head *head,
  1895. bool tail, struct btf_record *rec, u64 off)
  1896. {
  1897. struct list_head *n = &node->list_head, *h = (void *)head;
  1898. /* If list_head was 0-initialized by map, bpf_obj_init_field wasn't
  1899. * called on its fields, so init here
  1900. */
  1901. if (unlikely(!h->next))
  1902. INIT_LIST_HEAD(h);
  1903. /* node->owner != NULL implies !list_empty(n), no need to separately
  1904. * check the latter
  1905. */
  1906. if (cmpxchg(&node->owner, NULL, BPF_PTR_POISON)) {
  1907. /* Only called from BPF prog, no need to migrate_disable */
  1908. __bpf_obj_drop_impl((void *)n - off, rec, false);
  1909. return -EINVAL;
  1910. }
  1911. tail ? list_add_tail(n, h) : list_add(n, h);
  1912. WRITE_ONCE(node->owner, head);
  1913. return 0;
  1914. }
  1915. __bpf_kfunc int bpf_list_push_front_impl(struct bpf_list_head *head,
  1916. struct bpf_list_node *node,
  1917. void *meta__ign, u64 off)
  1918. {
  1919. struct bpf_list_node_kern *n = (void *)node;
  1920. struct btf_struct_meta *meta = meta__ign;
  1921. return __bpf_list_add(n, head, false, meta ? meta->record : NULL, off);
  1922. }
  1923. __bpf_kfunc int bpf_list_push_back_impl(struct bpf_list_head *head,
  1924. struct bpf_list_node *node,
  1925. void *meta__ign, u64 off)
  1926. {
  1927. struct bpf_list_node_kern *n = (void *)node;
  1928. struct btf_struct_meta *meta = meta__ign;
  1929. return __bpf_list_add(n, head, true, meta ? meta->record : NULL, off);
  1930. }
  1931. static struct bpf_list_node *__bpf_list_del(struct bpf_list_head *head, bool tail)
  1932. {
  1933. struct list_head *n, *h = (void *)head;
  1934. struct bpf_list_node_kern *node;
  1935. /* If list_head was 0-initialized by map, bpf_obj_init_field wasn't
  1936. * called on its fields, so init here
  1937. */
  1938. if (unlikely(!h->next))
  1939. INIT_LIST_HEAD(h);
  1940. if (list_empty(h))
  1941. return NULL;
  1942. n = tail ? h->prev : h->next;
  1943. node = container_of(n, struct bpf_list_node_kern, list_head);
  1944. if (WARN_ON_ONCE(READ_ONCE(node->owner) != head))
  1945. return NULL;
  1946. list_del_init(n);
  1947. WRITE_ONCE(node->owner, NULL);
  1948. return (struct bpf_list_node *)n;
  1949. }
  1950. __bpf_kfunc struct bpf_list_node *bpf_list_pop_front(struct bpf_list_head *head)
  1951. {
  1952. return __bpf_list_del(head, false);
  1953. }
  1954. __bpf_kfunc struct bpf_list_node *bpf_list_pop_back(struct bpf_list_head *head)
  1955. {
  1956. return __bpf_list_del(head, true);
  1957. }
  1958. __bpf_kfunc struct bpf_rb_node *bpf_rbtree_remove(struct bpf_rb_root *root,
  1959. struct bpf_rb_node *node)
  1960. {
  1961. struct bpf_rb_node_kern *node_internal = (struct bpf_rb_node_kern *)node;
  1962. struct rb_root_cached *r = (struct rb_root_cached *)root;
  1963. struct rb_node *n = &node_internal->rb_node;
  1964. /* node_internal->owner != root implies either RB_EMPTY_NODE(n) or
  1965. * n is owned by some other tree. No need to check RB_EMPTY_NODE(n)
  1966. */
  1967. if (READ_ONCE(node_internal->owner) != root)
  1968. return NULL;
  1969. rb_erase_cached(n, r);
  1970. RB_CLEAR_NODE(n);
  1971. WRITE_ONCE(node_internal->owner, NULL);
  1972. return (struct bpf_rb_node *)n;
  1973. }
  1974. /* Need to copy rbtree_add_cached's logic here because our 'less' is a BPF
  1975. * program
  1976. */
  1977. static int __bpf_rbtree_add(struct bpf_rb_root *root,
  1978. struct bpf_rb_node_kern *node,
  1979. void *less, struct btf_record *rec, u64 off)
  1980. {
  1981. struct rb_node **link = &((struct rb_root_cached *)root)->rb_root.rb_node;
  1982. struct rb_node *parent = NULL, *n = &node->rb_node;
  1983. bpf_callback_t cb = (bpf_callback_t)less;
  1984. bool leftmost = true;
  1985. /* node->owner != NULL implies !RB_EMPTY_NODE(n), no need to separately
  1986. * check the latter
  1987. */
  1988. if (cmpxchg(&node->owner, NULL, BPF_PTR_POISON)) {
  1989. /* Only called from BPF prog, no need to migrate_disable */
  1990. __bpf_obj_drop_impl((void *)n - off, rec, false);
  1991. return -EINVAL;
  1992. }
  1993. while (*link) {
  1994. parent = *link;
  1995. if (cb((uintptr_t)node, (uintptr_t)parent, 0, 0, 0)) {
  1996. link = &parent->rb_left;
  1997. } else {
  1998. link = &parent->rb_right;
  1999. leftmost = false;
  2000. }
  2001. }
  2002. rb_link_node(n, parent, link);
  2003. rb_insert_color_cached(n, (struct rb_root_cached *)root, leftmost);
  2004. WRITE_ONCE(node->owner, root);
  2005. return 0;
  2006. }
  2007. __bpf_kfunc int bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
  2008. bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b),
  2009. void *meta__ign, u64 off)
  2010. {
  2011. struct btf_struct_meta *meta = meta__ign;
  2012. struct bpf_rb_node_kern *n = (void *)node;
  2013. return __bpf_rbtree_add(root, n, (void *)less, meta ? meta->record : NULL, off);
  2014. }
  2015. __bpf_kfunc struct bpf_rb_node *bpf_rbtree_first(struct bpf_rb_root *root)
  2016. {
  2017. struct rb_root_cached *r = (struct rb_root_cached *)root;
  2018. return (struct bpf_rb_node *)rb_first_cached(r);
  2019. }
  2020. /**
  2021. * bpf_task_acquire - Acquire a reference to a task. A task acquired by this
  2022. * kfunc which is not stored in a map as a kptr, must be released by calling
  2023. * bpf_task_release().
  2024. * @p: The task on which a reference is being acquired.
  2025. */
  2026. __bpf_kfunc struct task_struct *bpf_task_acquire(struct task_struct *p)
  2027. {
  2028. if (refcount_inc_not_zero(&p->rcu_users))
  2029. return p;
  2030. return NULL;
  2031. }
  2032. /**
  2033. * bpf_task_release - Release the reference acquired on a task.
  2034. * @p: The task on which a reference is being released.
  2035. */
  2036. __bpf_kfunc void bpf_task_release(struct task_struct *p)
  2037. {
  2038. put_task_struct_rcu_user(p);
  2039. }
  2040. __bpf_kfunc void bpf_task_release_dtor(void *p)
  2041. {
  2042. put_task_struct_rcu_user(p);
  2043. }
  2044. CFI_NOSEAL(bpf_task_release_dtor);
  2045. #ifdef CONFIG_CGROUPS
  2046. /**
  2047. * bpf_cgroup_acquire - Acquire a reference to a cgroup. A cgroup acquired by
  2048. * this kfunc which is not stored in a map as a kptr, must be released by
  2049. * calling bpf_cgroup_release().
  2050. * @cgrp: The cgroup on which a reference is being acquired.
  2051. */
  2052. __bpf_kfunc struct cgroup *bpf_cgroup_acquire(struct cgroup *cgrp)
  2053. {
  2054. return cgroup_tryget(cgrp) ? cgrp : NULL;
  2055. }
  2056. /**
  2057. * bpf_cgroup_release - Release the reference acquired on a cgroup.
  2058. * If this kfunc is invoked in an RCU read region, the cgroup is guaranteed to
  2059. * not be freed until the current grace period has ended, even if its refcount
  2060. * drops to 0.
  2061. * @cgrp: The cgroup on which a reference is being released.
  2062. */
  2063. __bpf_kfunc void bpf_cgroup_release(struct cgroup *cgrp)
  2064. {
  2065. cgroup_put(cgrp);
  2066. }
  2067. __bpf_kfunc void bpf_cgroup_release_dtor(void *cgrp)
  2068. {
  2069. cgroup_put(cgrp);
  2070. }
  2071. CFI_NOSEAL(bpf_cgroup_release_dtor);
  2072. /**
  2073. * bpf_cgroup_ancestor - Perform a lookup on an entry in a cgroup's ancestor
  2074. * array. A cgroup returned by this kfunc which is not subsequently stored in a
  2075. * map, must be released by calling bpf_cgroup_release().
  2076. * @cgrp: The cgroup for which we're performing a lookup.
  2077. * @level: The level of ancestor to look up.
  2078. */
  2079. __bpf_kfunc struct cgroup *bpf_cgroup_ancestor(struct cgroup *cgrp, int level)
  2080. {
  2081. struct cgroup *ancestor;
  2082. if (level > cgrp->level || level < 0)
  2083. return NULL;
  2084. /* cgrp's refcnt could be 0 here, but ancestors can still be accessed */
  2085. ancestor = cgrp->ancestors[level];
  2086. if (!cgroup_tryget(ancestor))
  2087. return NULL;
  2088. return ancestor;
  2089. }
  2090. /**
  2091. * bpf_cgroup_from_id - Find a cgroup from its ID. A cgroup returned by this
  2092. * kfunc which is not subsequently stored in a map, must be released by calling
  2093. * bpf_cgroup_release().
  2094. * @cgid: cgroup id.
  2095. */
  2096. __bpf_kfunc struct cgroup *bpf_cgroup_from_id(u64 cgid)
  2097. {
  2098. struct cgroup *cgrp;
  2099. cgrp = cgroup_get_from_id(cgid);
  2100. if (IS_ERR(cgrp))
  2101. return NULL;
  2102. return cgrp;
  2103. }
  2104. /**
  2105. * bpf_task_under_cgroup - wrap task_under_cgroup_hierarchy() as a kfunc, test
  2106. * task's membership of cgroup ancestry.
  2107. * @task: the task to be tested
  2108. * @ancestor: possible ancestor of @task's cgroup
  2109. *
  2110. * Tests whether @task's default cgroup hierarchy is a descendant of @ancestor.
  2111. * It follows all the same rules as cgroup_is_descendant, and only applies
  2112. * to the default hierarchy.
  2113. */
  2114. __bpf_kfunc long bpf_task_under_cgroup(struct task_struct *task,
  2115. struct cgroup *ancestor)
  2116. {
  2117. long ret;
  2118. rcu_read_lock();
  2119. ret = task_under_cgroup_hierarchy(task, ancestor);
  2120. rcu_read_unlock();
  2121. return ret;
  2122. }
  2123. BPF_CALL_2(bpf_current_task_under_cgroup, struct bpf_map *, map, u32, idx)
  2124. {
  2125. struct bpf_array *array = container_of(map, struct bpf_array, map);
  2126. struct cgroup *cgrp;
  2127. if (unlikely(idx >= array->map.max_entries))
  2128. return -E2BIG;
  2129. cgrp = READ_ONCE(array->ptrs[idx]);
  2130. if (unlikely(!cgrp))
  2131. return -EAGAIN;
  2132. return task_under_cgroup_hierarchy(current, cgrp);
  2133. }
  2134. const struct bpf_func_proto bpf_current_task_under_cgroup_proto = {
  2135. .func = bpf_current_task_under_cgroup,
  2136. .gpl_only = false,
  2137. .ret_type = RET_INTEGER,
  2138. .arg1_type = ARG_CONST_MAP_PTR,
  2139. .arg2_type = ARG_ANYTHING,
  2140. };
  2141. /**
  2142. * bpf_task_get_cgroup1 - Acquires the associated cgroup of a task within a
  2143. * specific cgroup1 hierarchy. The cgroup1 hierarchy is identified by its
  2144. * hierarchy ID.
  2145. * @task: The target task
  2146. * @hierarchy_id: The ID of a cgroup1 hierarchy
  2147. *
  2148. * On success, the cgroup is returen. On failure, NULL is returned.
  2149. */
  2150. __bpf_kfunc struct cgroup *
  2151. bpf_task_get_cgroup1(struct task_struct *task, int hierarchy_id)
  2152. {
  2153. struct cgroup *cgrp = task_get_cgroup1(task, hierarchy_id);
  2154. if (IS_ERR(cgrp))
  2155. return NULL;
  2156. return cgrp;
  2157. }
  2158. #endif /* CONFIG_CGROUPS */
  2159. /**
  2160. * bpf_task_from_pid - Find a struct task_struct from its pid by looking it up
  2161. * in the root pid namespace idr. If a task is returned, it must either be
  2162. * stored in a map, or released with bpf_task_release().
  2163. * @pid: The pid of the task being looked up.
  2164. */
  2165. __bpf_kfunc struct task_struct *bpf_task_from_pid(s32 pid)
  2166. {
  2167. struct task_struct *p;
  2168. rcu_read_lock();
  2169. p = find_task_by_pid_ns(pid, &init_pid_ns);
  2170. if (p)
  2171. p = bpf_task_acquire(p);
  2172. rcu_read_unlock();
  2173. return p;
  2174. }
  2175. /**
  2176. * bpf_dynptr_slice() - Obtain a read-only pointer to the dynptr data.
  2177. * @p: The dynptr whose data slice to retrieve
  2178. * @offset: Offset into the dynptr
  2179. * @buffer__opt: User-provided buffer to copy contents into. May be NULL
  2180. * @buffer__szk: Size (in bytes) of the buffer if present. This is the
  2181. * length of the requested slice. This must be a constant.
  2182. *
  2183. * For non-skb and non-xdp type dynptrs, there is no difference between
  2184. * bpf_dynptr_slice and bpf_dynptr_data.
  2185. *
  2186. * If buffer__opt is NULL, the call will fail if buffer_opt was needed.
  2187. *
  2188. * If the intention is to write to the data slice, please use
  2189. * bpf_dynptr_slice_rdwr.
  2190. *
  2191. * The user must check that the returned pointer is not null before using it.
  2192. *
  2193. * Please note that in the case of skb and xdp dynptrs, bpf_dynptr_slice
  2194. * does not change the underlying packet data pointers, so a call to
  2195. * bpf_dynptr_slice will not invalidate any ctx->data/data_end pointers in
  2196. * the bpf program.
  2197. *
  2198. * Return: NULL if the call failed (eg invalid dynptr), pointer to a read-only
  2199. * data slice (can be either direct pointer to the data or a pointer to the user
  2200. * provided buffer, with its contents containing the data, if unable to obtain
  2201. * direct pointer)
  2202. */
  2203. __bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr *p, u32 offset,
  2204. void *buffer__opt, u32 buffer__szk)
  2205. {
  2206. const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
  2207. enum bpf_dynptr_type type;
  2208. u32 len = buffer__szk;
  2209. int err;
  2210. if (!ptr->data)
  2211. return NULL;
  2212. err = bpf_dynptr_check_off_len(ptr, offset, len);
  2213. if (err)
  2214. return NULL;
  2215. type = bpf_dynptr_get_type(ptr);
  2216. switch (type) {
  2217. case BPF_DYNPTR_TYPE_LOCAL:
  2218. case BPF_DYNPTR_TYPE_RINGBUF:
  2219. return ptr->data + ptr->offset + offset;
  2220. case BPF_DYNPTR_TYPE_SKB:
  2221. if (buffer__opt)
  2222. return skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer__opt);
  2223. else
  2224. return skb_pointer_if_linear(ptr->data, ptr->offset + offset, len);
  2225. case BPF_DYNPTR_TYPE_XDP:
  2226. {
  2227. void *xdp_ptr = bpf_xdp_pointer(ptr->data, ptr->offset + offset, len);
  2228. if (!IS_ERR_OR_NULL(xdp_ptr))
  2229. return xdp_ptr;
  2230. if (!buffer__opt)
  2231. return NULL;
  2232. bpf_xdp_copy_buf(ptr->data, ptr->offset + offset, buffer__opt, len, false);
  2233. return buffer__opt;
  2234. }
  2235. default:
  2236. WARN_ONCE(true, "unknown dynptr type %d\n", type);
  2237. return NULL;
  2238. }
  2239. }
  2240. /**
  2241. * bpf_dynptr_slice_rdwr() - Obtain a writable pointer to the dynptr data.
  2242. * @p: The dynptr whose data slice to retrieve
  2243. * @offset: Offset into the dynptr
  2244. * @buffer__opt: User-provided buffer to copy contents into. May be NULL
  2245. * @buffer__szk: Size (in bytes) of the buffer if present. This is the
  2246. * length of the requested slice. This must be a constant.
  2247. *
  2248. * For non-skb and non-xdp type dynptrs, there is no difference between
  2249. * bpf_dynptr_slice and bpf_dynptr_data.
  2250. *
  2251. * If buffer__opt is NULL, the call will fail if buffer_opt was needed.
  2252. *
  2253. * The returned pointer is writable and may point to either directly the dynptr
  2254. * data at the requested offset or to the buffer if unable to obtain a direct
  2255. * data pointer to (example: the requested slice is to the paged area of an skb
  2256. * packet). In the case where the returned pointer is to the buffer, the user
  2257. * is responsible for persisting writes through calling bpf_dynptr_write(). This
  2258. * usually looks something like this pattern:
  2259. *
  2260. * struct eth_hdr *eth = bpf_dynptr_slice_rdwr(&dynptr, 0, buffer, sizeof(buffer));
  2261. * if (!eth)
  2262. * return TC_ACT_SHOT;
  2263. *
  2264. * // mutate eth header //
  2265. *
  2266. * if (eth == buffer)
  2267. * bpf_dynptr_write(&ptr, 0, buffer, sizeof(buffer), 0);
  2268. *
  2269. * Please note that, as in the example above, the user must check that the
  2270. * returned pointer is not null before using it.
  2271. *
  2272. * Please also note that in the case of skb and xdp dynptrs, bpf_dynptr_slice_rdwr
  2273. * does not change the underlying packet data pointers, so a call to
  2274. * bpf_dynptr_slice_rdwr will not invalidate any ctx->data/data_end pointers in
  2275. * the bpf program.
  2276. *
  2277. * Return: NULL if the call failed (eg invalid dynptr), pointer to a
  2278. * data slice (can be either direct pointer to the data or a pointer to the user
  2279. * provided buffer, with its contents containing the data, if unable to obtain
  2280. * direct pointer)
  2281. */
  2282. __bpf_kfunc void *bpf_dynptr_slice_rdwr(const struct bpf_dynptr *p, u32 offset,
  2283. void *buffer__opt, u32 buffer__szk)
  2284. {
  2285. const struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
  2286. if (!ptr->data || __bpf_dynptr_is_rdonly(ptr))
  2287. return NULL;
  2288. /* bpf_dynptr_slice_rdwr is the same logic as bpf_dynptr_slice.
  2289. *
  2290. * For skb-type dynptrs, it is safe to write into the returned pointer
  2291. * if the bpf program allows skb data writes. There are two possibilities
  2292. * that may occur when calling bpf_dynptr_slice_rdwr:
  2293. *
  2294. * 1) The requested slice is in the head of the skb. In this case, the
  2295. * returned pointer is directly to skb data, and if the skb is cloned, the
  2296. * verifier will have uncloned it (see bpf_unclone_prologue()) already.
  2297. * The pointer can be directly written into.
  2298. *
  2299. * 2) Some portion of the requested slice is in the paged buffer area.
  2300. * In this case, the requested data will be copied out into the buffer
  2301. * and the returned pointer will be a pointer to the buffer. The skb
  2302. * will not be pulled. To persist the write, the user will need to call
  2303. * bpf_dynptr_write(), which will pull the skb and commit the write.
  2304. *
  2305. * Similarly for xdp programs, if the requested slice is not across xdp
  2306. * fragments, then a direct pointer will be returned, otherwise the data
  2307. * will be copied out into the buffer and the user will need to call
  2308. * bpf_dynptr_write() to commit changes.
  2309. */
  2310. return bpf_dynptr_slice(p, offset, buffer__opt, buffer__szk);
  2311. }
  2312. __bpf_kfunc int bpf_dynptr_adjust(const struct bpf_dynptr *p, u32 start, u32 end)
  2313. {
  2314. struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
  2315. u32 size;
  2316. if (!ptr->data || start > end)
  2317. return -EINVAL;
  2318. size = __bpf_dynptr_size(ptr);
  2319. if (start > size || end > size)
  2320. return -ERANGE;
  2321. ptr->offset += start;
  2322. bpf_dynptr_set_size(ptr, end - start);
  2323. return 0;
  2324. }
  2325. __bpf_kfunc bool bpf_dynptr_is_null(const struct bpf_dynptr *p)
  2326. {
  2327. struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
  2328. return !ptr->data;
  2329. }
  2330. __bpf_kfunc bool bpf_dynptr_is_rdonly(const struct bpf_dynptr *p)
  2331. {
  2332. struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
  2333. if (!ptr->data)
  2334. return false;
  2335. return __bpf_dynptr_is_rdonly(ptr);
  2336. }
  2337. __bpf_kfunc __u32 bpf_dynptr_size(const struct bpf_dynptr *p)
  2338. {
  2339. struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
  2340. if (!ptr->data)
  2341. return -EINVAL;
  2342. return __bpf_dynptr_size(ptr);
  2343. }
  2344. __bpf_kfunc int bpf_dynptr_clone(const struct bpf_dynptr *p,
  2345. struct bpf_dynptr *clone__uninit)
  2346. {
  2347. struct bpf_dynptr_kern *clone = (struct bpf_dynptr_kern *)clone__uninit;
  2348. struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)p;
  2349. if (!ptr->data) {
  2350. bpf_dynptr_set_null(clone);
  2351. return -EINVAL;
  2352. }
  2353. *clone = *ptr;
  2354. return 0;
  2355. }
  2356. __bpf_kfunc void *bpf_cast_to_kern_ctx(void *obj)
  2357. {
  2358. return obj;
  2359. }
  2360. __bpf_kfunc void *bpf_rdonly_cast(const void *obj__ign, u32 btf_id__k)
  2361. {
  2362. return (void *)obj__ign;
  2363. }
  2364. __bpf_kfunc void bpf_rcu_read_lock(void)
  2365. {
  2366. rcu_read_lock();
  2367. }
  2368. __bpf_kfunc void bpf_rcu_read_unlock(void)
  2369. {
  2370. rcu_read_unlock();
  2371. }
  2372. struct bpf_throw_ctx {
  2373. struct bpf_prog_aux *aux;
  2374. u64 sp;
  2375. u64 bp;
  2376. int cnt;
  2377. };
  2378. static bool bpf_stack_walker(void *cookie, u64 ip, u64 sp, u64 bp)
  2379. {
  2380. struct bpf_throw_ctx *ctx = cookie;
  2381. struct bpf_prog *prog;
  2382. /*
  2383. * The RCU read lock is held to safely traverse the latch tree, but we
  2384. * don't need its protection when accessing the prog, since it has an
  2385. * active stack frame on the current stack trace, and won't disappear.
  2386. */
  2387. rcu_read_lock();
  2388. prog = bpf_prog_ksym_find(ip);
  2389. rcu_read_unlock();
  2390. if (!prog)
  2391. return !ctx->cnt;
  2392. ctx->cnt++;
  2393. if (bpf_is_subprog(prog))
  2394. return true;
  2395. ctx->aux = prog->aux;
  2396. ctx->sp = sp;
  2397. ctx->bp = bp;
  2398. return false;
  2399. }
  2400. __bpf_kfunc void bpf_throw(u64 cookie)
  2401. {
  2402. struct bpf_throw_ctx ctx = {};
  2403. arch_bpf_stack_walk(bpf_stack_walker, &ctx);
  2404. WARN_ON_ONCE(!ctx.aux);
  2405. if (ctx.aux)
  2406. WARN_ON_ONCE(!ctx.aux->exception_boundary);
  2407. WARN_ON_ONCE(!ctx.bp);
  2408. WARN_ON_ONCE(!ctx.cnt);
  2409. /* Prevent KASAN false positives for CONFIG_KASAN_STACK by unpoisoning
  2410. * deeper stack depths than ctx.sp as we do not return from bpf_throw,
  2411. * which skips compiler generated instrumentation to do the same.
  2412. */
  2413. kasan_unpoison_task_stack_below((void *)(long)ctx.sp);
  2414. ctx.aux->bpf_exception_cb(cookie, ctx.sp, ctx.bp, 0, 0);
  2415. WARN(1, "A call to BPF exception callback should never return\n");
  2416. }
  2417. __bpf_kfunc int bpf_wq_init(struct bpf_wq *wq, void *p__map, unsigned int flags)
  2418. {
  2419. struct bpf_async_kern *async = (struct bpf_async_kern *)wq;
  2420. struct bpf_map *map = p__map;
  2421. BUILD_BUG_ON(sizeof(struct bpf_async_kern) > sizeof(struct bpf_wq));
  2422. BUILD_BUG_ON(__alignof__(struct bpf_async_kern) != __alignof__(struct bpf_wq));
  2423. if (flags)
  2424. return -EINVAL;
  2425. return __bpf_async_init(async, map, flags, BPF_ASYNC_TYPE_WQ);
  2426. }
  2427. __bpf_kfunc int bpf_wq_start(struct bpf_wq *wq, unsigned int flags)
  2428. {
  2429. struct bpf_async_kern *async = (struct bpf_async_kern *)wq;
  2430. struct bpf_work *w;
  2431. if (in_nmi())
  2432. return -EOPNOTSUPP;
  2433. if (flags)
  2434. return -EINVAL;
  2435. w = READ_ONCE(async->work);
  2436. if (!w || !READ_ONCE(w->cb.prog))
  2437. return -EINVAL;
  2438. schedule_work(&w->work);
  2439. return 0;
  2440. }
  2441. __bpf_kfunc int bpf_wq_set_callback_impl(struct bpf_wq *wq,
  2442. int (callback_fn)(void *map, int *key, void *value),
  2443. unsigned int flags,
  2444. void *aux__ign)
  2445. {
  2446. struct bpf_prog_aux *aux = (struct bpf_prog_aux *)aux__ign;
  2447. struct bpf_async_kern *async = (struct bpf_async_kern *)wq;
  2448. if (flags)
  2449. return -EINVAL;
  2450. return __bpf_async_set_callback(async, callback_fn, aux, flags, BPF_ASYNC_TYPE_WQ);
  2451. }
  2452. __bpf_kfunc void bpf_preempt_disable(void)
  2453. {
  2454. preempt_disable();
  2455. }
  2456. __bpf_kfunc void bpf_preempt_enable(void)
  2457. {
  2458. preempt_enable();
  2459. }
  2460. struct bpf_iter_bits {
  2461. __u64 __opaque[2];
  2462. } __aligned(8);
  2463. #define BITS_ITER_NR_WORDS_MAX 511
  2464. struct bpf_iter_bits_kern {
  2465. union {
  2466. __u64 *bits;
  2467. __u64 bits_copy;
  2468. };
  2469. int nr_bits;
  2470. int bit;
  2471. } __aligned(8);
  2472. /* On 64-bit hosts, unsigned long and u64 have the same size, so passing
  2473. * a u64 pointer and an unsigned long pointer to find_next_bit() will
  2474. * return the same result, as both point to the same 8-byte area.
  2475. *
  2476. * For 32-bit little-endian hosts, using a u64 pointer or unsigned long
  2477. * pointer also makes no difference. This is because the first iterated
  2478. * unsigned long is composed of bits 0-31 of the u64 and the second unsigned
  2479. * long is composed of bits 32-63 of the u64.
  2480. *
  2481. * However, for 32-bit big-endian hosts, this is not the case. The first
  2482. * iterated unsigned long will be bits 32-63 of the u64, so swap these two
  2483. * ulong values within the u64.
  2484. */
  2485. static void swap_ulong_in_u64(u64 *bits, unsigned int nr)
  2486. {
  2487. #if (BITS_PER_LONG == 32) && defined(__BIG_ENDIAN)
  2488. unsigned int i;
  2489. for (i = 0; i < nr; i++)
  2490. bits[i] = (bits[i] >> 32) | ((u64)(u32)bits[i] << 32);
  2491. #endif
  2492. }
  2493. /**
  2494. * bpf_iter_bits_new() - Initialize a new bits iterator for a given memory area
  2495. * @it: The new bpf_iter_bits to be created
  2496. * @unsafe_ptr__ign: A pointer pointing to a memory area to be iterated over
  2497. * @nr_words: The size of the specified memory area, measured in 8-byte units.
  2498. * The maximum value of @nr_words is @BITS_ITER_NR_WORDS_MAX. This limit may be
  2499. * further reduced by the BPF memory allocator implementation.
  2500. *
  2501. * This function initializes a new bpf_iter_bits structure for iterating over
  2502. * a memory area which is specified by the @unsafe_ptr__ign and @nr_words. It
  2503. * copies the data of the memory area to the newly created bpf_iter_bits @it for
  2504. * subsequent iteration operations.
  2505. *
  2506. * On success, 0 is returned. On failure, ERR is returned.
  2507. */
  2508. __bpf_kfunc int
  2509. bpf_iter_bits_new(struct bpf_iter_bits *it, const u64 *unsafe_ptr__ign, u32 nr_words)
  2510. {
  2511. struct bpf_iter_bits_kern *kit = (void *)it;
  2512. u32 nr_bytes = nr_words * sizeof(u64);
  2513. u32 nr_bits = BYTES_TO_BITS(nr_bytes);
  2514. int err;
  2515. BUILD_BUG_ON(sizeof(struct bpf_iter_bits_kern) != sizeof(struct bpf_iter_bits));
  2516. BUILD_BUG_ON(__alignof__(struct bpf_iter_bits_kern) !=
  2517. __alignof__(struct bpf_iter_bits));
  2518. kit->nr_bits = 0;
  2519. kit->bits_copy = 0;
  2520. kit->bit = -1;
  2521. if (!unsafe_ptr__ign || !nr_words)
  2522. return -EINVAL;
  2523. if (nr_words > BITS_ITER_NR_WORDS_MAX)
  2524. return -E2BIG;
  2525. /* Optimization for u64 mask */
  2526. if (nr_bits == 64) {
  2527. err = bpf_probe_read_kernel_common(&kit->bits_copy, nr_bytes, unsafe_ptr__ign);
  2528. if (err)
  2529. return -EFAULT;
  2530. swap_ulong_in_u64(&kit->bits_copy, nr_words);
  2531. kit->nr_bits = nr_bits;
  2532. return 0;
  2533. }
  2534. if (bpf_mem_alloc_check_size(false, nr_bytes))
  2535. return -E2BIG;
  2536. /* Fallback to memalloc */
  2537. kit->bits = bpf_mem_alloc(&bpf_global_ma, nr_bytes);
  2538. if (!kit->bits)
  2539. return -ENOMEM;
  2540. err = bpf_probe_read_kernel_common(kit->bits, nr_bytes, unsafe_ptr__ign);
  2541. if (err) {
  2542. bpf_mem_free(&bpf_global_ma, kit->bits);
  2543. return err;
  2544. }
  2545. swap_ulong_in_u64(kit->bits, nr_words);
  2546. kit->nr_bits = nr_bits;
  2547. return 0;
  2548. }
  2549. /**
  2550. * bpf_iter_bits_next() - Get the next bit in a bpf_iter_bits
  2551. * @it: The bpf_iter_bits to be checked
  2552. *
  2553. * This function returns a pointer to a number representing the value of the
  2554. * next bit in the bits.
  2555. *
  2556. * If there are no further bits available, it returns NULL.
  2557. */
  2558. __bpf_kfunc int *bpf_iter_bits_next(struct bpf_iter_bits *it)
  2559. {
  2560. struct bpf_iter_bits_kern *kit = (void *)it;
  2561. int bit = kit->bit, nr_bits = kit->nr_bits;
  2562. const void *bits;
  2563. if (!nr_bits || bit >= nr_bits)
  2564. return NULL;
  2565. bits = nr_bits == 64 ? &kit->bits_copy : kit->bits;
  2566. bit = find_next_bit(bits, nr_bits, bit + 1);
  2567. if (bit >= nr_bits) {
  2568. kit->bit = bit;
  2569. return NULL;
  2570. }
  2571. kit->bit = bit;
  2572. return &kit->bit;
  2573. }
  2574. /**
  2575. * bpf_iter_bits_destroy() - Destroy a bpf_iter_bits
  2576. * @it: The bpf_iter_bits to be destroyed
  2577. *
  2578. * Destroy the resource associated with the bpf_iter_bits.
  2579. */
  2580. __bpf_kfunc void bpf_iter_bits_destroy(struct bpf_iter_bits *it)
  2581. {
  2582. struct bpf_iter_bits_kern *kit = (void *)it;
  2583. if (kit->nr_bits <= 64)
  2584. return;
  2585. bpf_mem_free(&bpf_global_ma, kit->bits);
  2586. }
  2587. /**
  2588. * bpf_copy_from_user_str() - Copy a string from an unsafe user address
  2589. * @dst: Destination address, in kernel space. This buffer must be
  2590. * at least @dst__sz bytes long.
  2591. * @dst__sz: Maximum number of bytes to copy, includes the trailing NUL.
  2592. * @unsafe_ptr__ign: Source address, in user space.
  2593. * @flags: The only supported flag is BPF_F_PAD_ZEROS
  2594. *
  2595. * Copies a NUL-terminated string from userspace to BPF space. If user string is
  2596. * too long this will still ensure zero termination in the dst buffer unless
  2597. * buffer size is 0.
  2598. *
  2599. * If BPF_F_PAD_ZEROS flag is set, memset the tail of @dst to 0 on success and
  2600. * memset all of @dst on failure.
  2601. */
  2602. __bpf_kfunc int bpf_copy_from_user_str(void *dst, u32 dst__sz, const void __user *unsafe_ptr__ign, u64 flags)
  2603. {
  2604. int ret;
  2605. if (unlikely(flags & ~BPF_F_PAD_ZEROS))
  2606. return -EINVAL;
  2607. if (unlikely(!dst__sz))
  2608. return 0;
  2609. ret = strncpy_from_user(dst, unsafe_ptr__ign, dst__sz - 1);
  2610. if (ret < 0) {
  2611. if (flags & BPF_F_PAD_ZEROS)
  2612. memset((char *)dst, 0, dst__sz);
  2613. return ret;
  2614. }
  2615. if (flags & BPF_F_PAD_ZEROS)
  2616. memset((char *)dst + ret, 0, dst__sz - ret);
  2617. else
  2618. ((char *)dst)[ret] = '\0';
  2619. return ret + 1;
  2620. }
  2621. __bpf_kfunc_end_defs();
  2622. BTF_KFUNCS_START(generic_btf_ids)
  2623. #ifdef CONFIG_CRASH_DUMP
  2624. BTF_ID_FLAGS(func, crash_kexec, KF_DESTRUCTIVE)
  2625. #endif
  2626. BTF_ID_FLAGS(func, bpf_obj_new_impl, KF_ACQUIRE | KF_RET_NULL)
  2627. BTF_ID_FLAGS(func, bpf_percpu_obj_new_impl, KF_ACQUIRE | KF_RET_NULL)
  2628. BTF_ID_FLAGS(func, bpf_obj_drop_impl, KF_RELEASE)
  2629. BTF_ID_FLAGS(func, bpf_percpu_obj_drop_impl, KF_RELEASE)
  2630. BTF_ID_FLAGS(func, bpf_refcount_acquire_impl, KF_ACQUIRE | KF_RET_NULL | KF_RCU)
  2631. BTF_ID_FLAGS(func, bpf_list_push_front_impl)
  2632. BTF_ID_FLAGS(func, bpf_list_push_back_impl)
  2633. BTF_ID_FLAGS(func, bpf_list_pop_front, KF_ACQUIRE | KF_RET_NULL)
  2634. BTF_ID_FLAGS(func, bpf_list_pop_back, KF_ACQUIRE | KF_RET_NULL)
  2635. BTF_ID_FLAGS(func, bpf_task_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
  2636. BTF_ID_FLAGS(func, bpf_task_release, KF_RELEASE)
  2637. BTF_ID_FLAGS(func, bpf_rbtree_remove, KF_ACQUIRE | KF_RET_NULL)
  2638. BTF_ID_FLAGS(func, bpf_rbtree_add_impl)
  2639. BTF_ID_FLAGS(func, bpf_rbtree_first, KF_RET_NULL)
  2640. #ifdef CONFIG_CGROUPS
  2641. BTF_ID_FLAGS(func, bpf_cgroup_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
  2642. BTF_ID_FLAGS(func, bpf_cgroup_release, KF_RELEASE)
  2643. BTF_ID_FLAGS(func, bpf_cgroup_ancestor, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
  2644. BTF_ID_FLAGS(func, bpf_cgroup_from_id, KF_ACQUIRE | KF_RET_NULL)
  2645. BTF_ID_FLAGS(func, bpf_task_under_cgroup, KF_RCU)
  2646. BTF_ID_FLAGS(func, bpf_task_get_cgroup1, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
  2647. #endif
  2648. BTF_ID_FLAGS(func, bpf_task_from_pid, KF_ACQUIRE | KF_RET_NULL)
  2649. BTF_ID_FLAGS(func, bpf_throw)
  2650. BTF_KFUNCS_END(generic_btf_ids)
  2651. static const struct btf_kfunc_id_set generic_kfunc_set = {
  2652. .owner = THIS_MODULE,
  2653. .set = &generic_btf_ids,
  2654. };
  2655. BTF_ID_LIST(generic_dtor_ids)
  2656. BTF_ID(struct, task_struct)
  2657. BTF_ID(func, bpf_task_release_dtor)
  2658. #ifdef CONFIG_CGROUPS
  2659. BTF_ID(struct, cgroup)
  2660. BTF_ID(func, bpf_cgroup_release_dtor)
  2661. #endif
  2662. BTF_KFUNCS_START(common_btf_ids)
  2663. BTF_ID_FLAGS(func, bpf_cast_to_kern_ctx)
  2664. BTF_ID_FLAGS(func, bpf_rdonly_cast)
  2665. BTF_ID_FLAGS(func, bpf_rcu_read_lock)
  2666. BTF_ID_FLAGS(func, bpf_rcu_read_unlock)
  2667. BTF_ID_FLAGS(func, bpf_dynptr_slice, KF_RET_NULL)
  2668. BTF_ID_FLAGS(func, bpf_dynptr_slice_rdwr, KF_RET_NULL)
  2669. BTF_ID_FLAGS(func, bpf_iter_num_new, KF_ITER_NEW)
  2670. BTF_ID_FLAGS(func, bpf_iter_num_next, KF_ITER_NEXT | KF_RET_NULL)
  2671. BTF_ID_FLAGS(func, bpf_iter_num_destroy, KF_ITER_DESTROY)
  2672. BTF_ID_FLAGS(func, bpf_iter_task_vma_new, KF_ITER_NEW | KF_RCU)
  2673. BTF_ID_FLAGS(func, bpf_iter_task_vma_next, KF_ITER_NEXT | KF_RET_NULL)
  2674. BTF_ID_FLAGS(func, bpf_iter_task_vma_destroy, KF_ITER_DESTROY)
  2675. #ifdef CONFIG_CGROUPS
  2676. BTF_ID_FLAGS(func, bpf_iter_css_task_new, KF_ITER_NEW | KF_TRUSTED_ARGS)
  2677. BTF_ID_FLAGS(func, bpf_iter_css_task_next, KF_ITER_NEXT | KF_RET_NULL)
  2678. BTF_ID_FLAGS(func, bpf_iter_css_task_destroy, KF_ITER_DESTROY)
  2679. BTF_ID_FLAGS(func, bpf_iter_css_new, KF_ITER_NEW | KF_TRUSTED_ARGS | KF_RCU_PROTECTED)
  2680. BTF_ID_FLAGS(func, bpf_iter_css_next, KF_ITER_NEXT | KF_RET_NULL)
  2681. BTF_ID_FLAGS(func, bpf_iter_css_destroy, KF_ITER_DESTROY)
  2682. #endif
  2683. BTF_ID_FLAGS(func, bpf_iter_task_new, KF_ITER_NEW | KF_TRUSTED_ARGS | KF_RCU_PROTECTED)
  2684. BTF_ID_FLAGS(func, bpf_iter_task_next, KF_ITER_NEXT | KF_RET_NULL)
  2685. BTF_ID_FLAGS(func, bpf_iter_task_destroy, KF_ITER_DESTROY)
  2686. BTF_ID_FLAGS(func, bpf_dynptr_adjust)
  2687. BTF_ID_FLAGS(func, bpf_dynptr_is_null)
  2688. BTF_ID_FLAGS(func, bpf_dynptr_is_rdonly)
  2689. BTF_ID_FLAGS(func, bpf_dynptr_size)
  2690. BTF_ID_FLAGS(func, bpf_dynptr_clone)
  2691. BTF_ID_FLAGS(func, bpf_modify_return_test_tp)
  2692. BTF_ID_FLAGS(func, bpf_wq_init)
  2693. BTF_ID_FLAGS(func, bpf_wq_set_callback_impl)
  2694. BTF_ID_FLAGS(func, bpf_wq_start)
  2695. BTF_ID_FLAGS(func, bpf_preempt_disable)
  2696. BTF_ID_FLAGS(func, bpf_preempt_enable)
  2697. BTF_ID_FLAGS(func, bpf_iter_bits_new, KF_ITER_NEW)
  2698. BTF_ID_FLAGS(func, bpf_iter_bits_next, KF_ITER_NEXT | KF_RET_NULL)
  2699. BTF_ID_FLAGS(func, bpf_iter_bits_destroy, KF_ITER_DESTROY)
  2700. BTF_ID_FLAGS(func, bpf_copy_from_user_str, KF_SLEEPABLE)
  2701. BTF_KFUNCS_END(common_btf_ids)
  2702. static const struct btf_kfunc_id_set common_kfunc_set = {
  2703. .owner = THIS_MODULE,
  2704. .set = &common_btf_ids,
  2705. };
  2706. static int __init kfunc_init(void)
  2707. {
  2708. int ret;
  2709. const struct btf_id_dtor_kfunc generic_dtors[] = {
  2710. {
  2711. .btf_id = generic_dtor_ids[0],
  2712. .kfunc_btf_id = generic_dtor_ids[1]
  2713. },
  2714. #ifdef CONFIG_CGROUPS
  2715. {
  2716. .btf_id = generic_dtor_ids[2],
  2717. .kfunc_btf_id = generic_dtor_ids[3]
  2718. },
  2719. #endif
  2720. };
  2721. ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &generic_kfunc_set);
  2722. ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &generic_kfunc_set);
  2723. ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_XDP, &generic_kfunc_set);
  2724. ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, &generic_kfunc_set);
  2725. ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, &generic_kfunc_set);
  2726. ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_CGROUP_SKB, &generic_kfunc_set);
  2727. ret = ret ?: register_btf_id_dtor_kfuncs(generic_dtors,
  2728. ARRAY_SIZE(generic_dtors),
  2729. THIS_MODULE);
  2730. return ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_UNSPEC, &common_kfunc_set);
  2731. }
  2732. late_initcall(kfunc_init);
  2733. /* Get a pointer to dynptr data up to len bytes for read only access. If
  2734. * the dynptr doesn't have continuous data up to len bytes, return NULL.
  2735. */
  2736. const void *__bpf_dynptr_data(const struct bpf_dynptr_kern *ptr, u32 len)
  2737. {
  2738. const struct bpf_dynptr *p = (struct bpf_dynptr *)ptr;
  2739. return bpf_dynptr_slice(p, 0, NULL, len);
  2740. }
  2741. /* Get a pointer to dynptr data up to len bytes for read write access. If
  2742. * the dynptr doesn't have continuous data up to len bytes, or the dynptr
  2743. * is read only, return NULL.
  2744. */
  2745. void *__bpf_dynptr_data_rw(const struct bpf_dynptr_kern *ptr, u32 len)
  2746. {
  2747. if (__bpf_dynptr_is_rdonly(ptr))
  2748. return NULL;
  2749. return (void *)__bpf_dynptr_data(ptr, len);
  2750. }