tun.c 82 KB

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