tun.c 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664
  1. /*
  2. * TUN - Universal TUN/TAP device driver.
  3. * Copyright (C) 1999-2002 Maxim Krasnyansky <maxk@qualcomm.com>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * $Id: tun.c,v 1.15 2002/03/01 02:44:24 maxk Exp $
  16. */
  17. /*
  18. * Changes:
  19. *
  20. * Mike Kershaw <dragorn@kismetwireless.net> 2005/08/14
  21. * Add TUNSETLINK ioctl to set the link encapsulation
  22. *
  23. * Mark Smith <markzzzsmith@yahoo.com.au>
  24. * Use eth_random_addr() for tap MAC address.
  25. *
  26. * Harald Roelle <harald.roelle@ifi.lmu.de> 2004/04/20
  27. * Fixes in packet dropping, queue length setting and queue wakeup.
  28. * Increased default tx queue length.
  29. * Added ethtool API.
  30. * Minor cleanups
  31. *
  32. * Daniel Podlejski <underley@underley.eu.org>
  33. * Modifications for 2.3.99-pre5 kernel.
  34. */
  35. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  36. #define DRV_NAME "tun"
  37. #define DRV_VERSION "1.6"
  38. #define DRV_DESCRIPTION "Universal TUN/TAP device driver"
  39. #define DRV_COPYRIGHT "(C) 1999-2004 Max Krasnyansky <maxk@qualcomm.com>"
  40. #include <linux/module.h>
  41. #include <linux/errno.h>
  42. #include <linux/kernel.h>
  43. #include <linux/sched/signal.h>
  44. #include <linux/major.h>
  45. #include <linux/slab.h>
  46. #include <linux/poll.h>
  47. #include <linux/fcntl.h>
  48. #include <linux/init.h>
  49. #include <linux/skbuff.h>
  50. #include <linux/netdevice.h>
  51. #include <linux/etherdevice.h>
  52. #include <linux/miscdevice.h>
  53. #include <linux/ethtool.h>
  54. #include <linux/rtnetlink.h>
  55. #include <linux/compat.h>
  56. #include <linux/if.h>
  57. #include <linux/if_arp.h>
  58. #include <linux/if_ether.h>
  59. #include <linux/if_tun.h>
  60. #include <linux/if_vlan.h>
  61. #include <linux/crc32.h>
  62. #include <linux/nsproxy.h>
  63. #include <linux/virtio_net.h>
  64. #include <linux/rcupdate.h>
  65. #include <net/net_namespace.h>
  66. #include <net/netns/generic.h>
  67. #include <net/rtnetlink.h>
  68. #include <net/sock.h>
  69. #include <net/xdp.h>
  70. #include <linux/seq_file.h>
  71. #include <linux/uio.h>
  72. #include <linux/skb_array.h>
  73. #include <linux/bpf.h>
  74. #include <linux/bpf_trace.h>
  75. #include <linux/mutex.h>
  76. #include <linux/uaccess.h>
  77. #include <linux/proc_fs.h>
  78. static void tun_default_link_ksettings(struct net_device *dev,
  79. struct ethtool_link_ksettings *cmd);
  80. /* Uncomment to enable debugging */
  81. /* #define TUN_DEBUG 1 */
  82. #ifdef TUN_DEBUG
  83. static int debug;
  84. #define tun_debug(level, tun, fmt, args...) \
  85. do { \
  86. if (tun->debug) \
  87. netdev_printk(level, tun->dev, fmt, ##args); \
  88. } while (0)
  89. #define DBG1(level, fmt, args...) \
  90. do { \
  91. if (debug == 2) \
  92. printk(level fmt, ##args); \
  93. } while (0)
  94. #else
  95. #define tun_debug(level, tun, fmt, args...) \
  96. do { \
  97. if (0) \
  98. netdev_printk(level, tun->dev, fmt, ##args); \
  99. } while (0)
  100. #define DBG1(level, fmt, args...) \
  101. do { \
  102. if (0) \
  103. printk(level fmt, ##args); \
  104. } while (0)
  105. #endif
  106. #define TUN_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
  107. /* TUN device flags */
  108. /* IFF_ATTACH_QUEUE is never stored in device flags,
  109. * overload it to mean fasync when stored there.
  110. */
  111. #define TUN_FASYNC IFF_ATTACH_QUEUE
  112. /* High bits in flags field are unused. */
  113. #define TUN_VNET_LE 0x80000000
  114. #define TUN_VNET_BE 0x40000000
  115. #define TUN_FEATURES (IFF_NO_PI | IFF_ONE_QUEUE | IFF_VNET_HDR | \
  116. IFF_MULTI_QUEUE | IFF_NAPI | IFF_NAPI_FRAGS)
  117. #define GOODCOPY_LEN 128
  118. #define FLT_EXACT_COUNT 8
  119. struct tap_filter {
  120. unsigned int count; /* Number of addrs. Zero means disabled */
  121. u32 mask[2]; /* Mask of the hashed addrs */
  122. unsigned char addr[FLT_EXACT_COUNT][ETH_ALEN];
  123. };
  124. /* MAX_TAP_QUEUES 256 is chosen to allow rx/tx queues to be equal
  125. * to max number of VCPUs in guest. */
  126. #define MAX_TAP_QUEUES 256
  127. #define MAX_TAP_FLOWS 4096
  128. #define TUN_FLOW_EXPIRE (3 * HZ)
  129. struct tun_pcpu_stats {
  130. u64 rx_packets;
  131. u64 rx_bytes;
  132. u64 tx_packets;
  133. u64 tx_bytes;
  134. struct u64_stats_sync syncp;
  135. u32 rx_dropped;
  136. u32 tx_dropped;
  137. u32 rx_frame_errors;
  138. };
  139. /* A tun_file connects an open character device to a tuntap netdevice. It
  140. * also contains all socket related structures (except sock_fprog and tap_filter)
  141. * to serve as one transmit queue for tuntap device. The sock_fprog and
  142. * tap_filter were kept in tun_struct since they were used for filtering for the
  143. * netdevice not for a specific queue (at least I didn't see the requirement for
  144. * this).
  145. *
  146. * RCU usage:
  147. * The tun_file and tun_struct are loosely coupled, the pointer from one to the
  148. * other can only be read while rcu_read_lock or rtnl_lock is held.
  149. */
  150. struct tun_file {
  151. struct sock sk;
  152. struct socket socket;
  153. struct socket_wq wq;
  154. struct tun_struct __rcu *tun;
  155. struct fasync_struct *fasync;
  156. /* only used for fasnyc */
  157. unsigned int flags;
  158. union {
  159. u16 queue_index;
  160. unsigned int ifindex;
  161. };
  162. struct napi_struct napi;
  163. bool napi_enabled;
  164. bool napi_frags_enabled;
  165. struct mutex napi_mutex; /* Protects access to the above napi */
  166. struct list_head next;
  167. struct tun_struct *detached;
  168. struct ptr_ring tx_ring;
  169. struct xdp_rxq_info xdp_rxq;
  170. };
  171. struct tun_flow_entry {
  172. struct hlist_node hash_link;
  173. struct rcu_head rcu;
  174. struct tun_struct *tun;
  175. u32 rxhash;
  176. u32 rps_rxhash;
  177. int queue_index;
  178. unsigned long updated;
  179. };
  180. #define TUN_NUM_FLOW_ENTRIES 1024
  181. #define TUN_MASK_FLOW_ENTRIES (TUN_NUM_FLOW_ENTRIES - 1)
  182. struct tun_prog {
  183. struct rcu_head rcu;
  184. struct bpf_prog *prog;
  185. };
  186. /* Since the socket were moved to tun_file, to preserve the behavior of persist
  187. * device, socket filter, sndbuf and vnet header size were restore when the
  188. * file were attached to a persist device.
  189. */
  190. struct tun_struct {
  191. struct tun_file __rcu *tfiles[MAX_TAP_QUEUES];
  192. unsigned int numqueues;
  193. unsigned int flags;
  194. kuid_t owner;
  195. kgid_t group;
  196. struct net_device *dev;
  197. netdev_features_t set_features;
  198. #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
  199. NETIF_F_TSO6)
  200. int align;
  201. int vnet_hdr_sz;
  202. int sndbuf;
  203. struct tap_filter txflt;
  204. struct sock_fprog fprog;
  205. /* protected by rtnl lock */
  206. bool filter_attached;
  207. #ifdef TUN_DEBUG
  208. int debug;
  209. #endif
  210. spinlock_t lock;
  211. struct hlist_head flows[TUN_NUM_FLOW_ENTRIES];
  212. struct timer_list flow_gc_timer;
  213. unsigned long ageing_time;
  214. unsigned int numdisabled;
  215. struct list_head disabled;
  216. void *security;
  217. u32 flow_count;
  218. u32 rx_batched;
  219. struct tun_pcpu_stats __percpu *pcpu_stats;
  220. struct bpf_prog __rcu *xdp_prog;
  221. struct tun_prog __rcu *steering_prog;
  222. struct tun_prog __rcu *filter_prog;
  223. struct ethtool_link_ksettings link_ksettings;
  224. };
  225. struct veth {
  226. __be16 h_vlan_proto;
  227. __be16 h_vlan_TCI;
  228. };
  229. bool tun_is_xdp_frame(void *ptr)
  230. {
  231. return (unsigned long)ptr & TUN_XDP_FLAG;
  232. }
  233. EXPORT_SYMBOL(tun_is_xdp_frame);
  234. void *tun_xdp_to_ptr(void *ptr)
  235. {
  236. return (void *)((unsigned long)ptr | TUN_XDP_FLAG);
  237. }
  238. EXPORT_SYMBOL(tun_xdp_to_ptr);
  239. void *tun_ptr_to_xdp(void *ptr)
  240. {
  241. return (void *)((unsigned long)ptr & ~TUN_XDP_FLAG);
  242. }
  243. EXPORT_SYMBOL(tun_ptr_to_xdp);
  244. static int tun_napi_receive(struct napi_struct *napi, int budget)
  245. {
  246. struct tun_file *tfile = container_of(napi, struct tun_file, napi);
  247. struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
  248. struct sk_buff_head process_queue;
  249. struct sk_buff *skb;
  250. int received = 0;
  251. __skb_queue_head_init(&process_queue);
  252. spin_lock(&queue->lock);
  253. skb_queue_splice_tail_init(queue, &process_queue);
  254. spin_unlock(&queue->lock);
  255. while (received < budget && (skb = __skb_dequeue(&process_queue))) {
  256. napi_gro_receive(napi, skb);
  257. ++received;
  258. }
  259. if (!skb_queue_empty(&process_queue)) {
  260. spin_lock(&queue->lock);
  261. skb_queue_splice(&process_queue, queue);
  262. spin_unlock(&queue->lock);
  263. }
  264. return received;
  265. }
  266. static int tun_napi_poll(struct napi_struct *napi, int budget)
  267. {
  268. unsigned int received;
  269. received = tun_napi_receive(napi, budget);
  270. if (received < budget)
  271. napi_complete_done(napi, received);
  272. return received;
  273. }
  274. static void tun_napi_init(struct tun_struct *tun, struct tun_file *tfile,
  275. bool napi_en, bool napi_frags)
  276. {
  277. tfile->napi_enabled = napi_en;
  278. tfile->napi_frags_enabled = napi_en && napi_frags;
  279. if (napi_en) {
  280. netif_napi_add(tun->dev, &tfile->napi, tun_napi_poll,
  281. NAPI_POLL_WEIGHT);
  282. napi_enable(&tfile->napi);
  283. }
  284. }
  285. static void tun_napi_disable(struct tun_file *tfile)
  286. {
  287. if (tfile->napi_enabled)
  288. napi_disable(&tfile->napi);
  289. }
  290. static void tun_napi_del(struct tun_file *tfile)
  291. {
  292. if (tfile->napi_enabled)
  293. netif_napi_del(&tfile->napi);
  294. }
  295. static bool tun_napi_frags_enabled(const struct tun_file *tfile)
  296. {
  297. return tfile->napi_frags_enabled;
  298. }
  299. #ifdef CONFIG_TUN_VNET_CROSS_LE
  300. static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
  301. {
  302. return tun->flags & TUN_VNET_BE ? false :
  303. virtio_legacy_is_little_endian();
  304. }
  305. static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
  306. {
  307. int be = !!(tun->flags & TUN_VNET_BE);
  308. if (put_user(be, argp))
  309. return -EFAULT;
  310. return 0;
  311. }
  312. static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
  313. {
  314. int be;
  315. if (get_user(be, argp))
  316. return -EFAULT;
  317. if (be)
  318. tun->flags |= TUN_VNET_BE;
  319. else
  320. tun->flags &= ~TUN_VNET_BE;
  321. return 0;
  322. }
  323. #else
  324. static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
  325. {
  326. return virtio_legacy_is_little_endian();
  327. }
  328. static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
  329. {
  330. return -EINVAL;
  331. }
  332. static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
  333. {
  334. return -EINVAL;
  335. }
  336. #endif /* CONFIG_TUN_VNET_CROSS_LE */
  337. static inline bool tun_is_little_endian(struct tun_struct *tun)
  338. {
  339. return tun->flags & TUN_VNET_LE ||
  340. tun_legacy_is_little_endian(tun);
  341. }
  342. static inline u16 tun16_to_cpu(struct tun_struct *tun, __virtio16 val)
  343. {
  344. return __virtio16_to_cpu(tun_is_little_endian(tun), val);
  345. }
  346. static inline __virtio16 cpu_to_tun16(struct tun_struct *tun, u16 val)
  347. {
  348. return __cpu_to_virtio16(tun_is_little_endian(tun), val);
  349. }
  350. static inline u32 tun_hashfn(u32 rxhash)
  351. {
  352. return rxhash & TUN_MASK_FLOW_ENTRIES;
  353. }
  354. static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash)
  355. {
  356. struct tun_flow_entry *e;
  357. hlist_for_each_entry_rcu(e, head, hash_link) {
  358. if (e->rxhash == rxhash)
  359. return e;
  360. }
  361. return NULL;
  362. }
  363. static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun,
  364. struct hlist_head *head,
  365. u32 rxhash, u16 queue_index)
  366. {
  367. struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC);
  368. if (e) {
  369. tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n",
  370. rxhash, queue_index);
  371. e->updated = jiffies;
  372. e->rxhash = rxhash;
  373. e->rps_rxhash = 0;
  374. e->queue_index = queue_index;
  375. e->tun = tun;
  376. hlist_add_head_rcu(&e->hash_link, head);
  377. ++tun->flow_count;
  378. }
  379. return e;
  380. }
  381. static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e)
  382. {
  383. tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n",
  384. e->rxhash, e->queue_index);
  385. hlist_del_rcu(&e->hash_link);
  386. kfree_rcu(e, rcu);
  387. --tun->flow_count;
  388. }
  389. static void tun_flow_flush(struct tun_struct *tun)
  390. {
  391. int i;
  392. spin_lock_bh(&tun->lock);
  393. for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
  394. struct tun_flow_entry *e;
  395. struct hlist_node *n;
  396. hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link)
  397. tun_flow_delete(tun, e);
  398. }
  399. spin_unlock_bh(&tun->lock);
  400. }
  401. static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index)
  402. {
  403. int i;
  404. spin_lock_bh(&tun->lock);
  405. for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
  406. struct tun_flow_entry *e;
  407. struct hlist_node *n;
  408. hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
  409. if (e->queue_index == queue_index)
  410. tun_flow_delete(tun, e);
  411. }
  412. }
  413. spin_unlock_bh(&tun->lock);
  414. }
  415. static void tun_flow_cleanup(struct timer_list *t)
  416. {
  417. struct tun_struct *tun = from_timer(tun, t, flow_gc_timer);
  418. unsigned long delay = tun->ageing_time;
  419. unsigned long next_timer = jiffies + delay;
  420. unsigned long count = 0;
  421. int i;
  422. tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n");
  423. spin_lock(&tun->lock);
  424. for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
  425. struct tun_flow_entry *e;
  426. struct hlist_node *n;
  427. hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
  428. unsigned long this_timer;
  429. this_timer = e->updated + delay;
  430. if (time_before_eq(this_timer, jiffies)) {
  431. tun_flow_delete(tun, e);
  432. continue;
  433. }
  434. count++;
  435. if (time_before(this_timer, next_timer))
  436. next_timer = this_timer;
  437. }
  438. }
  439. if (count)
  440. mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer));
  441. spin_unlock(&tun->lock);
  442. }
  443. static void tun_flow_update(struct tun_struct *tun, u32 rxhash,
  444. struct tun_file *tfile)
  445. {
  446. struct hlist_head *head;
  447. struct tun_flow_entry *e;
  448. unsigned long delay = tun->ageing_time;
  449. u16 queue_index = tfile->queue_index;
  450. if (!rxhash)
  451. return;
  452. else
  453. head = &tun->flows[tun_hashfn(rxhash)];
  454. rcu_read_lock();
  455. e = tun_flow_find(head, rxhash);
  456. if (likely(e)) {
  457. /* TODO: keep queueing to old queue until it's empty? */
  458. e->queue_index = queue_index;
  459. e->updated = jiffies;
  460. sock_rps_record_flow_hash(e->rps_rxhash);
  461. } else {
  462. spin_lock_bh(&tun->lock);
  463. if (!tun_flow_find(head, rxhash) &&
  464. tun->flow_count < MAX_TAP_FLOWS)
  465. tun_flow_create(tun, head, rxhash, queue_index);
  466. if (!timer_pending(&tun->flow_gc_timer))
  467. mod_timer(&tun->flow_gc_timer,
  468. round_jiffies_up(jiffies + delay));
  469. spin_unlock_bh(&tun->lock);
  470. }
  471. rcu_read_unlock();
  472. }
  473. /**
  474. * Save the hash received in the stack receive path and update the
  475. * flow_hash table accordingly.
  476. */
  477. static inline void tun_flow_save_rps_rxhash(struct tun_flow_entry *e, u32 hash)
  478. {
  479. if (unlikely(e->rps_rxhash != hash))
  480. e->rps_rxhash = hash;
  481. }
  482. /* We try to identify a flow through its rxhash. The reason that
  483. * we do not check rxq no. is because some cards(e.g 82599), chooses
  484. * the rxq based on the txq where the last packet of the flow comes. As
  485. * the userspace application move between processors, we may get a
  486. * different rxq no. here.
  487. */
  488. static u16 tun_automq_select_queue(struct tun_struct *tun, struct sk_buff *skb)
  489. {
  490. struct tun_flow_entry *e;
  491. u32 txq = 0;
  492. u32 numqueues = 0;
  493. numqueues = READ_ONCE(tun->numqueues);
  494. txq = __skb_get_hash_symmetric(skb);
  495. e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq);
  496. if (e) {
  497. tun_flow_save_rps_rxhash(e, txq);
  498. txq = e->queue_index;
  499. } else {
  500. /* use multiply and shift instead of expensive divide */
  501. txq = ((u64)txq * numqueues) >> 32;
  502. }
  503. return txq;
  504. }
  505. static u16 tun_ebpf_select_queue(struct tun_struct *tun, struct sk_buff *skb)
  506. {
  507. struct tun_prog *prog;
  508. u16 ret = 0;
  509. prog = rcu_dereference(tun->steering_prog);
  510. if (prog)
  511. ret = bpf_prog_run_clear_cb(prog->prog, skb);
  512. return ret % tun->numqueues;
  513. }
  514. static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb,
  515. struct net_device *sb_dev,
  516. select_queue_fallback_t fallback)
  517. {
  518. struct tun_struct *tun = netdev_priv(dev);
  519. u16 ret;
  520. rcu_read_lock();
  521. if (rcu_dereference(tun->steering_prog))
  522. ret = tun_ebpf_select_queue(tun, skb);
  523. else
  524. ret = tun_automq_select_queue(tun, skb);
  525. rcu_read_unlock();
  526. return ret;
  527. }
  528. static inline bool tun_not_capable(struct tun_struct *tun)
  529. {
  530. const struct cred *cred = current_cred();
  531. struct net *net = dev_net(tun->dev);
  532. return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
  533. (gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
  534. !ns_capable(net->user_ns, CAP_NET_ADMIN);
  535. }
  536. static void tun_set_real_num_queues(struct tun_struct *tun)
  537. {
  538. netif_set_real_num_tx_queues(tun->dev, tun->numqueues);
  539. netif_set_real_num_rx_queues(tun->dev, tun->numqueues);
  540. }
  541. static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile)
  542. {
  543. tfile->detached = tun;
  544. list_add_tail(&tfile->next, &tun->disabled);
  545. ++tun->numdisabled;
  546. }
  547. static struct tun_struct *tun_enable_queue(struct tun_file *tfile)
  548. {
  549. struct tun_struct *tun = tfile->detached;
  550. tfile->detached = NULL;
  551. list_del_init(&tfile->next);
  552. --tun->numdisabled;
  553. return tun;
  554. }
  555. void tun_ptr_free(void *ptr)
  556. {
  557. if (!ptr)
  558. return;
  559. if (tun_is_xdp_frame(ptr)) {
  560. struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
  561. xdp_return_frame(xdpf);
  562. } else {
  563. __skb_array_destroy_skb(ptr);
  564. }
  565. }
  566. EXPORT_SYMBOL_GPL(tun_ptr_free);
  567. static void tun_queue_purge(struct tun_file *tfile)
  568. {
  569. void *ptr;
  570. while ((ptr = ptr_ring_consume(&tfile->tx_ring)) != NULL)
  571. tun_ptr_free(ptr);
  572. skb_queue_purge(&tfile->sk.sk_write_queue);
  573. skb_queue_purge(&tfile->sk.sk_error_queue);
  574. }
  575. static void __tun_detach(struct tun_file *tfile, bool clean)
  576. {
  577. struct tun_file *ntfile;
  578. struct tun_struct *tun;
  579. tun = rtnl_dereference(tfile->tun);
  580. if (tun && clean) {
  581. tun_napi_disable(tfile);
  582. tun_napi_del(tfile);
  583. }
  584. if (tun && !tfile->detached) {
  585. u16 index = tfile->queue_index;
  586. BUG_ON(index >= tun->numqueues);
  587. rcu_assign_pointer(tun->tfiles[index],
  588. tun->tfiles[tun->numqueues - 1]);
  589. ntfile = rtnl_dereference(tun->tfiles[index]);
  590. ntfile->queue_index = index;
  591. --tun->numqueues;
  592. if (clean) {
  593. RCU_INIT_POINTER(tfile->tun, NULL);
  594. sock_put(&tfile->sk);
  595. } else
  596. tun_disable_queue(tun, tfile);
  597. synchronize_net();
  598. tun_flow_delete_by_queue(tun, tun->numqueues + 1);
  599. /* Drop read queue */
  600. tun_queue_purge(tfile);
  601. tun_set_real_num_queues(tun);
  602. } else if (tfile->detached && clean) {
  603. tun = tun_enable_queue(tfile);
  604. sock_put(&tfile->sk);
  605. }
  606. if (clean) {
  607. if (tun && tun->numqueues == 0 && tun->numdisabled == 0) {
  608. netif_carrier_off(tun->dev);
  609. if (!(tun->flags & IFF_PERSIST) &&
  610. tun->dev->reg_state == NETREG_REGISTERED)
  611. unregister_netdevice(tun->dev);
  612. }
  613. if (tun)
  614. xdp_rxq_info_unreg(&tfile->xdp_rxq);
  615. ptr_ring_cleanup(&tfile->tx_ring, tun_ptr_free);
  616. sock_put(&tfile->sk);
  617. }
  618. }
  619. static void tun_detach(struct tun_file *tfile, bool clean)
  620. {
  621. struct tun_struct *tun;
  622. struct net_device *dev;
  623. rtnl_lock();
  624. tun = rtnl_dereference(tfile->tun);
  625. dev = tun ? tun->dev : NULL;
  626. __tun_detach(tfile, clean);
  627. if (dev)
  628. netdev_state_change(dev);
  629. rtnl_unlock();
  630. }
  631. static void tun_detach_all(struct net_device *dev)
  632. {
  633. struct tun_struct *tun = netdev_priv(dev);
  634. struct tun_file *tfile, *tmp;
  635. int i, n = tun->numqueues;
  636. for (i = 0; i < n; i++) {
  637. tfile = rtnl_dereference(tun->tfiles[i]);
  638. BUG_ON(!tfile);
  639. tun_napi_disable(tfile);
  640. tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
  641. tfile->socket.sk->sk_data_ready(tfile->socket.sk);
  642. RCU_INIT_POINTER(tfile->tun, NULL);
  643. --tun->numqueues;
  644. }
  645. list_for_each_entry(tfile, &tun->disabled, next) {
  646. tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
  647. tfile->socket.sk->sk_data_ready(tfile->socket.sk);
  648. RCU_INIT_POINTER(tfile->tun, NULL);
  649. }
  650. BUG_ON(tun->numqueues != 0);
  651. synchronize_net();
  652. for (i = 0; i < n; i++) {
  653. tfile = rtnl_dereference(tun->tfiles[i]);
  654. tun_napi_del(tfile);
  655. /* Drop read queue */
  656. tun_queue_purge(tfile);
  657. xdp_rxq_info_unreg(&tfile->xdp_rxq);
  658. sock_put(&tfile->sk);
  659. }
  660. list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
  661. tun_enable_queue(tfile);
  662. tun_queue_purge(tfile);
  663. xdp_rxq_info_unreg(&tfile->xdp_rxq);
  664. sock_put(&tfile->sk);
  665. }
  666. BUG_ON(tun->numdisabled != 0);
  667. if (tun->flags & IFF_PERSIST)
  668. module_put(THIS_MODULE);
  669. }
  670. static int tun_attach(struct tun_struct *tun, struct file *file,
  671. bool skip_filter, bool napi, bool napi_frags)
  672. {
  673. struct tun_file *tfile = file->private_data;
  674. struct net_device *dev = tun->dev;
  675. int err;
  676. err = security_tun_dev_attach(tfile->socket.sk, tun->security);
  677. if (err < 0)
  678. goto out;
  679. err = -EINVAL;
  680. if (rtnl_dereference(tfile->tun) && !tfile->detached)
  681. goto out;
  682. err = -EBUSY;
  683. if (!(tun->flags & IFF_MULTI_QUEUE) && tun->numqueues == 1)
  684. goto out;
  685. err = -E2BIG;
  686. if (!tfile->detached &&
  687. tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES)
  688. goto out;
  689. err = 0;
  690. /* Re-attach the filter to persist device */
  691. if (!skip_filter && (tun->filter_attached == true)) {
  692. lock_sock(tfile->socket.sk);
  693. err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
  694. release_sock(tfile->socket.sk);
  695. if (!err)
  696. goto out;
  697. }
  698. if (!tfile->detached &&
  699. ptr_ring_resize(&tfile->tx_ring, dev->tx_queue_len,
  700. GFP_KERNEL, tun_ptr_free)) {
  701. err = -ENOMEM;
  702. goto out;
  703. }
  704. tfile->queue_index = tun->numqueues;
  705. tfile->socket.sk->sk_shutdown &= ~RCV_SHUTDOWN;
  706. if (tfile->detached) {
  707. /* Re-attach detached tfile, updating XDP queue_index */
  708. WARN_ON(!xdp_rxq_info_is_reg(&tfile->xdp_rxq));
  709. if (tfile->xdp_rxq.queue_index != tfile->queue_index)
  710. tfile->xdp_rxq.queue_index = tfile->queue_index;
  711. } else {
  712. /* Setup XDP RX-queue info, for new tfile getting attached */
  713. err = xdp_rxq_info_reg(&tfile->xdp_rxq,
  714. tun->dev, tfile->queue_index);
  715. if (err < 0)
  716. goto out;
  717. err = xdp_rxq_info_reg_mem_model(&tfile->xdp_rxq,
  718. MEM_TYPE_PAGE_SHARED, NULL);
  719. if (err < 0) {
  720. xdp_rxq_info_unreg(&tfile->xdp_rxq);
  721. goto out;
  722. }
  723. err = 0;
  724. }
  725. rcu_assign_pointer(tfile->tun, tun);
  726. rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile);
  727. tun->numqueues++;
  728. if (tfile->detached) {
  729. tun_enable_queue(tfile);
  730. } else {
  731. sock_hold(&tfile->sk);
  732. tun_napi_init(tun, tfile, napi, napi_frags);
  733. }
  734. if (rtnl_dereference(tun->xdp_prog))
  735. sock_set_flag(&tfile->sk, SOCK_XDP);
  736. tun_set_real_num_queues(tun);
  737. /* device is allowed to go away first, so no need to hold extra
  738. * refcnt.
  739. */
  740. out:
  741. return err;
  742. }
  743. static struct tun_struct *tun_get(struct tun_file *tfile)
  744. {
  745. struct tun_struct *tun;
  746. rcu_read_lock();
  747. tun = rcu_dereference(tfile->tun);
  748. if (tun)
  749. dev_hold(tun->dev);
  750. rcu_read_unlock();
  751. return tun;
  752. }
  753. static void tun_put(struct tun_struct *tun)
  754. {
  755. dev_put(tun->dev);
  756. }
  757. /* TAP filtering */
  758. static void addr_hash_set(u32 *mask, const u8 *addr)
  759. {
  760. int n = ether_crc(ETH_ALEN, addr) >> 26;
  761. mask[n >> 5] |= (1 << (n & 31));
  762. }
  763. static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
  764. {
  765. int n = ether_crc(ETH_ALEN, addr) >> 26;
  766. return mask[n >> 5] & (1 << (n & 31));
  767. }
  768. static int update_filter(struct tap_filter *filter, void __user *arg)
  769. {
  770. struct { u8 u[ETH_ALEN]; } *addr;
  771. struct tun_filter uf;
  772. int err, alen, n, nexact;
  773. if (copy_from_user(&uf, arg, sizeof(uf)))
  774. return -EFAULT;
  775. if (!uf.count) {
  776. /* Disabled */
  777. filter->count = 0;
  778. return 0;
  779. }
  780. alen = ETH_ALEN * uf.count;
  781. addr = memdup_user(arg + sizeof(uf), alen);
  782. if (IS_ERR(addr))
  783. return PTR_ERR(addr);
  784. /* The filter is updated without holding any locks. Which is
  785. * perfectly safe. We disable it first and in the worst
  786. * case we'll accept a few undesired packets. */
  787. filter->count = 0;
  788. wmb();
  789. /* Use first set of addresses as an exact filter */
  790. for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
  791. memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
  792. nexact = n;
  793. /* Remaining multicast addresses are hashed,
  794. * unicast will leave the filter disabled. */
  795. memset(filter->mask, 0, sizeof(filter->mask));
  796. for (; n < uf.count; n++) {
  797. if (!is_multicast_ether_addr(addr[n].u)) {
  798. err = 0; /* no filter */
  799. goto free_addr;
  800. }
  801. addr_hash_set(filter->mask, addr[n].u);
  802. }
  803. /* For ALLMULTI just set the mask to all ones.
  804. * This overrides the mask populated above. */
  805. if ((uf.flags & TUN_FLT_ALLMULTI))
  806. memset(filter->mask, ~0, sizeof(filter->mask));
  807. /* Now enable the filter */
  808. wmb();
  809. filter->count = nexact;
  810. /* Return the number of exact filters */
  811. err = nexact;
  812. free_addr:
  813. kfree(addr);
  814. return err;
  815. }
  816. /* Returns: 0 - drop, !=0 - accept */
  817. static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
  818. {
  819. /* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
  820. * at this point. */
  821. struct ethhdr *eh = (struct ethhdr *) skb->data;
  822. int i;
  823. /* Exact match */
  824. for (i = 0; i < filter->count; i++)
  825. if (ether_addr_equal(eh->h_dest, filter->addr[i]))
  826. return 1;
  827. /* Inexact match (multicast only) */
  828. if (is_multicast_ether_addr(eh->h_dest))
  829. return addr_hash_test(filter->mask, eh->h_dest);
  830. return 0;
  831. }
  832. /*
  833. * Checks whether the packet is accepted or not.
  834. * Returns: 0 - drop, !=0 - accept
  835. */
  836. static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
  837. {
  838. if (!filter->count)
  839. return 1;
  840. return run_filter(filter, skb);
  841. }
  842. /* Network device part of the driver */
  843. static const struct ethtool_ops tun_ethtool_ops;
  844. /* Net device detach from fd. */
  845. static void tun_net_uninit(struct net_device *dev)
  846. {
  847. tun_detach_all(dev);
  848. }
  849. /* Net device open. */
  850. static int tun_net_open(struct net_device *dev)
  851. {
  852. struct tun_struct *tun = netdev_priv(dev);
  853. int i;
  854. netif_tx_start_all_queues(dev);
  855. for (i = 0; i < tun->numqueues; i++) {
  856. struct tun_file *tfile;
  857. tfile = rtnl_dereference(tun->tfiles[i]);
  858. tfile->socket.sk->sk_write_space(tfile->socket.sk);
  859. }
  860. return 0;
  861. }
  862. /* Net device close. */
  863. static int tun_net_close(struct net_device *dev)
  864. {
  865. netif_tx_stop_all_queues(dev);
  866. return 0;
  867. }
  868. /* Net device start xmit */
  869. static void tun_automq_xmit(struct tun_struct *tun, struct sk_buff *skb)
  870. {
  871. #ifdef CONFIG_RPS
  872. if (tun->numqueues == 1 && static_key_false(&rps_needed)) {
  873. /* Select queue was not called for the skbuff, so we extract the
  874. * RPS hash and save it into the flow_table here.
  875. */
  876. struct tun_flow_entry *e;
  877. __u32 rxhash;
  878. rxhash = __skb_get_hash_symmetric(skb);
  879. e = tun_flow_find(&tun->flows[tun_hashfn(rxhash)], rxhash);
  880. if (e)
  881. tun_flow_save_rps_rxhash(e, rxhash);
  882. }
  883. #endif
  884. }
  885. static unsigned int run_ebpf_filter(struct tun_struct *tun,
  886. struct sk_buff *skb,
  887. int len)
  888. {
  889. struct tun_prog *prog = rcu_dereference(tun->filter_prog);
  890. if (prog)
  891. len = bpf_prog_run_clear_cb(prog->prog, skb);
  892. return len;
  893. }
  894. /* Net device start xmit */
  895. static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
  896. {
  897. struct tun_struct *tun = netdev_priv(dev);
  898. int txq = skb->queue_mapping;
  899. struct tun_file *tfile;
  900. int len = skb->len;
  901. rcu_read_lock();
  902. tfile = rcu_dereference(tun->tfiles[txq]);
  903. /* Drop packet if interface is not attached */
  904. if (txq >= tun->numqueues)
  905. goto drop;
  906. if (!rcu_dereference(tun->steering_prog))
  907. tun_automq_xmit(tun, skb);
  908. tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len);
  909. BUG_ON(!tfile);
  910. /* Drop if the filter does not like it.
  911. * This is a noop if the filter is disabled.
  912. * Filter can be enabled only for the TAP devices. */
  913. if (!check_filter(&tun->txflt, skb))
  914. goto drop;
  915. if (tfile->socket.sk->sk_filter &&
  916. sk_filter(tfile->socket.sk, skb))
  917. goto drop;
  918. len = run_ebpf_filter(tun, skb, len);
  919. if (len == 0 || pskb_trim(skb, len))
  920. goto drop;
  921. if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
  922. goto drop;
  923. skb_tx_timestamp(skb);
  924. /* Orphan the skb - required as we might hang on to it
  925. * for indefinite time.
  926. */
  927. skb_orphan(skb);
  928. nf_reset(skb);
  929. if (ptr_ring_produce(&tfile->tx_ring, skb))
  930. goto drop;
  931. /* Notify and wake up reader process */
  932. if (tfile->flags & TUN_FASYNC)
  933. kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
  934. tfile->socket.sk->sk_data_ready(tfile->socket.sk);
  935. rcu_read_unlock();
  936. return NETDEV_TX_OK;
  937. drop:
  938. this_cpu_inc(tun->pcpu_stats->tx_dropped);
  939. skb_tx_error(skb);
  940. kfree_skb(skb);
  941. rcu_read_unlock();
  942. return NET_XMIT_DROP;
  943. }
  944. static void tun_net_mclist(struct net_device *dev)
  945. {
  946. /*
  947. * This callback is supposed to deal with mc filter in
  948. * _rx_ path and has nothing to do with the _tx_ path.
  949. * In rx path we always accept everything userspace gives us.
  950. */
  951. }
  952. static netdev_features_t tun_net_fix_features(struct net_device *dev,
  953. netdev_features_t features)
  954. {
  955. struct tun_struct *tun = netdev_priv(dev);
  956. return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
  957. }
  958. static void tun_set_headroom(struct net_device *dev, int new_hr)
  959. {
  960. struct tun_struct *tun = netdev_priv(dev);
  961. if (new_hr < NET_SKB_PAD)
  962. new_hr = NET_SKB_PAD;
  963. tun->align = new_hr;
  964. }
  965. static void
  966. tun_net_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats)
  967. {
  968. u32 rx_dropped = 0, tx_dropped = 0, rx_frame_errors = 0;
  969. struct tun_struct *tun = netdev_priv(dev);
  970. struct tun_pcpu_stats *p;
  971. int i;
  972. for_each_possible_cpu(i) {
  973. u64 rxpackets, rxbytes, txpackets, txbytes;
  974. unsigned int start;
  975. p = per_cpu_ptr(tun->pcpu_stats, i);
  976. do {
  977. start = u64_stats_fetch_begin(&p->syncp);
  978. rxpackets = p->rx_packets;
  979. rxbytes = p->rx_bytes;
  980. txpackets = p->tx_packets;
  981. txbytes = p->tx_bytes;
  982. } while (u64_stats_fetch_retry(&p->syncp, start));
  983. stats->rx_packets += rxpackets;
  984. stats->rx_bytes += rxbytes;
  985. stats->tx_packets += txpackets;
  986. stats->tx_bytes += txbytes;
  987. /* u32 counters */
  988. rx_dropped += p->rx_dropped;
  989. rx_frame_errors += p->rx_frame_errors;
  990. tx_dropped += p->tx_dropped;
  991. }
  992. stats->rx_dropped = rx_dropped;
  993. stats->rx_frame_errors = rx_frame_errors;
  994. stats->tx_dropped = tx_dropped;
  995. }
  996. static int tun_xdp_set(struct net_device *dev, struct bpf_prog *prog,
  997. struct netlink_ext_ack *extack)
  998. {
  999. struct tun_struct *tun = netdev_priv(dev);
  1000. struct tun_file *tfile;
  1001. struct bpf_prog *old_prog;
  1002. int i;
  1003. old_prog = rtnl_dereference(tun->xdp_prog);
  1004. rcu_assign_pointer(tun->xdp_prog, prog);
  1005. if (old_prog)
  1006. bpf_prog_put(old_prog);
  1007. for (i = 0; i < tun->numqueues; i++) {
  1008. tfile = rtnl_dereference(tun->tfiles[i]);
  1009. if (prog)
  1010. sock_set_flag(&tfile->sk, SOCK_XDP);
  1011. else
  1012. sock_reset_flag(&tfile->sk, SOCK_XDP);
  1013. }
  1014. list_for_each_entry(tfile, &tun->disabled, next) {
  1015. if (prog)
  1016. sock_set_flag(&tfile->sk, SOCK_XDP);
  1017. else
  1018. sock_reset_flag(&tfile->sk, SOCK_XDP);
  1019. }
  1020. return 0;
  1021. }
  1022. static u32 tun_xdp_query(struct net_device *dev)
  1023. {
  1024. struct tun_struct *tun = netdev_priv(dev);
  1025. const struct bpf_prog *xdp_prog;
  1026. xdp_prog = rtnl_dereference(tun->xdp_prog);
  1027. if (xdp_prog)
  1028. return xdp_prog->aux->id;
  1029. return 0;
  1030. }
  1031. static int tun_xdp(struct net_device *dev, struct netdev_bpf *xdp)
  1032. {
  1033. switch (xdp->command) {
  1034. case XDP_SETUP_PROG:
  1035. return tun_xdp_set(dev, xdp->prog, xdp->extack);
  1036. case XDP_QUERY_PROG:
  1037. xdp->prog_id = tun_xdp_query(dev);
  1038. return 0;
  1039. default:
  1040. return -EINVAL;
  1041. }
  1042. }
  1043. static const struct net_device_ops tun_netdev_ops = {
  1044. .ndo_uninit = tun_net_uninit,
  1045. .ndo_open = tun_net_open,
  1046. .ndo_stop = tun_net_close,
  1047. .ndo_start_xmit = tun_net_xmit,
  1048. .ndo_fix_features = tun_net_fix_features,
  1049. .ndo_select_queue = tun_select_queue,
  1050. .ndo_set_rx_headroom = tun_set_headroom,
  1051. .ndo_get_stats64 = tun_net_get_stats64,
  1052. };
  1053. static void __tun_xdp_flush_tfile(struct tun_file *tfile)
  1054. {
  1055. /* Notify and wake up reader process */
  1056. if (tfile->flags & TUN_FASYNC)
  1057. kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
  1058. tfile->socket.sk->sk_data_ready(tfile->socket.sk);
  1059. }
  1060. static int tun_xdp_xmit(struct net_device *dev, int n,
  1061. struct xdp_frame **frames, u32 flags)
  1062. {
  1063. struct tun_struct *tun = netdev_priv(dev);
  1064. struct tun_file *tfile;
  1065. u32 numqueues;
  1066. int drops = 0;
  1067. int cnt = n;
  1068. int i;
  1069. if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK))
  1070. return -EINVAL;
  1071. rcu_read_lock();
  1072. numqueues = READ_ONCE(tun->numqueues);
  1073. if (!numqueues) {
  1074. rcu_read_unlock();
  1075. return -ENXIO; /* Caller will free/return all frames */
  1076. }
  1077. tfile = rcu_dereference(tun->tfiles[smp_processor_id() %
  1078. numqueues]);
  1079. spin_lock(&tfile->tx_ring.producer_lock);
  1080. for (i = 0; i < n; i++) {
  1081. struct xdp_frame *xdp = frames[i];
  1082. /* Encode the XDP flag into lowest bit for consumer to differ
  1083. * XDP buffer from sk_buff.
  1084. */
  1085. void *frame = tun_xdp_to_ptr(xdp);
  1086. if (__ptr_ring_produce(&tfile->tx_ring, frame)) {
  1087. this_cpu_inc(tun->pcpu_stats->tx_dropped);
  1088. xdp_return_frame_rx_napi(xdp);
  1089. drops++;
  1090. }
  1091. }
  1092. spin_unlock(&tfile->tx_ring.producer_lock);
  1093. if (flags & XDP_XMIT_FLUSH)
  1094. __tun_xdp_flush_tfile(tfile);
  1095. rcu_read_unlock();
  1096. return cnt - drops;
  1097. }
  1098. static int tun_xdp_tx(struct net_device *dev, struct xdp_buff *xdp)
  1099. {
  1100. struct xdp_frame *frame = convert_to_xdp_frame(xdp);
  1101. if (unlikely(!frame))
  1102. return -EOVERFLOW;
  1103. return tun_xdp_xmit(dev, 1, &frame, XDP_XMIT_FLUSH);
  1104. }
  1105. static const struct net_device_ops tap_netdev_ops = {
  1106. .ndo_uninit = tun_net_uninit,
  1107. .ndo_open = tun_net_open,
  1108. .ndo_stop = tun_net_close,
  1109. .ndo_start_xmit = tun_net_xmit,
  1110. .ndo_fix_features = tun_net_fix_features,
  1111. .ndo_set_rx_mode = tun_net_mclist,
  1112. .ndo_set_mac_address = eth_mac_addr,
  1113. .ndo_validate_addr = eth_validate_addr,
  1114. .ndo_select_queue = tun_select_queue,
  1115. .ndo_features_check = passthru_features_check,
  1116. .ndo_set_rx_headroom = tun_set_headroom,
  1117. .ndo_get_stats64 = tun_net_get_stats64,
  1118. .ndo_bpf = tun_xdp,
  1119. .ndo_xdp_xmit = tun_xdp_xmit,
  1120. };
  1121. static void tun_flow_init(struct tun_struct *tun)
  1122. {
  1123. int i;
  1124. for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++)
  1125. INIT_HLIST_HEAD(&tun->flows[i]);
  1126. tun->ageing_time = TUN_FLOW_EXPIRE;
  1127. timer_setup(&tun->flow_gc_timer, tun_flow_cleanup, 0);
  1128. mod_timer(&tun->flow_gc_timer,
  1129. round_jiffies_up(jiffies + tun->ageing_time));
  1130. }
  1131. static void tun_flow_uninit(struct tun_struct *tun)
  1132. {
  1133. del_timer_sync(&tun->flow_gc_timer);
  1134. tun_flow_flush(tun);
  1135. }
  1136. #define MIN_MTU 68
  1137. #define MAX_MTU 65535
  1138. /* Initialize net device. */
  1139. static void tun_net_init(struct net_device *dev)
  1140. {
  1141. struct tun_struct *tun = netdev_priv(dev);
  1142. switch (tun->flags & TUN_TYPE_MASK) {
  1143. case IFF_TUN:
  1144. dev->netdev_ops = &tun_netdev_ops;
  1145. /* Point-to-Point TUN Device */
  1146. dev->hard_header_len = 0;
  1147. dev->addr_len = 0;
  1148. dev->mtu = 1500;
  1149. /* Zero header length */
  1150. dev->type = ARPHRD_NONE;
  1151. dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
  1152. break;
  1153. case IFF_TAP:
  1154. dev->netdev_ops = &tap_netdev_ops;
  1155. /* Ethernet TAP Device */
  1156. ether_setup(dev);
  1157. dev->priv_flags &= ~IFF_TX_SKB_SHARING;
  1158. dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
  1159. eth_hw_addr_random(dev);
  1160. break;
  1161. }
  1162. dev->min_mtu = MIN_MTU;
  1163. dev->max_mtu = MAX_MTU - dev->hard_header_len;
  1164. }
  1165. static bool tun_sock_writeable(struct tun_struct *tun, struct tun_file *tfile)
  1166. {
  1167. struct sock *sk = tfile->socket.sk;
  1168. return (tun->dev->flags & IFF_UP) && sock_writeable(sk);
  1169. }
  1170. /* Character device part */
  1171. /* Poll */
  1172. static __poll_t tun_chr_poll(struct file *file, poll_table *wait)
  1173. {
  1174. struct tun_file *tfile = file->private_data;
  1175. struct tun_struct *tun = tun_get(tfile);
  1176. struct sock *sk;
  1177. __poll_t mask = 0;
  1178. if (!tun)
  1179. return EPOLLERR;
  1180. sk = tfile->socket.sk;
  1181. tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
  1182. poll_wait(file, sk_sleep(sk), wait);
  1183. if (!ptr_ring_empty(&tfile->tx_ring))
  1184. mask |= EPOLLIN | EPOLLRDNORM;
  1185. /* Make sure SOCKWQ_ASYNC_NOSPACE is set if not writable to
  1186. * guarantee EPOLLOUT to be raised by either here or
  1187. * tun_sock_write_space(). Then process could get notification
  1188. * after it writes to a down device and meets -EIO.
  1189. */
  1190. if (tun_sock_writeable(tun, tfile) ||
  1191. (!test_and_set_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
  1192. tun_sock_writeable(tun, tfile)))
  1193. mask |= EPOLLOUT | EPOLLWRNORM;
  1194. if (tun->dev->reg_state != NETREG_REGISTERED)
  1195. mask = EPOLLERR;
  1196. tun_put(tun);
  1197. return mask;
  1198. }
  1199. static struct sk_buff *tun_napi_alloc_frags(struct tun_file *tfile,
  1200. size_t len,
  1201. const struct iov_iter *it)
  1202. {
  1203. struct sk_buff *skb;
  1204. size_t linear;
  1205. int err;
  1206. int i;
  1207. if (it->nr_segs > MAX_SKB_FRAGS + 1)
  1208. return ERR_PTR(-ENOMEM);
  1209. local_bh_disable();
  1210. skb = napi_get_frags(&tfile->napi);
  1211. local_bh_enable();
  1212. if (!skb)
  1213. return ERR_PTR(-ENOMEM);
  1214. linear = iov_iter_single_seg_count(it);
  1215. err = __skb_grow(skb, linear);
  1216. if (err)
  1217. goto free;
  1218. skb->len = len;
  1219. skb->data_len = len - linear;
  1220. skb->truesize += skb->data_len;
  1221. for (i = 1; i < it->nr_segs; i++) {
  1222. struct page_frag *pfrag = &current->task_frag;
  1223. size_t fragsz = it->iov[i].iov_len;
  1224. if (fragsz == 0 || fragsz > PAGE_SIZE) {
  1225. err = -EINVAL;
  1226. goto free;
  1227. }
  1228. if (!skb_page_frag_refill(fragsz, pfrag, GFP_KERNEL)) {
  1229. err = -ENOMEM;
  1230. goto free;
  1231. }
  1232. skb_fill_page_desc(skb, i - 1, pfrag->page,
  1233. pfrag->offset, fragsz);
  1234. page_ref_inc(pfrag->page);
  1235. pfrag->offset += fragsz;
  1236. }
  1237. return skb;
  1238. free:
  1239. /* frees skb and all frags allocated with napi_alloc_frag() */
  1240. napi_free_frags(&tfile->napi);
  1241. return ERR_PTR(err);
  1242. }
  1243. /* prepad is the amount to reserve at front. len is length after that.
  1244. * linear is a hint as to how much to copy (usually headers). */
  1245. static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
  1246. size_t prepad, size_t len,
  1247. size_t linear, int noblock)
  1248. {
  1249. struct sock *sk = tfile->socket.sk;
  1250. struct sk_buff *skb;
  1251. int err;
  1252. /* Under a page? Don't bother with paged skb. */
  1253. if (prepad + len < PAGE_SIZE || !linear)
  1254. linear = len;
  1255. skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
  1256. &err, 0);
  1257. if (!skb)
  1258. return ERR_PTR(err);
  1259. skb_reserve(skb, prepad);
  1260. skb_put(skb, linear);
  1261. skb->data_len = len - linear;
  1262. skb->len += len - linear;
  1263. return skb;
  1264. }
  1265. static void tun_rx_batched(struct tun_struct *tun, struct tun_file *tfile,
  1266. struct sk_buff *skb, int more)
  1267. {
  1268. struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
  1269. struct sk_buff_head process_queue;
  1270. u32 rx_batched = tun->rx_batched;
  1271. bool rcv = false;
  1272. if (!rx_batched || (!more && skb_queue_empty(queue))) {
  1273. local_bh_disable();
  1274. skb_record_rx_queue(skb, tfile->queue_index);
  1275. netif_receive_skb(skb);
  1276. local_bh_enable();
  1277. return;
  1278. }
  1279. spin_lock(&queue->lock);
  1280. if (!more || skb_queue_len(queue) == rx_batched) {
  1281. __skb_queue_head_init(&process_queue);
  1282. skb_queue_splice_tail_init(queue, &process_queue);
  1283. rcv = true;
  1284. } else {
  1285. __skb_queue_tail(queue, skb);
  1286. }
  1287. spin_unlock(&queue->lock);
  1288. if (rcv) {
  1289. struct sk_buff *nskb;
  1290. local_bh_disable();
  1291. while ((nskb = __skb_dequeue(&process_queue))) {
  1292. skb_record_rx_queue(nskb, tfile->queue_index);
  1293. netif_receive_skb(nskb);
  1294. }
  1295. skb_record_rx_queue(skb, tfile->queue_index);
  1296. netif_receive_skb(skb);
  1297. local_bh_enable();
  1298. }
  1299. }
  1300. static bool tun_can_build_skb(struct tun_struct *tun, struct tun_file *tfile,
  1301. int len, int noblock, bool zerocopy)
  1302. {
  1303. if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
  1304. return false;
  1305. if (tfile->socket.sk->sk_sndbuf != INT_MAX)
  1306. return false;
  1307. if (!noblock)
  1308. return false;
  1309. if (zerocopy)
  1310. return false;
  1311. if (SKB_DATA_ALIGN(len + TUN_RX_PAD) +
  1312. SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) > PAGE_SIZE)
  1313. return false;
  1314. return true;
  1315. }
  1316. static struct sk_buff *__tun_build_skb(struct page_frag *alloc_frag, char *buf,
  1317. int buflen, int len, int pad)
  1318. {
  1319. struct sk_buff *skb = build_skb(buf, buflen);
  1320. if (!skb)
  1321. return ERR_PTR(-ENOMEM);
  1322. skb_reserve(skb, pad);
  1323. skb_put(skb, len);
  1324. get_page(alloc_frag->page);
  1325. alloc_frag->offset += buflen;
  1326. return skb;
  1327. }
  1328. static int tun_xdp_act(struct tun_struct *tun, struct bpf_prog *xdp_prog,
  1329. struct xdp_buff *xdp, u32 act)
  1330. {
  1331. int err;
  1332. switch (act) {
  1333. case XDP_REDIRECT:
  1334. err = xdp_do_redirect(tun->dev, xdp, xdp_prog);
  1335. if (err)
  1336. return err;
  1337. break;
  1338. case XDP_TX:
  1339. err = tun_xdp_tx(tun->dev, xdp);
  1340. if (err < 0)
  1341. return err;
  1342. break;
  1343. case XDP_PASS:
  1344. break;
  1345. default:
  1346. bpf_warn_invalid_xdp_action(act);
  1347. /* fall through */
  1348. case XDP_ABORTED:
  1349. trace_xdp_exception(tun->dev, xdp_prog, act);
  1350. /* fall through */
  1351. case XDP_DROP:
  1352. this_cpu_inc(tun->pcpu_stats->rx_dropped);
  1353. break;
  1354. }
  1355. return act;
  1356. }
  1357. static struct sk_buff *tun_build_skb(struct tun_struct *tun,
  1358. struct tun_file *tfile,
  1359. struct iov_iter *from,
  1360. struct virtio_net_hdr *hdr,
  1361. int len, int *skb_xdp)
  1362. {
  1363. struct page_frag *alloc_frag = &current->task_frag;
  1364. struct bpf_prog *xdp_prog;
  1365. int buflen = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
  1366. char *buf;
  1367. size_t copied;
  1368. int pad = TUN_RX_PAD;
  1369. int err = 0;
  1370. rcu_read_lock();
  1371. xdp_prog = rcu_dereference(tun->xdp_prog);
  1372. if (xdp_prog)
  1373. pad += XDP_PACKET_HEADROOM;
  1374. buflen += SKB_DATA_ALIGN(len + pad);
  1375. rcu_read_unlock();
  1376. alloc_frag->offset = ALIGN((u64)alloc_frag->offset, SMP_CACHE_BYTES);
  1377. if (unlikely(!skb_page_frag_refill(buflen, alloc_frag, GFP_KERNEL)))
  1378. return ERR_PTR(-ENOMEM);
  1379. buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
  1380. copied = copy_page_from_iter(alloc_frag->page,
  1381. alloc_frag->offset + pad,
  1382. len, from);
  1383. if (copied != len)
  1384. return ERR_PTR(-EFAULT);
  1385. /* There's a small window that XDP may be set after the check
  1386. * of xdp_prog above, this should be rare and for simplicity
  1387. * we do XDP on skb in case the headroom is not enough.
  1388. */
  1389. if (hdr->gso_type || !xdp_prog) {
  1390. *skb_xdp = 1;
  1391. return __tun_build_skb(alloc_frag, buf, buflen, len, pad);
  1392. }
  1393. *skb_xdp = 0;
  1394. local_bh_disable();
  1395. rcu_read_lock();
  1396. xdp_prog = rcu_dereference(tun->xdp_prog);
  1397. if (xdp_prog) {
  1398. struct xdp_buff xdp;
  1399. u32 act;
  1400. xdp.data_hard_start = buf;
  1401. xdp.data = buf + pad;
  1402. xdp_set_data_meta_invalid(&xdp);
  1403. xdp.data_end = xdp.data + len;
  1404. xdp.rxq = &tfile->xdp_rxq;
  1405. act = bpf_prog_run_xdp(xdp_prog, &xdp);
  1406. if (act == XDP_REDIRECT || act == XDP_TX) {
  1407. get_page(alloc_frag->page);
  1408. alloc_frag->offset += buflen;
  1409. }
  1410. err = tun_xdp_act(tun, xdp_prog, &xdp, act);
  1411. if (err < 0)
  1412. goto err_xdp;
  1413. if (err == XDP_REDIRECT)
  1414. xdp_do_flush_map();
  1415. if (err != XDP_PASS)
  1416. goto out;
  1417. pad = xdp.data - xdp.data_hard_start;
  1418. len = xdp.data_end - xdp.data;
  1419. }
  1420. rcu_read_unlock();
  1421. local_bh_enable();
  1422. return __tun_build_skb(alloc_frag, buf, buflen, len, pad);
  1423. err_xdp:
  1424. put_page(alloc_frag->page);
  1425. out:
  1426. rcu_read_unlock();
  1427. local_bh_enable();
  1428. return NULL;
  1429. }
  1430. /* Get packet from user space buffer */
  1431. static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
  1432. void *msg_control, struct iov_iter *from,
  1433. int noblock, bool more)
  1434. {
  1435. struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
  1436. struct sk_buff *skb;
  1437. size_t total_len = iov_iter_count(from);
  1438. size_t len = total_len, align = tun->align, linear;
  1439. struct virtio_net_hdr gso = { 0 };
  1440. struct tun_pcpu_stats *stats;
  1441. int good_linear;
  1442. int copylen;
  1443. bool zerocopy = false;
  1444. int err;
  1445. u32 rxhash = 0;
  1446. int skb_xdp = 1;
  1447. bool frags = tun_napi_frags_enabled(tfile);
  1448. if (!(tun->dev->flags & IFF_UP))
  1449. return -EIO;
  1450. if (!(tun->flags & IFF_NO_PI)) {
  1451. if (len < sizeof(pi))
  1452. return -EINVAL;
  1453. len -= sizeof(pi);
  1454. if (!copy_from_iter_full(&pi, sizeof(pi), from))
  1455. return -EFAULT;
  1456. }
  1457. if (tun->flags & IFF_VNET_HDR) {
  1458. int vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
  1459. if (len < vnet_hdr_sz)
  1460. return -EINVAL;
  1461. len -= vnet_hdr_sz;
  1462. if (!copy_from_iter_full(&gso, sizeof(gso), from))
  1463. return -EFAULT;
  1464. if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
  1465. tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2 > tun16_to_cpu(tun, gso.hdr_len))
  1466. gso.hdr_len = cpu_to_tun16(tun, tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2);
  1467. if (tun16_to_cpu(tun, gso.hdr_len) > len)
  1468. return -EINVAL;
  1469. iov_iter_advance(from, vnet_hdr_sz - sizeof(gso));
  1470. }
  1471. if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP) {
  1472. align += NET_IP_ALIGN;
  1473. if (unlikely(len < ETH_HLEN ||
  1474. (gso.hdr_len && tun16_to_cpu(tun, gso.hdr_len) < ETH_HLEN)))
  1475. return -EINVAL;
  1476. }
  1477. good_linear = SKB_MAX_HEAD(align);
  1478. if (msg_control) {
  1479. struct iov_iter i = *from;
  1480. /* There are 256 bytes to be copied in skb, so there is
  1481. * enough room for skb expand head in case it is used.
  1482. * The rest of the buffer is mapped from userspace.
  1483. */
  1484. copylen = gso.hdr_len ? tun16_to_cpu(tun, gso.hdr_len) : GOODCOPY_LEN;
  1485. if (copylen > good_linear)
  1486. copylen = good_linear;
  1487. linear = copylen;
  1488. iov_iter_advance(&i, copylen);
  1489. if (iov_iter_npages(&i, INT_MAX) <= MAX_SKB_FRAGS)
  1490. zerocopy = true;
  1491. }
  1492. if (!frags && tun_can_build_skb(tun, tfile, len, noblock, zerocopy)) {
  1493. /* For the packet that is not easy to be processed
  1494. * (e.g gso or jumbo packet), we will do it at after
  1495. * skb was created with generic XDP routine.
  1496. */
  1497. skb = tun_build_skb(tun, tfile, from, &gso, len, &skb_xdp);
  1498. if (IS_ERR(skb)) {
  1499. this_cpu_inc(tun->pcpu_stats->rx_dropped);
  1500. return PTR_ERR(skb);
  1501. }
  1502. if (!skb)
  1503. return total_len;
  1504. } else {
  1505. if (!zerocopy) {
  1506. copylen = len;
  1507. if (tun16_to_cpu(tun, gso.hdr_len) > good_linear)
  1508. linear = good_linear;
  1509. else
  1510. linear = tun16_to_cpu(tun, gso.hdr_len);
  1511. }
  1512. if (frags) {
  1513. mutex_lock(&tfile->napi_mutex);
  1514. skb = tun_napi_alloc_frags(tfile, copylen, from);
  1515. /* tun_napi_alloc_frags() enforces a layout for the skb.
  1516. * If zerocopy is enabled, then this layout will be
  1517. * overwritten by zerocopy_sg_from_iter().
  1518. */
  1519. zerocopy = false;
  1520. } else {
  1521. skb = tun_alloc_skb(tfile, align, copylen, linear,
  1522. noblock);
  1523. }
  1524. if (IS_ERR(skb)) {
  1525. if (PTR_ERR(skb) != -EAGAIN)
  1526. this_cpu_inc(tun->pcpu_stats->rx_dropped);
  1527. if (frags)
  1528. mutex_unlock(&tfile->napi_mutex);
  1529. return PTR_ERR(skb);
  1530. }
  1531. if (zerocopy)
  1532. err = zerocopy_sg_from_iter(skb, from);
  1533. else
  1534. err = skb_copy_datagram_from_iter(skb, 0, from, len);
  1535. if (err) {
  1536. this_cpu_inc(tun->pcpu_stats->rx_dropped);
  1537. kfree_skb(skb);
  1538. if (frags) {
  1539. tfile->napi.skb = NULL;
  1540. mutex_unlock(&tfile->napi_mutex);
  1541. }
  1542. return -EFAULT;
  1543. }
  1544. }
  1545. if (virtio_net_hdr_to_skb(skb, &gso, tun_is_little_endian(tun))) {
  1546. this_cpu_inc(tun->pcpu_stats->rx_frame_errors);
  1547. kfree_skb(skb);
  1548. if (frags) {
  1549. tfile->napi.skb = NULL;
  1550. mutex_unlock(&tfile->napi_mutex);
  1551. }
  1552. return -EINVAL;
  1553. }
  1554. switch (tun->flags & TUN_TYPE_MASK) {
  1555. case IFF_TUN:
  1556. if (tun->flags & IFF_NO_PI) {
  1557. u8 ip_version = skb->len ? (skb->data[0] >> 4) : 0;
  1558. switch (ip_version) {
  1559. case 4:
  1560. pi.proto = htons(ETH_P_IP);
  1561. break;
  1562. case 6:
  1563. pi.proto = htons(ETH_P_IPV6);
  1564. break;
  1565. default:
  1566. this_cpu_inc(tun->pcpu_stats->rx_dropped);
  1567. kfree_skb(skb);
  1568. return -EINVAL;
  1569. }
  1570. }
  1571. skb_reset_mac_header(skb);
  1572. skb->protocol = pi.proto;
  1573. skb->dev = tun->dev;
  1574. break;
  1575. case IFF_TAP:
  1576. if (!frags)
  1577. skb->protocol = eth_type_trans(skb, tun->dev);
  1578. break;
  1579. }
  1580. /* copy skb_ubuf_info for callback when skb has no error */
  1581. if (zerocopy) {
  1582. skb_shinfo(skb)->destructor_arg = msg_control;
  1583. skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
  1584. skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
  1585. } else if (msg_control) {
  1586. struct ubuf_info *uarg = msg_control;
  1587. uarg->callback(uarg, false);
  1588. }
  1589. skb_reset_network_header(skb);
  1590. skb_probe_transport_header(skb, 0);
  1591. if (skb_xdp) {
  1592. struct bpf_prog *xdp_prog;
  1593. int ret;
  1594. local_bh_disable();
  1595. rcu_read_lock();
  1596. xdp_prog = rcu_dereference(tun->xdp_prog);
  1597. if (xdp_prog) {
  1598. ret = do_xdp_generic(xdp_prog, skb);
  1599. if (ret != XDP_PASS) {
  1600. rcu_read_unlock();
  1601. local_bh_enable();
  1602. return total_len;
  1603. }
  1604. }
  1605. rcu_read_unlock();
  1606. local_bh_enable();
  1607. }
  1608. /* Compute the costly rx hash only if needed for flow updates.
  1609. * We may get a very small possibility of OOO during switching, not
  1610. * worth to optimize.
  1611. */
  1612. if (!rcu_access_pointer(tun->steering_prog) && tun->numqueues > 1 &&
  1613. !tfile->detached)
  1614. rxhash = __skb_get_hash_symmetric(skb);
  1615. if (frags) {
  1616. /* Exercise flow dissector code path. */
  1617. u32 headlen = eth_get_headlen(skb->data, skb_headlen(skb));
  1618. if (unlikely(headlen > skb_headlen(skb))) {
  1619. this_cpu_inc(tun->pcpu_stats->rx_dropped);
  1620. napi_free_frags(&tfile->napi);
  1621. mutex_unlock(&tfile->napi_mutex);
  1622. WARN_ON(1);
  1623. return -ENOMEM;
  1624. }
  1625. local_bh_disable();
  1626. napi_gro_frags(&tfile->napi);
  1627. local_bh_enable();
  1628. mutex_unlock(&tfile->napi_mutex);
  1629. } else if (tfile->napi_enabled) {
  1630. struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
  1631. int queue_len;
  1632. spin_lock_bh(&queue->lock);
  1633. __skb_queue_tail(queue, skb);
  1634. queue_len = skb_queue_len(queue);
  1635. spin_unlock(&queue->lock);
  1636. if (!more || queue_len > NAPI_POLL_WEIGHT)
  1637. napi_schedule(&tfile->napi);
  1638. local_bh_enable();
  1639. } else if (!IS_ENABLED(CONFIG_4KSTACKS)) {
  1640. tun_rx_batched(tun, tfile, skb, more);
  1641. } else {
  1642. netif_rx_ni(skb);
  1643. }
  1644. stats = get_cpu_ptr(tun->pcpu_stats);
  1645. u64_stats_update_begin(&stats->syncp);
  1646. stats->rx_packets++;
  1647. stats->rx_bytes += len;
  1648. u64_stats_update_end(&stats->syncp);
  1649. put_cpu_ptr(stats);
  1650. if (rxhash)
  1651. tun_flow_update(tun, rxhash, tfile);
  1652. return total_len;
  1653. }
  1654. static ssize_t tun_chr_write_iter(struct kiocb *iocb, struct iov_iter *from)
  1655. {
  1656. struct file *file = iocb->ki_filp;
  1657. struct tun_file *tfile = file->private_data;
  1658. struct tun_struct *tun = tun_get(tfile);
  1659. ssize_t result;
  1660. if (!tun)
  1661. return -EBADFD;
  1662. result = tun_get_user(tun, tfile, NULL, from,
  1663. file->f_flags & O_NONBLOCK, false);
  1664. tun_put(tun);
  1665. return result;
  1666. }
  1667. static ssize_t tun_put_user_xdp(struct tun_struct *tun,
  1668. struct tun_file *tfile,
  1669. struct xdp_frame *xdp_frame,
  1670. struct iov_iter *iter)
  1671. {
  1672. int vnet_hdr_sz = 0;
  1673. size_t size = xdp_frame->len;
  1674. struct tun_pcpu_stats *stats;
  1675. size_t ret;
  1676. if (tun->flags & IFF_VNET_HDR) {
  1677. struct virtio_net_hdr gso = { 0 };
  1678. vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
  1679. if (unlikely(iov_iter_count(iter) < vnet_hdr_sz))
  1680. return -EINVAL;
  1681. if (unlikely(copy_to_iter(&gso, sizeof(gso), iter) !=
  1682. sizeof(gso)))
  1683. return -EFAULT;
  1684. iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
  1685. }
  1686. ret = copy_to_iter(xdp_frame->data, size, iter) + vnet_hdr_sz;
  1687. stats = get_cpu_ptr(tun->pcpu_stats);
  1688. u64_stats_update_begin(&stats->syncp);
  1689. stats->tx_packets++;
  1690. stats->tx_bytes += ret;
  1691. u64_stats_update_end(&stats->syncp);
  1692. put_cpu_ptr(tun->pcpu_stats);
  1693. return ret;
  1694. }
  1695. /* Put packet to the user space buffer */
  1696. static ssize_t tun_put_user(struct tun_struct *tun,
  1697. struct tun_file *tfile,
  1698. struct sk_buff *skb,
  1699. struct iov_iter *iter)
  1700. {
  1701. struct tun_pi pi = { 0, skb->protocol };
  1702. struct tun_pcpu_stats *stats;
  1703. ssize_t total;
  1704. int vlan_offset = 0;
  1705. int vlan_hlen = 0;
  1706. int vnet_hdr_sz = 0;
  1707. if (skb_vlan_tag_present(skb))
  1708. vlan_hlen = VLAN_HLEN;
  1709. if (tun->flags & IFF_VNET_HDR)
  1710. vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
  1711. total = skb->len + vlan_hlen + vnet_hdr_sz;
  1712. if (!(tun->flags & IFF_NO_PI)) {
  1713. if (iov_iter_count(iter) < sizeof(pi))
  1714. return -EINVAL;
  1715. total += sizeof(pi);
  1716. if (iov_iter_count(iter) < total) {
  1717. /* Packet will be striped */
  1718. pi.flags |= TUN_PKT_STRIP;
  1719. }
  1720. if (copy_to_iter(&pi, sizeof(pi), iter) != sizeof(pi))
  1721. return -EFAULT;
  1722. }
  1723. if (vnet_hdr_sz) {
  1724. struct virtio_net_hdr gso;
  1725. if (iov_iter_count(iter) < vnet_hdr_sz)
  1726. return -EINVAL;
  1727. if (virtio_net_hdr_from_skb(skb, &gso,
  1728. tun_is_little_endian(tun), true,
  1729. vlan_hlen)) {
  1730. struct skb_shared_info *sinfo = skb_shinfo(skb);
  1731. pr_err("unexpected GSO type: "
  1732. "0x%x, gso_size %d, hdr_len %d\n",
  1733. sinfo->gso_type, tun16_to_cpu(tun, gso.gso_size),
  1734. tun16_to_cpu(tun, gso.hdr_len));
  1735. print_hex_dump(KERN_ERR, "tun: ",
  1736. DUMP_PREFIX_NONE,
  1737. 16, 1, skb->head,
  1738. min((int)tun16_to_cpu(tun, gso.hdr_len), 64), true);
  1739. WARN_ON_ONCE(1);
  1740. return -EINVAL;
  1741. }
  1742. if (copy_to_iter(&gso, sizeof(gso), iter) != sizeof(gso))
  1743. return -EFAULT;
  1744. iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
  1745. }
  1746. if (vlan_hlen) {
  1747. int ret;
  1748. struct veth veth;
  1749. veth.h_vlan_proto = skb->vlan_proto;
  1750. veth.h_vlan_TCI = htons(skb_vlan_tag_get(skb));
  1751. vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
  1752. ret = skb_copy_datagram_iter(skb, 0, iter, vlan_offset);
  1753. if (ret || !iov_iter_count(iter))
  1754. goto done;
  1755. ret = copy_to_iter(&veth, sizeof(veth), iter);
  1756. if (ret != sizeof(veth) || !iov_iter_count(iter))
  1757. goto done;
  1758. }
  1759. skb_copy_datagram_iter(skb, vlan_offset, iter, skb->len - vlan_offset);
  1760. done:
  1761. /* caller is in process context, */
  1762. stats = get_cpu_ptr(tun->pcpu_stats);
  1763. u64_stats_update_begin(&stats->syncp);
  1764. stats->tx_packets++;
  1765. stats->tx_bytes += skb->len + vlan_hlen;
  1766. u64_stats_update_end(&stats->syncp);
  1767. put_cpu_ptr(tun->pcpu_stats);
  1768. return total;
  1769. }
  1770. static void *tun_ring_recv(struct tun_file *tfile, int noblock, int *err)
  1771. {
  1772. DECLARE_WAITQUEUE(wait, current);
  1773. void *ptr = NULL;
  1774. int error = 0;
  1775. ptr = ptr_ring_consume(&tfile->tx_ring);
  1776. if (ptr)
  1777. goto out;
  1778. if (noblock) {
  1779. error = -EAGAIN;
  1780. goto out;
  1781. }
  1782. add_wait_queue(&tfile->wq.wait, &wait);
  1783. current->state = TASK_INTERRUPTIBLE;
  1784. while (1) {
  1785. ptr = ptr_ring_consume(&tfile->tx_ring);
  1786. if (ptr)
  1787. break;
  1788. if (signal_pending(current)) {
  1789. error = -ERESTARTSYS;
  1790. break;
  1791. }
  1792. if (tfile->socket.sk->sk_shutdown & RCV_SHUTDOWN) {
  1793. error = -EFAULT;
  1794. break;
  1795. }
  1796. schedule();
  1797. }
  1798. current->state = TASK_RUNNING;
  1799. remove_wait_queue(&tfile->wq.wait, &wait);
  1800. out:
  1801. *err = error;
  1802. return ptr;
  1803. }
  1804. static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
  1805. struct iov_iter *to,
  1806. int noblock, void *ptr)
  1807. {
  1808. ssize_t ret;
  1809. int err;
  1810. tun_debug(KERN_INFO, tun, "tun_do_read\n");
  1811. if (!iov_iter_count(to)) {
  1812. tun_ptr_free(ptr);
  1813. return 0;
  1814. }
  1815. if (!ptr) {
  1816. /* Read frames from ring */
  1817. ptr = tun_ring_recv(tfile, noblock, &err);
  1818. if (!ptr)
  1819. return err;
  1820. }
  1821. if (tun_is_xdp_frame(ptr)) {
  1822. struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
  1823. ret = tun_put_user_xdp(tun, tfile, xdpf, to);
  1824. xdp_return_frame(xdpf);
  1825. } else {
  1826. struct sk_buff *skb = ptr;
  1827. ret = tun_put_user(tun, tfile, skb, to);
  1828. if (unlikely(ret < 0))
  1829. kfree_skb(skb);
  1830. else
  1831. consume_skb(skb);
  1832. }
  1833. return ret;
  1834. }
  1835. static ssize_t tun_chr_read_iter(struct kiocb *iocb, struct iov_iter *to)
  1836. {
  1837. struct file *file = iocb->ki_filp;
  1838. struct tun_file *tfile = file->private_data;
  1839. struct tun_struct *tun = tun_get(tfile);
  1840. ssize_t len = iov_iter_count(to), ret;
  1841. if (!tun)
  1842. return -EBADFD;
  1843. ret = tun_do_read(tun, tfile, to, file->f_flags & O_NONBLOCK, NULL);
  1844. ret = min_t(ssize_t, ret, len);
  1845. if (ret > 0)
  1846. iocb->ki_pos = ret;
  1847. tun_put(tun);
  1848. return ret;
  1849. }
  1850. static void tun_prog_free(struct rcu_head *rcu)
  1851. {
  1852. struct tun_prog *prog = container_of(rcu, struct tun_prog, rcu);
  1853. bpf_prog_destroy(prog->prog);
  1854. kfree(prog);
  1855. }
  1856. static int __tun_set_ebpf(struct tun_struct *tun,
  1857. struct tun_prog __rcu **prog_p,
  1858. struct bpf_prog *prog)
  1859. {
  1860. struct tun_prog *old, *new = NULL;
  1861. if (prog) {
  1862. new = kmalloc(sizeof(*new), GFP_KERNEL);
  1863. if (!new)
  1864. return -ENOMEM;
  1865. new->prog = prog;
  1866. }
  1867. spin_lock_bh(&tun->lock);
  1868. old = rcu_dereference_protected(*prog_p,
  1869. lockdep_is_held(&tun->lock));
  1870. rcu_assign_pointer(*prog_p, new);
  1871. spin_unlock_bh(&tun->lock);
  1872. if (old)
  1873. call_rcu(&old->rcu, tun_prog_free);
  1874. return 0;
  1875. }
  1876. static void tun_free_netdev(struct net_device *dev)
  1877. {
  1878. struct tun_struct *tun = netdev_priv(dev);
  1879. BUG_ON(!(list_empty(&tun->disabled)));
  1880. free_percpu(tun->pcpu_stats);
  1881. tun_flow_uninit(tun);
  1882. security_tun_dev_free_security(tun->security);
  1883. __tun_set_ebpf(tun, &tun->steering_prog, NULL);
  1884. __tun_set_ebpf(tun, &tun->filter_prog, NULL);
  1885. }
  1886. static void tun_setup(struct net_device *dev)
  1887. {
  1888. struct tun_struct *tun = netdev_priv(dev);
  1889. tun->owner = INVALID_UID;
  1890. tun->group = INVALID_GID;
  1891. tun_default_link_ksettings(dev, &tun->link_ksettings);
  1892. dev->ethtool_ops = &tun_ethtool_ops;
  1893. dev->needs_free_netdev = true;
  1894. dev->priv_destructor = tun_free_netdev;
  1895. /* We prefer our own queue length */
  1896. dev->tx_queue_len = TUN_READQ_SIZE;
  1897. }
  1898. /* Trivial set of netlink ops to allow deleting tun or tap
  1899. * device with netlink.
  1900. */
  1901. static int tun_validate(struct nlattr *tb[], struct nlattr *data[],
  1902. struct netlink_ext_ack *extack)
  1903. {
  1904. NL_SET_ERR_MSG(extack,
  1905. "tun/tap creation via rtnetlink is not supported.");
  1906. return -EOPNOTSUPP;
  1907. }
  1908. static size_t tun_get_size(const struct net_device *dev)
  1909. {
  1910. BUILD_BUG_ON(sizeof(u32) != sizeof(uid_t));
  1911. BUILD_BUG_ON(sizeof(u32) != sizeof(gid_t));
  1912. return nla_total_size(sizeof(uid_t)) + /* OWNER */
  1913. nla_total_size(sizeof(gid_t)) + /* GROUP */
  1914. nla_total_size(sizeof(u8)) + /* TYPE */
  1915. nla_total_size(sizeof(u8)) + /* PI */
  1916. nla_total_size(sizeof(u8)) + /* VNET_HDR */
  1917. nla_total_size(sizeof(u8)) + /* PERSIST */
  1918. nla_total_size(sizeof(u8)) + /* MULTI_QUEUE */
  1919. nla_total_size(sizeof(u32)) + /* NUM_QUEUES */
  1920. nla_total_size(sizeof(u32)) + /* NUM_DISABLED_QUEUES */
  1921. 0;
  1922. }
  1923. static int tun_fill_info(struct sk_buff *skb, const struct net_device *dev)
  1924. {
  1925. struct tun_struct *tun = netdev_priv(dev);
  1926. if (nla_put_u8(skb, IFLA_TUN_TYPE, tun->flags & TUN_TYPE_MASK))
  1927. goto nla_put_failure;
  1928. if (uid_valid(tun->owner) &&
  1929. nla_put_u32(skb, IFLA_TUN_OWNER,
  1930. from_kuid_munged(current_user_ns(), tun->owner)))
  1931. goto nla_put_failure;
  1932. if (gid_valid(tun->group) &&
  1933. nla_put_u32(skb, IFLA_TUN_GROUP,
  1934. from_kgid_munged(current_user_ns(), tun->group)))
  1935. goto nla_put_failure;
  1936. if (nla_put_u8(skb, IFLA_TUN_PI, !(tun->flags & IFF_NO_PI)))
  1937. goto nla_put_failure;
  1938. if (nla_put_u8(skb, IFLA_TUN_VNET_HDR, !!(tun->flags & IFF_VNET_HDR)))
  1939. goto nla_put_failure;
  1940. if (nla_put_u8(skb, IFLA_TUN_PERSIST, !!(tun->flags & IFF_PERSIST)))
  1941. goto nla_put_failure;
  1942. if (nla_put_u8(skb, IFLA_TUN_MULTI_QUEUE,
  1943. !!(tun->flags & IFF_MULTI_QUEUE)))
  1944. goto nla_put_failure;
  1945. if (tun->flags & IFF_MULTI_QUEUE) {
  1946. if (nla_put_u32(skb, IFLA_TUN_NUM_QUEUES, tun->numqueues))
  1947. goto nla_put_failure;
  1948. if (nla_put_u32(skb, IFLA_TUN_NUM_DISABLED_QUEUES,
  1949. tun->numdisabled))
  1950. goto nla_put_failure;
  1951. }
  1952. return 0;
  1953. nla_put_failure:
  1954. return -EMSGSIZE;
  1955. }
  1956. static struct rtnl_link_ops tun_link_ops __read_mostly = {
  1957. .kind = DRV_NAME,
  1958. .priv_size = sizeof(struct tun_struct),
  1959. .setup = tun_setup,
  1960. .validate = tun_validate,
  1961. .get_size = tun_get_size,
  1962. .fill_info = tun_fill_info,
  1963. };
  1964. static void tun_sock_write_space(struct sock *sk)
  1965. {
  1966. struct tun_file *tfile;
  1967. wait_queue_head_t *wqueue;
  1968. if (!sock_writeable(sk))
  1969. return;
  1970. if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags))
  1971. return;
  1972. wqueue = sk_sleep(sk);
  1973. if (wqueue && waitqueue_active(wqueue))
  1974. wake_up_interruptible_sync_poll(wqueue, EPOLLOUT |
  1975. EPOLLWRNORM | EPOLLWRBAND);
  1976. tfile = container_of(sk, struct tun_file, sk);
  1977. kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
  1978. }
  1979. static int tun_xdp_one(struct tun_struct *tun,
  1980. struct tun_file *tfile,
  1981. struct xdp_buff *xdp, int *flush)
  1982. {
  1983. unsigned int datasize = xdp->data_end - xdp->data;
  1984. struct tun_xdp_hdr *hdr = xdp->data_hard_start;
  1985. struct virtio_net_hdr *gso = &hdr->gso;
  1986. struct tun_pcpu_stats *stats;
  1987. struct bpf_prog *xdp_prog;
  1988. struct sk_buff *skb = NULL;
  1989. u32 rxhash = 0, act;
  1990. int buflen = hdr->buflen;
  1991. int err = 0;
  1992. bool skb_xdp = false;
  1993. xdp_prog = rcu_dereference(tun->xdp_prog);
  1994. if (xdp_prog) {
  1995. if (gso->gso_type) {
  1996. skb_xdp = true;
  1997. goto build;
  1998. }
  1999. xdp_set_data_meta_invalid(xdp);
  2000. xdp->rxq = &tfile->xdp_rxq;
  2001. act = bpf_prog_run_xdp(xdp_prog, xdp);
  2002. err = tun_xdp_act(tun, xdp_prog, xdp, act);
  2003. if (err < 0) {
  2004. put_page(virt_to_head_page(xdp->data));
  2005. return err;
  2006. }
  2007. switch (err) {
  2008. case XDP_REDIRECT:
  2009. *flush = true;
  2010. /* fall through */
  2011. case XDP_TX:
  2012. return 0;
  2013. case XDP_PASS:
  2014. break;
  2015. default:
  2016. put_page(virt_to_head_page(xdp->data));
  2017. return 0;
  2018. }
  2019. }
  2020. build:
  2021. skb = build_skb(xdp->data_hard_start, buflen);
  2022. if (!skb) {
  2023. err = -ENOMEM;
  2024. goto out;
  2025. }
  2026. skb_reserve(skb, xdp->data - xdp->data_hard_start);
  2027. skb_put(skb, xdp->data_end - xdp->data);
  2028. if (virtio_net_hdr_to_skb(skb, gso, tun_is_little_endian(tun))) {
  2029. this_cpu_inc(tun->pcpu_stats->rx_frame_errors);
  2030. kfree_skb(skb);
  2031. err = -EINVAL;
  2032. goto out;
  2033. }
  2034. skb->protocol = eth_type_trans(skb, tun->dev);
  2035. skb_reset_network_header(skb);
  2036. skb_probe_transport_header(skb, 0);
  2037. if (skb_xdp) {
  2038. err = do_xdp_generic(xdp_prog, skb);
  2039. if (err != XDP_PASS)
  2040. goto out;
  2041. }
  2042. if (!rcu_dereference(tun->steering_prog))
  2043. rxhash = __skb_get_hash_symmetric(skb);
  2044. skb_record_rx_queue(skb, tfile->queue_index);
  2045. netif_receive_skb(skb);
  2046. stats = get_cpu_ptr(tun->pcpu_stats);
  2047. u64_stats_update_begin(&stats->syncp);
  2048. stats->rx_packets++;
  2049. stats->rx_bytes += datasize;
  2050. u64_stats_update_end(&stats->syncp);
  2051. put_cpu_ptr(stats);
  2052. if (rxhash)
  2053. tun_flow_update(tun, rxhash, tfile);
  2054. out:
  2055. return err;
  2056. }
  2057. static int tun_sendmsg(struct socket *sock, struct msghdr *m, size_t total_len)
  2058. {
  2059. int ret, i;
  2060. struct tun_file *tfile = container_of(sock, struct tun_file, socket);
  2061. struct tun_struct *tun = tun_get(tfile);
  2062. struct tun_msg_ctl *ctl = m->msg_control;
  2063. struct xdp_buff *xdp;
  2064. if (!tun)
  2065. return -EBADFD;
  2066. if (ctl && (ctl->type == TUN_MSG_PTR)) {
  2067. int n = ctl->num;
  2068. int flush = 0;
  2069. local_bh_disable();
  2070. rcu_read_lock();
  2071. for (i = 0; i < n; i++) {
  2072. xdp = &((struct xdp_buff *)ctl->ptr)[i];
  2073. tun_xdp_one(tun, tfile, xdp, &flush);
  2074. }
  2075. if (flush)
  2076. xdp_do_flush_map();
  2077. rcu_read_unlock();
  2078. local_bh_enable();
  2079. ret = total_len;
  2080. goto out;
  2081. }
  2082. ret = tun_get_user(tun, tfile, ctl ? ctl->ptr : NULL, &m->msg_iter,
  2083. m->msg_flags & MSG_DONTWAIT,
  2084. m->msg_flags & MSG_MORE);
  2085. out:
  2086. tun_put(tun);
  2087. return ret;
  2088. }
  2089. static int tun_recvmsg(struct socket *sock, struct msghdr *m, size_t total_len,
  2090. int flags)
  2091. {
  2092. struct tun_file *tfile = container_of(sock, struct tun_file, socket);
  2093. struct tun_struct *tun = tun_get(tfile);
  2094. void *ptr = m->msg_control;
  2095. int ret;
  2096. if (!tun) {
  2097. ret = -EBADFD;
  2098. goto out_free;
  2099. }
  2100. if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) {
  2101. ret = -EINVAL;
  2102. goto out_put_tun;
  2103. }
  2104. if (flags & MSG_ERRQUEUE) {
  2105. ret = sock_recv_errqueue(sock->sk, m, total_len,
  2106. SOL_PACKET, TUN_TX_TIMESTAMP);
  2107. goto out;
  2108. }
  2109. ret = tun_do_read(tun, tfile, &m->msg_iter, flags & MSG_DONTWAIT, ptr);
  2110. if (ret > (ssize_t)total_len) {
  2111. m->msg_flags |= MSG_TRUNC;
  2112. ret = flags & MSG_TRUNC ? ret : total_len;
  2113. }
  2114. out:
  2115. tun_put(tun);
  2116. return ret;
  2117. out_put_tun:
  2118. tun_put(tun);
  2119. out_free:
  2120. tun_ptr_free(ptr);
  2121. return ret;
  2122. }
  2123. static int tun_ptr_peek_len(void *ptr)
  2124. {
  2125. if (likely(ptr)) {
  2126. if (tun_is_xdp_frame(ptr)) {
  2127. struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
  2128. return xdpf->len;
  2129. }
  2130. return __skb_array_len_with_tag(ptr);
  2131. } else {
  2132. return 0;
  2133. }
  2134. }
  2135. static int tun_peek_len(struct socket *sock)
  2136. {
  2137. struct tun_file *tfile = container_of(sock, struct tun_file, socket);
  2138. struct tun_struct *tun;
  2139. int ret = 0;
  2140. tun = tun_get(tfile);
  2141. if (!tun)
  2142. return 0;
  2143. ret = PTR_RING_PEEK_CALL(&tfile->tx_ring, tun_ptr_peek_len);
  2144. tun_put(tun);
  2145. return ret;
  2146. }
  2147. /* Ops structure to mimic raw sockets with tun */
  2148. static const struct proto_ops tun_socket_ops = {
  2149. .peek_len = tun_peek_len,
  2150. .sendmsg = tun_sendmsg,
  2151. .recvmsg = tun_recvmsg,
  2152. };
  2153. static struct proto tun_proto = {
  2154. .name = "tun",
  2155. .owner = THIS_MODULE,
  2156. .obj_size = sizeof(struct tun_file),
  2157. };
  2158. static int tun_flags(struct tun_struct *tun)
  2159. {
  2160. return tun->flags & (TUN_FEATURES | IFF_PERSIST | IFF_TUN | IFF_TAP);
  2161. }
  2162. static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
  2163. char *buf)
  2164. {
  2165. struct tun_struct *tun = netdev_priv(to_net_dev(dev));
  2166. return sprintf(buf, "0x%x\n", tun_flags(tun));
  2167. }
  2168. static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
  2169. char *buf)
  2170. {
  2171. struct tun_struct *tun = netdev_priv(to_net_dev(dev));
  2172. return uid_valid(tun->owner)?
  2173. sprintf(buf, "%u\n",
  2174. from_kuid_munged(current_user_ns(), tun->owner)):
  2175. sprintf(buf, "-1\n");
  2176. }
  2177. static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
  2178. char *buf)
  2179. {
  2180. struct tun_struct *tun = netdev_priv(to_net_dev(dev));
  2181. return gid_valid(tun->group) ?
  2182. sprintf(buf, "%u\n",
  2183. from_kgid_munged(current_user_ns(), tun->group)):
  2184. sprintf(buf, "-1\n");
  2185. }
  2186. static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
  2187. static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
  2188. static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
  2189. static struct attribute *tun_dev_attrs[] = {
  2190. &dev_attr_tun_flags.attr,
  2191. &dev_attr_owner.attr,
  2192. &dev_attr_group.attr,
  2193. NULL
  2194. };
  2195. static const struct attribute_group tun_attr_group = {
  2196. .attrs = tun_dev_attrs
  2197. };
  2198. static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
  2199. {
  2200. struct tun_struct *tun;
  2201. struct tun_file *tfile = file->private_data;
  2202. struct net_device *dev;
  2203. int err;
  2204. if (tfile->detached)
  2205. return -EINVAL;
  2206. if ((ifr->ifr_flags & IFF_NAPI_FRAGS)) {
  2207. if (!capable(CAP_NET_ADMIN))
  2208. return -EPERM;
  2209. if (!(ifr->ifr_flags & IFF_NAPI) ||
  2210. (ifr->ifr_flags & TUN_TYPE_MASK) != IFF_TAP)
  2211. return -EINVAL;
  2212. }
  2213. dev = __dev_get_by_name(net, ifr->ifr_name);
  2214. if (dev) {
  2215. if (ifr->ifr_flags & IFF_TUN_EXCL)
  2216. return -EBUSY;
  2217. if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
  2218. tun = netdev_priv(dev);
  2219. else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
  2220. tun = netdev_priv(dev);
  2221. else
  2222. return -EINVAL;
  2223. if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
  2224. !!(tun->flags & IFF_MULTI_QUEUE))
  2225. return -EINVAL;
  2226. if (tun_not_capable(tun))
  2227. return -EPERM;
  2228. err = security_tun_dev_open(tun->security);
  2229. if (err < 0)
  2230. return err;
  2231. err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER,
  2232. ifr->ifr_flags & IFF_NAPI,
  2233. ifr->ifr_flags & IFF_NAPI_FRAGS);
  2234. if (err < 0)
  2235. return err;
  2236. if (tun->flags & IFF_MULTI_QUEUE &&
  2237. (tun->numqueues + tun->numdisabled > 1)) {
  2238. /* One or more queue has already been attached, no need
  2239. * to initialize the device again.
  2240. */
  2241. netdev_state_change(dev);
  2242. return 0;
  2243. }
  2244. tun->flags = (tun->flags & ~TUN_FEATURES) |
  2245. (ifr->ifr_flags & TUN_FEATURES);
  2246. netdev_state_change(dev);
  2247. } else {
  2248. char *name;
  2249. unsigned long flags = 0;
  2250. int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
  2251. MAX_TAP_QUEUES : 1;
  2252. if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
  2253. return -EPERM;
  2254. err = security_tun_dev_create();
  2255. if (err < 0)
  2256. return err;
  2257. /* Set dev type */
  2258. if (ifr->ifr_flags & IFF_TUN) {
  2259. /* TUN device */
  2260. flags |= IFF_TUN;
  2261. name = "tun%d";
  2262. } else if (ifr->ifr_flags & IFF_TAP) {
  2263. /* TAP device */
  2264. flags |= IFF_TAP;
  2265. name = "tap%d";
  2266. } else
  2267. return -EINVAL;
  2268. if (*ifr->ifr_name)
  2269. name = ifr->ifr_name;
  2270. dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
  2271. NET_NAME_UNKNOWN, tun_setup, queues,
  2272. queues);
  2273. if (!dev)
  2274. return -ENOMEM;
  2275. err = dev_get_valid_name(net, dev, name);
  2276. if (err < 0)
  2277. goto err_free_dev;
  2278. dev_net_set(dev, net);
  2279. dev->rtnl_link_ops = &tun_link_ops;
  2280. dev->ifindex = tfile->ifindex;
  2281. dev->sysfs_groups[0] = &tun_attr_group;
  2282. tun = netdev_priv(dev);
  2283. tun->dev = dev;
  2284. tun->flags = flags;
  2285. tun->txflt.count = 0;
  2286. tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
  2287. tun->align = NET_SKB_PAD;
  2288. tun->filter_attached = false;
  2289. tun->sndbuf = tfile->socket.sk->sk_sndbuf;
  2290. tun->rx_batched = 0;
  2291. RCU_INIT_POINTER(tun->steering_prog, NULL);
  2292. tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats);
  2293. if (!tun->pcpu_stats) {
  2294. err = -ENOMEM;
  2295. goto err_free_dev;
  2296. }
  2297. spin_lock_init(&tun->lock);
  2298. err = security_tun_dev_alloc_security(&tun->security);
  2299. if (err < 0)
  2300. goto err_free_stat;
  2301. tun_net_init(dev);
  2302. tun_flow_init(tun);
  2303. dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
  2304. TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
  2305. NETIF_F_HW_VLAN_STAG_TX;
  2306. dev->features = dev->hw_features | NETIF_F_LLTX;
  2307. dev->vlan_features = dev->features &
  2308. ~(NETIF_F_HW_VLAN_CTAG_TX |
  2309. NETIF_F_HW_VLAN_STAG_TX);
  2310. tun->flags = (tun->flags & ~TUN_FEATURES) |
  2311. (ifr->ifr_flags & TUN_FEATURES);
  2312. INIT_LIST_HEAD(&tun->disabled);
  2313. err = tun_attach(tun, file, false, ifr->ifr_flags & IFF_NAPI,
  2314. ifr->ifr_flags & IFF_NAPI_FRAGS);
  2315. if (err < 0)
  2316. goto err_free_flow;
  2317. err = register_netdevice(tun->dev);
  2318. if (err < 0)
  2319. goto err_detach;
  2320. }
  2321. netif_carrier_on(tun->dev);
  2322. tun_debug(KERN_INFO, tun, "tun_set_iff\n");
  2323. /* Make sure persistent devices do not get stuck in
  2324. * xoff state.
  2325. */
  2326. if (netif_running(tun->dev))
  2327. netif_tx_wake_all_queues(tun->dev);
  2328. strcpy(ifr->ifr_name, tun->dev->name);
  2329. return 0;
  2330. err_detach:
  2331. tun_detach_all(dev);
  2332. /* register_netdevice() already called tun_free_netdev() */
  2333. goto err_free_dev;
  2334. err_free_flow:
  2335. tun_flow_uninit(tun);
  2336. security_tun_dev_free_security(tun->security);
  2337. err_free_stat:
  2338. free_percpu(tun->pcpu_stats);
  2339. err_free_dev:
  2340. free_netdev(dev);
  2341. return err;
  2342. }
  2343. static void tun_get_iff(struct net *net, struct tun_struct *tun,
  2344. struct ifreq *ifr)
  2345. {
  2346. tun_debug(KERN_INFO, tun, "tun_get_iff\n");
  2347. strcpy(ifr->ifr_name, tun->dev->name);
  2348. ifr->ifr_flags = tun_flags(tun);
  2349. }
  2350. /* This is like a cut-down ethtool ops, except done via tun fd so no
  2351. * privs required. */
  2352. static int set_offload(struct tun_struct *tun, unsigned long arg)
  2353. {
  2354. netdev_features_t features = 0;
  2355. if (arg & TUN_F_CSUM) {
  2356. features |= NETIF_F_HW_CSUM;
  2357. arg &= ~TUN_F_CSUM;
  2358. if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
  2359. if (arg & TUN_F_TSO_ECN) {
  2360. features |= NETIF_F_TSO_ECN;
  2361. arg &= ~TUN_F_TSO_ECN;
  2362. }
  2363. if (arg & TUN_F_TSO4)
  2364. features |= NETIF_F_TSO;
  2365. if (arg & TUN_F_TSO6)
  2366. features |= NETIF_F_TSO6;
  2367. arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
  2368. }
  2369. arg &= ~TUN_F_UFO;
  2370. }
  2371. /* This gives the user a way to test for new features in future by
  2372. * trying to set them. */
  2373. if (arg)
  2374. return -EINVAL;
  2375. tun->set_features = features;
  2376. tun->dev->wanted_features &= ~TUN_USER_FEATURES;
  2377. tun->dev->wanted_features |= features;
  2378. netdev_update_features(tun->dev);
  2379. return 0;
  2380. }
  2381. static void tun_detach_filter(struct tun_struct *tun, int n)
  2382. {
  2383. int i;
  2384. struct tun_file *tfile;
  2385. for (i = 0; i < n; i++) {
  2386. tfile = rtnl_dereference(tun->tfiles[i]);
  2387. lock_sock(tfile->socket.sk);
  2388. sk_detach_filter(tfile->socket.sk);
  2389. release_sock(tfile->socket.sk);
  2390. }
  2391. tun->filter_attached = false;
  2392. }
  2393. static int tun_attach_filter(struct tun_struct *tun)
  2394. {
  2395. int i, ret = 0;
  2396. struct tun_file *tfile;
  2397. for (i = 0; i < tun->numqueues; i++) {
  2398. tfile = rtnl_dereference(tun->tfiles[i]);
  2399. lock_sock(tfile->socket.sk);
  2400. ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
  2401. release_sock(tfile->socket.sk);
  2402. if (ret) {
  2403. tun_detach_filter(tun, i);
  2404. return ret;
  2405. }
  2406. }
  2407. tun->filter_attached = true;
  2408. return ret;
  2409. }
  2410. static void tun_set_sndbuf(struct tun_struct *tun)
  2411. {
  2412. struct tun_file *tfile;
  2413. int i;
  2414. for (i = 0; i < tun->numqueues; i++) {
  2415. tfile = rtnl_dereference(tun->tfiles[i]);
  2416. tfile->socket.sk->sk_sndbuf = tun->sndbuf;
  2417. }
  2418. }
  2419. static int tun_set_queue(struct file *file, struct ifreq *ifr)
  2420. {
  2421. struct tun_file *tfile = file->private_data;
  2422. struct tun_struct *tun;
  2423. int ret = 0;
  2424. rtnl_lock();
  2425. if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
  2426. tun = tfile->detached;
  2427. if (!tun) {
  2428. ret = -EINVAL;
  2429. goto unlock;
  2430. }
  2431. ret = security_tun_dev_attach_queue(tun->security);
  2432. if (ret < 0)
  2433. goto unlock;
  2434. ret = tun_attach(tun, file, false, tun->flags & IFF_NAPI,
  2435. tun->flags & IFF_NAPI_FRAGS);
  2436. } else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
  2437. tun = rtnl_dereference(tfile->tun);
  2438. if (!tun || !(tun->flags & IFF_MULTI_QUEUE) || tfile->detached)
  2439. ret = -EINVAL;
  2440. else
  2441. __tun_detach(tfile, false);
  2442. } else
  2443. ret = -EINVAL;
  2444. if (ret >= 0)
  2445. netdev_state_change(tun->dev);
  2446. unlock:
  2447. rtnl_unlock();
  2448. return ret;
  2449. }
  2450. static int tun_set_ebpf(struct tun_struct *tun, struct tun_prog **prog_p,
  2451. void __user *data)
  2452. {
  2453. struct bpf_prog *prog;
  2454. int fd;
  2455. if (copy_from_user(&fd, data, sizeof(fd)))
  2456. return -EFAULT;
  2457. if (fd == -1) {
  2458. prog = NULL;
  2459. } else {
  2460. prog = bpf_prog_get_type(fd, BPF_PROG_TYPE_SOCKET_FILTER);
  2461. if (IS_ERR(prog))
  2462. return PTR_ERR(prog);
  2463. }
  2464. return __tun_set_ebpf(tun, prog_p, prog);
  2465. }
  2466. static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
  2467. unsigned long arg, int ifreq_len)
  2468. {
  2469. struct tun_file *tfile = file->private_data;
  2470. struct net *net = sock_net(&tfile->sk);
  2471. struct tun_struct *tun;
  2472. void __user* argp = (void __user*)arg;
  2473. struct ifreq ifr;
  2474. kuid_t owner;
  2475. kgid_t group;
  2476. int sndbuf;
  2477. int vnet_hdr_sz;
  2478. unsigned int ifindex;
  2479. int le;
  2480. int ret;
  2481. bool do_notify = false;
  2482. if (cmd == TUNSETIFF || cmd == TUNSETQUEUE ||
  2483. (_IOC_TYPE(cmd) == SOCK_IOC_TYPE && cmd != SIOCGSKNS)) {
  2484. if (copy_from_user(&ifr, argp, ifreq_len))
  2485. return -EFAULT;
  2486. } else {
  2487. memset(&ifr, 0, sizeof(ifr));
  2488. }
  2489. if (cmd == TUNGETFEATURES) {
  2490. /* Currently this just means: "what IFF flags are valid?".
  2491. * This is needed because we never checked for invalid flags on
  2492. * TUNSETIFF.
  2493. */
  2494. return put_user(IFF_TUN | IFF_TAP | TUN_FEATURES,
  2495. (unsigned int __user*)argp);
  2496. } else if (cmd == TUNSETQUEUE) {
  2497. return tun_set_queue(file, &ifr);
  2498. } else if (cmd == SIOCGSKNS) {
  2499. if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
  2500. return -EPERM;
  2501. return open_related_ns(&net->ns, get_net_ns);
  2502. }
  2503. ret = 0;
  2504. rtnl_lock();
  2505. tun = tun_get(tfile);
  2506. if (cmd == TUNSETIFF) {
  2507. ret = -EEXIST;
  2508. if (tun)
  2509. goto unlock;
  2510. ifr.ifr_name[IFNAMSIZ-1] = '\0';
  2511. ret = tun_set_iff(net, file, &ifr);
  2512. if (ret)
  2513. goto unlock;
  2514. if (copy_to_user(argp, &ifr, ifreq_len))
  2515. ret = -EFAULT;
  2516. goto unlock;
  2517. }
  2518. if (cmd == TUNSETIFINDEX) {
  2519. ret = -EPERM;
  2520. if (tun)
  2521. goto unlock;
  2522. ret = -EFAULT;
  2523. if (copy_from_user(&ifindex, argp, sizeof(ifindex)))
  2524. goto unlock;
  2525. ret = 0;
  2526. tfile->ifindex = ifindex;
  2527. goto unlock;
  2528. }
  2529. ret = -EBADFD;
  2530. if (!tun)
  2531. goto unlock;
  2532. tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
  2533. ret = 0;
  2534. switch (cmd) {
  2535. case TUNGETIFF:
  2536. tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
  2537. if (tfile->detached)
  2538. ifr.ifr_flags |= IFF_DETACH_QUEUE;
  2539. if (!tfile->socket.sk->sk_filter)
  2540. ifr.ifr_flags |= IFF_NOFILTER;
  2541. if (copy_to_user(argp, &ifr, ifreq_len))
  2542. ret = -EFAULT;
  2543. break;
  2544. case TUNSETNOCSUM:
  2545. /* Disable/Enable checksum */
  2546. /* [unimplemented] */
  2547. tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
  2548. arg ? "disabled" : "enabled");
  2549. break;
  2550. case TUNSETPERSIST:
  2551. /* Disable/Enable persist mode. Keep an extra reference to the
  2552. * module to prevent the module being unprobed.
  2553. */
  2554. if (arg && !(tun->flags & IFF_PERSIST)) {
  2555. tun->flags |= IFF_PERSIST;
  2556. __module_get(THIS_MODULE);
  2557. do_notify = true;
  2558. }
  2559. if (!arg && (tun->flags & IFF_PERSIST)) {
  2560. tun->flags &= ~IFF_PERSIST;
  2561. module_put(THIS_MODULE);
  2562. do_notify = true;
  2563. }
  2564. tun_debug(KERN_INFO, tun, "persist %s\n",
  2565. arg ? "enabled" : "disabled");
  2566. break;
  2567. case TUNSETOWNER:
  2568. /* Set owner of the device */
  2569. owner = make_kuid(current_user_ns(), arg);
  2570. if (!uid_valid(owner)) {
  2571. ret = -EINVAL;
  2572. break;
  2573. }
  2574. tun->owner = owner;
  2575. do_notify = true;
  2576. tun_debug(KERN_INFO, tun, "owner set to %u\n",
  2577. from_kuid(&init_user_ns, tun->owner));
  2578. break;
  2579. case TUNSETGROUP:
  2580. /* Set group of the device */
  2581. group = make_kgid(current_user_ns(), arg);
  2582. if (!gid_valid(group)) {
  2583. ret = -EINVAL;
  2584. break;
  2585. }
  2586. tun->group = group;
  2587. do_notify = true;
  2588. tun_debug(KERN_INFO, tun, "group set to %u\n",
  2589. from_kgid(&init_user_ns, tun->group));
  2590. break;
  2591. case TUNSETLINK:
  2592. /* Only allow setting the type when the interface is down */
  2593. if (tun->dev->flags & IFF_UP) {
  2594. tun_debug(KERN_INFO, tun,
  2595. "Linktype set failed because interface is up\n");
  2596. ret = -EBUSY;
  2597. } else {
  2598. tun->dev->type = (int) arg;
  2599. tun_debug(KERN_INFO, tun, "linktype set to %d\n",
  2600. tun->dev->type);
  2601. ret = 0;
  2602. }
  2603. break;
  2604. #ifdef TUN_DEBUG
  2605. case TUNSETDEBUG:
  2606. tun->debug = arg;
  2607. break;
  2608. #endif
  2609. case TUNSETOFFLOAD:
  2610. ret = set_offload(tun, arg);
  2611. break;
  2612. case TUNSETTXFILTER:
  2613. /* Can be set only for TAPs */
  2614. ret = -EINVAL;
  2615. if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
  2616. break;
  2617. ret = update_filter(&tun->txflt, (void __user *)arg);
  2618. break;
  2619. case SIOCGIFHWADDR:
  2620. /* Get hw address */
  2621. memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
  2622. ifr.ifr_hwaddr.sa_family = tun->dev->type;
  2623. if (copy_to_user(argp, &ifr, ifreq_len))
  2624. ret = -EFAULT;
  2625. break;
  2626. case SIOCSIFHWADDR:
  2627. /* Set hw address */
  2628. tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
  2629. ifr.ifr_hwaddr.sa_data);
  2630. ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
  2631. break;
  2632. case TUNGETSNDBUF:
  2633. sndbuf = tfile->socket.sk->sk_sndbuf;
  2634. if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
  2635. ret = -EFAULT;
  2636. break;
  2637. case TUNSETSNDBUF:
  2638. if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
  2639. ret = -EFAULT;
  2640. break;
  2641. }
  2642. if (sndbuf <= 0) {
  2643. ret = -EINVAL;
  2644. break;
  2645. }
  2646. tun->sndbuf = sndbuf;
  2647. tun_set_sndbuf(tun);
  2648. break;
  2649. case TUNGETVNETHDRSZ:
  2650. vnet_hdr_sz = tun->vnet_hdr_sz;
  2651. if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
  2652. ret = -EFAULT;
  2653. break;
  2654. case TUNSETVNETHDRSZ:
  2655. if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
  2656. ret = -EFAULT;
  2657. break;
  2658. }
  2659. if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
  2660. ret = -EINVAL;
  2661. break;
  2662. }
  2663. tun->vnet_hdr_sz = vnet_hdr_sz;
  2664. break;
  2665. case TUNGETVNETLE:
  2666. le = !!(tun->flags & TUN_VNET_LE);
  2667. if (put_user(le, (int __user *)argp))
  2668. ret = -EFAULT;
  2669. break;
  2670. case TUNSETVNETLE:
  2671. if (get_user(le, (int __user *)argp)) {
  2672. ret = -EFAULT;
  2673. break;
  2674. }
  2675. if (le)
  2676. tun->flags |= TUN_VNET_LE;
  2677. else
  2678. tun->flags &= ~TUN_VNET_LE;
  2679. break;
  2680. case TUNGETVNETBE:
  2681. ret = tun_get_vnet_be(tun, argp);
  2682. break;
  2683. case TUNSETVNETBE:
  2684. ret = tun_set_vnet_be(tun, argp);
  2685. break;
  2686. case TUNATTACHFILTER:
  2687. /* Can be set only for TAPs */
  2688. ret = -EINVAL;
  2689. if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
  2690. break;
  2691. ret = -EFAULT;
  2692. if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
  2693. break;
  2694. ret = tun_attach_filter(tun);
  2695. break;
  2696. case TUNDETACHFILTER:
  2697. /* Can be set only for TAPs */
  2698. ret = -EINVAL;
  2699. if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
  2700. break;
  2701. ret = 0;
  2702. tun_detach_filter(tun, tun->numqueues);
  2703. break;
  2704. case TUNGETFILTER:
  2705. ret = -EINVAL;
  2706. if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
  2707. break;
  2708. ret = -EFAULT;
  2709. if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog)))
  2710. break;
  2711. ret = 0;
  2712. break;
  2713. case TUNSETSTEERINGEBPF:
  2714. ret = tun_set_ebpf(tun, &tun->steering_prog, argp);
  2715. break;
  2716. case TUNSETFILTEREBPF:
  2717. ret = tun_set_ebpf(tun, &tun->filter_prog, argp);
  2718. break;
  2719. default:
  2720. ret = -EINVAL;
  2721. break;
  2722. }
  2723. if (do_notify)
  2724. netdev_state_change(tun->dev);
  2725. unlock:
  2726. rtnl_unlock();
  2727. if (tun)
  2728. tun_put(tun);
  2729. return ret;
  2730. }
  2731. static long tun_chr_ioctl(struct file *file,
  2732. unsigned int cmd, unsigned long arg)
  2733. {
  2734. return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
  2735. }
  2736. #ifdef CONFIG_COMPAT
  2737. static long tun_chr_compat_ioctl(struct file *file,
  2738. unsigned int cmd, unsigned long arg)
  2739. {
  2740. switch (cmd) {
  2741. case TUNSETIFF:
  2742. case TUNGETIFF:
  2743. case TUNSETTXFILTER:
  2744. case TUNGETSNDBUF:
  2745. case TUNSETSNDBUF:
  2746. case SIOCGIFHWADDR:
  2747. case SIOCSIFHWADDR:
  2748. arg = (unsigned long)compat_ptr(arg);
  2749. break;
  2750. default:
  2751. arg = (compat_ulong_t)arg;
  2752. break;
  2753. }
  2754. /*
  2755. * compat_ifreq is shorter than ifreq, so we must not access beyond
  2756. * the end of that structure. All fields that are used in this
  2757. * driver are compatible though, we don't need to convert the
  2758. * contents.
  2759. */
  2760. return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
  2761. }
  2762. #endif /* CONFIG_COMPAT */
  2763. static int tun_chr_fasync(int fd, struct file *file, int on)
  2764. {
  2765. struct tun_file *tfile = file->private_data;
  2766. int ret;
  2767. if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
  2768. goto out;
  2769. if (on) {
  2770. __f_setown(file, task_pid(current), PIDTYPE_TGID, 0);
  2771. tfile->flags |= TUN_FASYNC;
  2772. } else
  2773. tfile->flags &= ~TUN_FASYNC;
  2774. ret = 0;
  2775. out:
  2776. return ret;
  2777. }
  2778. static int tun_chr_open(struct inode *inode, struct file * file)
  2779. {
  2780. struct net *net = current->nsproxy->net_ns;
  2781. struct tun_file *tfile;
  2782. DBG1(KERN_INFO, "tunX: tun_chr_open\n");
  2783. tfile = (struct tun_file *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
  2784. &tun_proto, 0);
  2785. if (!tfile)
  2786. return -ENOMEM;
  2787. if (ptr_ring_init(&tfile->tx_ring, 0, GFP_KERNEL)) {
  2788. sk_free(&tfile->sk);
  2789. return -ENOMEM;
  2790. }
  2791. mutex_init(&tfile->napi_mutex);
  2792. RCU_INIT_POINTER(tfile->tun, NULL);
  2793. tfile->flags = 0;
  2794. tfile->ifindex = 0;
  2795. init_waitqueue_head(&tfile->wq.wait);
  2796. RCU_INIT_POINTER(tfile->socket.wq, &tfile->wq);
  2797. tfile->socket.file = file;
  2798. tfile->socket.ops = &tun_socket_ops;
  2799. sock_init_data(&tfile->socket, &tfile->sk);
  2800. tfile->sk.sk_write_space = tun_sock_write_space;
  2801. tfile->sk.sk_sndbuf = INT_MAX;
  2802. file->private_data = tfile;
  2803. INIT_LIST_HEAD(&tfile->next);
  2804. sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
  2805. return 0;
  2806. }
  2807. static int tun_chr_close(struct inode *inode, struct file *file)
  2808. {
  2809. struct tun_file *tfile = file->private_data;
  2810. tun_detach(tfile, true);
  2811. return 0;
  2812. }
  2813. #ifdef CONFIG_PROC_FS
  2814. static void tun_chr_show_fdinfo(struct seq_file *m, struct file *file)
  2815. {
  2816. struct tun_file *tfile = file->private_data;
  2817. struct tun_struct *tun;
  2818. struct ifreq ifr;
  2819. memset(&ifr, 0, sizeof(ifr));
  2820. rtnl_lock();
  2821. tun = tun_get(tfile);
  2822. if (tun)
  2823. tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
  2824. rtnl_unlock();
  2825. if (tun)
  2826. tun_put(tun);
  2827. seq_printf(m, "iff:\t%s\n", ifr.ifr_name);
  2828. }
  2829. #endif
  2830. static const struct file_operations tun_fops = {
  2831. .owner = THIS_MODULE,
  2832. .llseek = no_llseek,
  2833. .read_iter = tun_chr_read_iter,
  2834. .write_iter = tun_chr_write_iter,
  2835. .poll = tun_chr_poll,
  2836. .unlocked_ioctl = tun_chr_ioctl,
  2837. #ifdef CONFIG_COMPAT
  2838. .compat_ioctl = tun_chr_compat_ioctl,
  2839. #endif
  2840. .open = tun_chr_open,
  2841. .release = tun_chr_close,
  2842. .fasync = tun_chr_fasync,
  2843. #ifdef CONFIG_PROC_FS
  2844. .show_fdinfo = tun_chr_show_fdinfo,
  2845. #endif
  2846. };
  2847. static struct miscdevice tun_miscdev = {
  2848. .minor = TUN_MINOR,
  2849. .name = "tun",
  2850. .nodename = "net/tun",
  2851. .fops = &tun_fops,
  2852. };
  2853. /* ethtool interface */
  2854. static void tun_default_link_ksettings(struct net_device *dev,
  2855. struct ethtool_link_ksettings *cmd)
  2856. {
  2857. ethtool_link_ksettings_zero_link_mode(cmd, supported);
  2858. ethtool_link_ksettings_zero_link_mode(cmd, advertising);
  2859. cmd->base.speed = SPEED_10;
  2860. cmd->base.duplex = DUPLEX_FULL;
  2861. cmd->base.port = PORT_TP;
  2862. cmd->base.phy_address = 0;
  2863. cmd->base.autoneg = AUTONEG_DISABLE;
  2864. }
  2865. static int tun_get_link_ksettings(struct net_device *dev,
  2866. struct ethtool_link_ksettings *cmd)
  2867. {
  2868. struct tun_struct *tun = netdev_priv(dev);
  2869. memcpy(cmd, &tun->link_ksettings, sizeof(*cmd));
  2870. return 0;
  2871. }
  2872. static int tun_set_link_ksettings(struct net_device *dev,
  2873. const struct ethtool_link_ksettings *cmd)
  2874. {
  2875. struct tun_struct *tun = netdev_priv(dev);
  2876. memcpy(&tun->link_ksettings, cmd, sizeof(*cmd));
  2877. return 0;
  2878. }
  2879. static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
  2880. {
  2881. struct tun_struct *tun = netdev_priv(dev);
  2882. strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
  2883. strlcpy(info->version, DRV_VERSION, sizeof(info->version));
  2884. switch (tun->flags & TUN_TYPE_MASK) {
  2885. case IFF_TUN:
  2886. strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
  2887. break;
  2888. case IFF_TAP:
  2889. strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
  2890. break;
  2891. }
  2892. }
  2893. static u32 tun_get_msglevel(struct net_device *dev)
  2894. {
  2895. #ifdef TUN_DEBUG
  2896. struct tun_struct *tun = netdev_priv(dev);
  2897. return tun->debug;
  2898. #else
  2899. return -EOPNOTSUPP;
  2900. #endif
  2901. }
  2902. static void tun_set_msglevel(struct net_device *dev, u32 value)
  2903. {
  2904. #ifdef TUN_DEBUG
  2905. struct tun_struct *tun = netdev_priv(dev);
  2906. tun->debug = value;
  2907. #endif
  2908. }
  2909. static int tun_get_coalesce(struct net_device *dev,
  2910. struct ethtool_coalesce *ec)
  2911. {
  2912. struct tun_struct *tun = netdev_priv(dev);
  2913. ec->rx_max_coalesced_frames = tun->rx_batched;
  2914. return 0;
  2915. }
  2916. static int tun_set_coalesce(struct net_device *dev,
  2917. struct ethtool_coalesce *ec)
  2918. {
  2919. struct tun_struct *tun = netdev_priv(dev);
  2920. if (ec->rx_max_coalesced_frames > NAPI_POLL_WEIGHT)
  2921. tun->rx_batched = NAPI_POLL_WEIGHT;
  2922. else
  2923. tun->rx_batched = ec->rx_max_coalesced_frames;
  2924. return 0;
  2925. }
  2926. static const struct ethtool_ops tun_ethtool_ops = {
  2927. .get_drvinfo = tun_get_drvinfo,
  2928. .get_msglevel = tun_get_msglevel,
  2929. .set_msglevel = tun_set_msglevel,
  2930. .get_link = ethtool_op_get_link,
  2931. .get_ts_info = ethtool_op_get_ts_info,
  2932. .get_coalesce = tun_get_coalesce,
  2933. .set_coalesce = tun_set_coalesce,
  2934. .get_link_ksettings = tun_get_link_ksettings,
  2935. .set_link_ksettings = tun_set_link_ksettings,
  2936. };
  2937. static int tun_queue_resize(struct tun_struct *tun)
  2938. {
  2939. struct net_device *dev = tun->dev;
  2940. struct tun_file *tfile;
  2941. struct ptr_ring **rings;
  2942. int n = tun->numqueues + tun->numdisabled;
  2943. int ret, i;
  2944. rings = kmalloc_array(n, sizeof(*rings), GFP_KERNEL);
  2945. if (!rings)
  2946. return -ENOMEM;
  2947. for (i = 0; i < tun->numqueues; i++) {
  2948. tfile = rtnl_dereference(tun->tfiles[i]);
  2949. rings[i] = &tfile->tx_ring;
  2950. }
  2951. list_for_each_entry(tfile, &tun->disabled, next)
  2952. rings[i++] = &tfile->tx_ring;
  2953. ret = ptr_ring_resize_multiple(rings, n,
  2954. dev->tx_queue_len, GFP_KERNEL,
  2955. tun_ptr_free);
  2956. kfree(rings);
  2957. return ret;
  2958. }
  2959. static int tun_device_event(struct notifier_block *unused,
  2960. unsigned long event, void *ptr)
  2961. {
  2962. struct net_device *dev = netdev_notifier_info_to_dev(ptr);
  2963. struct tun_struct *tun = netdev_priv(dev);
  2964. if (dev->rtnl_link_ops != &tun_link_ops)
  2965. return NOTIFY_DONE;
  2966. switch (event) {
  2967. case NETDEV_CHANGE_TX_QUEUE_LEN:
  2968. if (tun_queue_resize(tun))
  2969. return NOTIFY_BAD;
  2970. break;
  2971. default:
  2972. break;
  2973. }
  2974. return NOTIFY_DONE;
  2975. }
  2976. static struct notifier_block tun_notifier_block __read_mostly = {
  2977. .notifier_call = tun_device_event,
  2978. };
  2979. static int __init tun_init(void)
  2980. {
  2981. int ret = 0;
  2982. pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
  2983. ret = rtnl_link_register(&tun_link_ops);
  2984. if (ret) {
  2985. pr_err("Can't register link_ops\n");
  2986. goto err_linkops;
  2987. }
  2988. ret = misc_register(&tun_miscdev);
  2989. if (ret) {
  2990. pr_err("Can't register misc device %d\n", TUN_MINOR);
  2991. goto err_misc;
  2992. }
  2993. ret = register_netdevice_notifier(&tun_notifier_block);
  2994. if (ret) {
  2995. pr_err("Can't register netdevice notifier\n");
  2996. goto err_notifier;
  2997. }
  2998. return 0;
  2999. err_notifier:
  3000. misc_deregister(&tun_miscdev);
  3001. err_misc:
  3002. rtnl_link_unregister(&tun_link_ops);
  3003. err_linkops:
  3004. return ret;
  3005. }
  3006. static void tun_cleanup(void)
  3007. {
  3008. misc_deregister(&tun_miscdev);
  3009. rtnl_link_unregister(&tun_link_ops);
  3010. unregister_netdevice_notifier(&tun_notifier_block);
  3011. }
  3012. /* Get an underlying socket object from tun file. Returns error unless file is
  3013. * attached to a device. The returned object works like a packet socket, it
  3014. * can be used for sock_sendmsg/sock_recvmsg. The caller is responsible for
  3015. * holding a reference to the file for as long as the socket is in use. */
  3016. struct socket *tun_get_socket(struct file *file)
  3017. {
  3018. struct tun_file *tfile;
  3019. if (file->f_op != &tun_fops)
  3020. return ERR_PTR(-EINVAL);
  3021. tfile = file->private_data;
  3022. if (!tfile)
  3023. return ERR_PTR(-EBADFD);
  3024. return &tfile->socket;
  3025. }
  3026. EXPORT_SYMBOL_GPL(tun_get_socket);
  3027. struct ptr_ring *tun_get_tx_ring(struct file *file)
  3028. {
  3029. struct tun_file *tfile;
  3030. if (file->f_op != &tun_fops)
  3031. return ERR_PTR(-EINVAL);
  3032. tfile = file->private_data;
  3033. if (!tfile)
  3034. return ERR_PTR(-EBADFD);
  3035. return &tfile->tx_ring;
  3036. }
  3037. EXPORT_SYMBOL_GPL(tun_get_tx_ring);
  3038. module_init(tun_init);
  3039. module_exit(tun_cleanup);
  3040. MODULE_DESCRIPTION(DRV_DESCRIPTION);
  3041. MODULE_AUTHOR(DRV_COPYRIGHT);
  3042. MODULE_LICENSE("GPL");
  3043. MODULE_ALIAS_MISCDEV(TUN_MINOR);
  3044. MODULE_ALIAS("devname:net/tun");