tun.c 81 KB

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