tun.c 72 KB

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