tun.c 81 KB

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