tun.c 82 KB

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