tun.c 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107
  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(unsigned long data)
  384. {
  385. struct tun_struct *tun = (struct tun_struct *)data;
  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 = ACCESS_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 = ACCESS_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. setup_timer(&tun->flow_gc_timer, tun_flow_cleanup, (unsigned long)tun);
  1007. }
  1008. static void tun_flow_uninit(struct tun_struct *tun)
  1009. {
  1010. del_timer_sync(&tun->flow_gc_timer);
  1011. tun_flow_flush(tun);
  1012. }
  1013. #define MIN_MTU 68
  1014. #define MAX_MTU 65535
  1015. /* Initialize net device. */
  1016. static void tun_net_init(struct net_device *dev)
  1017. {
  1018. struct tun_struct *tun = netdev_priv(dev);
  1019. switch (tun->flags & TUN_TYPE_MASK) {
  1020. case IFF_TUN:
  1021. dev->netdev_ops = &tun_netdev_ops;
  1022. /* Point-to-Point TUN Device */
  1023. dev->hard_header_len = 0;
  1024. dev->addr_len = 0;
  1025. dev->mtu = 1500;
  1026. /* Zero header length */
  1027. dev->type = ARPHRD_NONE;
  1028. dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
  1029. break;
  1030. case IFF_TAP:
  1031. dev->netdev_ops = &tap_netdev_ops;
  1032. /* Ethernet TAP Device */
  1033. ether_setup(dev);
  1034. dev->priv_flags &= ~IFF_TX_SKB_SHARING;
  1035. dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
  1036. eth_hw_addr_random(dev);
  1037. break;
  1038. }
  1039. dev->min_mtu = MIN_MTU;
  1040. dev->max_mtu = MAX_MTU - dev->hard_header_len;
  1041. }
  1042. /* Character device part */
  1043. /* Poll */
  1044. static unsigned int tun_chr_poll(struct file *file, poll_table *wait)
  1045. {
  1046. struct tun_file *tfile = file->private_data;
  1047. struct tun_struct *tun = tun_get(tfile);
  1048. struct sock *sk;
  1049. unsigned int mask = 0;
  1050. if (!tun)
  1051. return POLLERR;
  1052. sk = tfile->socket.sk;
  1053. tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
  1054. poll_wait(file, sk_sleep(sk), wait);
  1055. if (!skb_array_empty(&tfile->tx_array))
  1056. mask |= POLLIN | POLLRDNORM;
  1057. if (tun->dev->flags & IFF_UP &&
  1058. (sock_writeable(sk) ||
  1059. (!test_and_set_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
  1060. sock_writeable(sk))))
  1061. mask |= POLLOUT | POLLWRNORM;
  1062. if (tun->dev->reg_state != NETREG_REGISTERED)
  1063. mask = POLLERR;
  1064. tun_put(tun);
  1065. return mask;
  1066. }
  1067. static struct sk_buff *tun_napi_alloc_frags(struct tun_file *tfile,
  1068. size_t len,
  1069. const struct iov_iter *it)
  1070. {
  1071. struct sk_buff *skb;
  1072. size_t linear;
  1073. int err;
  1074. int i;
  1075. if (it->nr_segs > MAX_SKB_FRAGS + 1)
  1076. return ERR_PTR(-ENOMEM);
  1077. local_bh_disable();
  1078. skb = napi_get_frags(&tfile->napi);
  1079. local_bh_enable();
  1080. if (!skb)
  1081. return ERR_PTR(-ENOMEM);
  1082. linear = iov_iter_single_seg_count(it);
  1083. err = __skb_grow(skb, linear);
  1084. if (err)
  1085. goto free;
  1086. skb->len = len;
  1087. skb->data_len = len - linear;
  1088. skb->truesize += skb->data_len;
  1089. for (i = 1; i < it->nr_segs; i++) {
  1090. size_t fragsz = it->iov[i].iov_len;
  1091. unsigned long offset;
  1092. struct page *page;
  1093. void *data;
  1094. if (fragsz == 0 || fragsz > PAGE_SIZE) {
  1095. err = -EINVAL;
  1096. goto free;
  1097. }
  1098. local_bh_disable();
  1099. data = napi_alloc_frag(fragsz);
  1100. local_bh_enable();
  1101. if (!data) {
  1102. err = -ENOMEM;
  1103. goto free;
  1104. }
  1105. page = virt_to_head_page(data);
  1106. offset = data - page_address(page);
  1107. skb_fill_page_desc(skb, i - 1, page, offset, fragsz);
  1108. }
  1109. return skb;
  1110. free:
  1111. /* frees skb and all frags allocated with napi_alloc_frag() */
  1112. napi_free_frags(&tfile->napi);
  1113. return ERR_PTR(err);
  1114. }
  1115. /* prepad is the amount to reserve at front. len is length after that.
  1116. * linear is a hint as to how much to copy (usually headers). */
  1117. static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
  1118. size_t prepad, size_t len,
  1119. size_t linear, int noblock)
  1120. {
  1121. struct sock *sk = tfile->socket.sk;
  1122. struct sk_buff *skb;
  1123. int err;
  1124. /* Under a page? Don't bother with paged skb. */
  1125. if (prepad + len < PAGE_SIZE || !linear)
  1126. linear = len;
  1127. skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
  1128. &err, 0);
  1129. if (!skb)
  1130. return ERR_PTR(err);
  1131. skb_reserve(skb, prepad);
  1132. skb_put(skb, linear);
  1133. skb->data_len = len - linear;
  1134. skb->len += len - linear;
  1135. return skb;
  1136. }
  1137. static void tun_rx_batched(struct tun_struct *tun, struct tun_file *tfile,
  1138. struct sk_buff *skb, int more)
  1139. {
  1140. struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
  1141. struct sk_buff_head process_queue;
  1142. u32 rx_batched = tun->rx_batched;
  1143. bool rcv = false;
  1144. if (!rx_batched || (!more && skb_queue_empty(queue))) {
  1145. local_bh_disable();
  1146. netif_receive_skb(skb);
  1147. local_bh_enable();
  1148. return;
  1149. }
  1150. spin_lock(&queue->lock);
  1151. if (!more || skb_queue_len(queue) == rx_batched) {
  1152. __skb_queue_head_init(&process_queue);
  1153. skb_queue_splice_tail_init(queue, &process_queue);
  1154. rcv = true;
  1155. } else {
  1156. __skb_queue_tail(queue, skb);
  1157. }
  1158. spin_unlock(&queue->lock);
  1159. if (rcv) {
  1160. struct sk_buff *nskb;
  1161. local_bh_disable();
  1162. while ((nskb = __skb_dequeue(&process_queue)))
  1163. netif_receive_skb(nskb);
  1164. netif_receive_skb(skb);
  1165. local_bh_enable();
  1166. }
  1167. }
  1168. static bool tun_can_build_skb(struct tun_struct *tun, struct tun_file *tfile,
  1169. int len, int noblock, bool zerocopy)
  1170. {
  1171. if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
  1172. return false;
  1173. if (tfile->socket.sk->sk_sndbuf != INT_MAX)
  1174. return false;
  1175. if (!noblock)
  1176. return false;
  1177. if (zerocopy)
  1178. return false;
  1179. if (SKB_DATA_ALIGN(len + TUN_RX_PAD) +
  1180. SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) > PAGE_SIZE)
  1181. return false;
  1182. return true;
  1183. }
  1184. static struct sk_buff *tun_build_skb(struct tun_struct *tun,
  1185. struct tun_file *tfile,
  1186. struct iov_iter *from,
  1187. struct virtio_net_hdr *hdr,
  1188. int len, int *skb_xdp)
  1189. {
  1190. struct page_frag *alloc_frag = &current->task_frag;
  1191. struct sk_buff *skb;
  1192. struct bpf_prog *xdp_prog;
  1193. int buflen = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
  1194. unsigned int delta = 0;
  1195. char *buf;
  1196. size_t copied;
  1197. bool xdp_xmit = false;
  1198. int err, pad = TUN_RX_PAD;
  1199. rcu_read_lock();
  1200. xdp_prog = rcu_dereference(tun->xdp_prog);
  1201. if (xdp_prog)
  1202. pad += TUN_HEADROOM;
  1203. buflen += SKB_DATA_ALIGN(len + pad);
  1204. rcu_read_unlock();
  1205. alloc_frag->offset = ALIGN((u64)alloc_frag->offset, SMP_CACHE_BYTES);
  1206. if (unlikely(!skb_page_frag_refill(buflen, alloc_frag, GFP_KERNEL)))
  1207. return ERR_PTR(-ENOMEM);
  1208. buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
  1209. copied = copy_page_from_iter(alloc_frag->page,
  1210. alloc_frag->offset + pad,
  1211. len, from);
  1212. if (copied != len)
  1213. return ERR_PTR(-EFAULT);
  1214. /* There's a small window that XDP may be set after the check
  1215. * of xdp_prog above, this should be rare and for simplicity
  1216. * we do XDP on skb in case the headroom is not enough.
  1217. */
  1218. if (hdr->gso_type || !xdp_prog)
  1219. *skb_xdp = 1;
  1220. else
  1221. *skb_xdp = 0;
  1222. rcu_read_lock();
  1223. xdp_prog = rcu_dereference(tun->xdp_prog);
  1224. if (xdp_prog && !*skb_xdp) {
  1225. struct xdp_buff xdp;
  1226. void *orig_data;
  1227. u32 act;
  1228. xdp.data_hard_start = buf;
  1229. xdp.data = buf + pad;
  1230. xdp_set_data_meta_invalid(&xdp);
  1231. xdp.data_end = xdp.data + len;
  1232. orig_data = xdp.data;
  1233. act = bpf_prog_run_xdp(xdp_prog, &xdp);
  1234. switch (act) {
  1235. case XDP_REDIRECT:
  1236. get_page(alloc_frag->page);
  1237. alloc_frag->offset += buflen;
  1238. err = xdp_do_redirect(tun->dev, &xdp, xdp_prog);
  1239. if (err)
  1240. goto err_redirect;
  1241. return NULL;
  1242. case XDP_TX:
  1243. xdp_xmit = true;
  1244. /* fall through */
  1245. case XDP_PASS:
  1246. delta = orig_data - xdp.data;
  1247. break;
  1248. default:
  1249. bpf_warn_invalid_xdp_action(act);
  1250. /* fall through */
  1251. case XDP_ABORTED:
  1252. trace_xdp_exception(tun->dev, xdp_prog, act);
  1253. /* fall through */
  1254. case XDP_DROP:
  1255. goto err_xdp;
  1256. }
  1257. }
  1258. skb = build_skb(buf, buflen);
  1259. if (!skb) {
  1260. rcu_read_unlock();
  1261. return ERR_PTR(-ENOMEM);
  1262. }
  1263. skb_reserve(skb, pad - delta);
  1264. skb_put(skb, len + delta);
  1265. get_page(alloc_frag->page);
  1266. alloc_frag->offset += buflen;
  1267. if (xdp_xmit) {
  1268. skb->dev = tun->dev;
  1269. generic_xdp_tx(skb, xdp_prog);
  1270. rcu_read_lock();
  1271. return NULL;
  1272. }
  1273. rcu_read_unlock();
  1274. return skb;
  1275. err_redirect:
  1276. put_page(alloc_frag->page);
  1277. err_xdp:
  1278. rcu_read_unlock();
  1279. this_cpu_inc(tun->pcpu_stats->rx_dropped);
  1280. return NULL;
  1281. }
  1282. /* Get packet from user space buffer */
  1283. static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
  1284. void *msg_control, struct iov_iter *from,
  1285. int noblock, bool more)
  1286. {
  1287. struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
  1288. struct sk_buff *skb;
  1289. size_t total_len = iov_iter_count(from);
  1290. size_t len = total_len, align = tun->align, linear;
  1291. struct virtio_net_hdr gso = { 0 };
  1292. struct tun_pcpu_stats *stats;
  1293. int good_linear;
  1294. int copylen;
  1295. bool zerocopy = false;
  1296. int err;
  1297. u32 rxhash;
  1298. int skb_xdp = 1;
  1299. bool frags = tun_napi_frags_enabled(tun);
  1300. if (!(tun->dev->flags & IFF_UP))
  1301. return -EIO;
  1302. if (!(tun->flags & IFF_NO_PI)) {
  1303. if (len < sizeof(pi))
  1304. return -EINVAL;
  1305. len -= sizeof(pi);
  1306. if (!copy_from_iter_full(&pi, sizeof(pi), from))
  1307. return -EFAULT;
  1308. }
  1309. if (tun->flags & IFF_VNET_HDR) {
  1310. int vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
  1311. if (len < vnet_hdr_sz)
  1312. return -EINVAL;
  1313. len -= vnet_hdr_sz;
  1314. if (!copy_from_iter_full(&gso, sizeof(gso), from))
  1315. return -EFAULT;
  1316. if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
  1317. tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2 > tun16_to_cpu(tun, gso.hdr_len))
  1318. gso.hdr_len = cpu_to_tun16(tun, tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2);
  1319. if (tun16_to_cpu(tun, gso.hdr_len) > len)
  1320. return -EINVAL;
  1321. iov_iter_advance(from, vnet_hdr_sz - sizeof(gso));
  1322. }
  1323. if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP) {
  1324. align += NET_IP_ALIGN;
  1325. if (unlikely(len < ETH_HLEN ||
  1326. (gso.hdr_len && tun16_to_cpu(tun, gso.hdr_len) < ETH_HLEN)))
  1327. return -EINVAL;
  1328. }
  1329. good_linear = SKB_MAX_HEAD(align);
  1330. if (msg_control) {
  1331. struct iov_iter i = *from;
  1332. /* There are 256 bytes to be copied in skb, so there is
  1333. * enough room for skb expand head in case it is used.
  1334. * The rest of the buffer is mapped from userspace.
  1335. */
  1336. copylen = gso.hdr_len ? tun16_to_cpu(tun, gso.hdr_len) : GOODCOPY_LEN;
  1337. if (copylen > good_linear)
  1338. copylen = good_linear;
  1339. linear = copylen;
  1340. iov_iter_advance(&i, copylen);
  1341. if (iov_iter_npages(&i, INT_MAX) <= MAX_SKB_FRAGS)
  1342. zerocopy = true;
  1343. }
  1344. if (!frags && tun_can_build_skb(tun, tfile, len, noblock, zerocopy)) {
  1345. /* For the packet that is not easy to be processed
  1346. * (e.g gso or jumbo packet), we will do it at after
  1347. * skb was created with generic XDP routine.
  1348. */
  1349. skb = tun_build_skb(tun, tfile, from, &gso, len, &skb_xdp);
  1350. if (IS_ERR(skb)) {
  1351. this_cpu_inc(tun->pcpu_stats->rx_dropped);
  1352. return PTR_ERR(skb);
  1353. }
  1354. if (!skb)
  1355. return total_len;
  1356. } else {
  1357. if (!zerocopy) {
  1358. copylen = len;
  1359. if (tun16_to_cpu(tun, gso.hdr_len) > good_linear)
  1360. linear = good_linear;
  1361. else
  1362. linear = tun16_to_cpu(tun, gso.hdr_len);
  1363. }
  1364. if (frags) {
  1365. mutex_lock(&tfile->napi_mutex);
  1366. skb = tun_napi_alloc_frags(tfile, copylen, from);
  1367. /* tun_napi_alloc_frags() enforces a layout for the skb.
  1368. * If zerocopy is enabled, then this layout will be
  1369. * overwritten by zerocopy_sg_from_iter().
  1370. */
  1371. zerocopy = false;
  1372. } else {
  1373. skb = tun_alloc_skb(tfile, align, copylen, linear,
  1374. noblock);
  1375. }
  1376. if (IS_ERR(skb)) {
  1377. if (PTR_ERR(skb) != -EAGAIN)
  1378. this_cpu_inc(tun->pcpu_stats->rx_dropped);
  1379. if (frags)
  1380. mutex_unlock(&tfile->napi_mutex);
  1381. return PTR_ERR(skb);
  1382. }
  1383. if (zerocopy)
  1384. err = zerocopy_sg_from_iter(skb, from);
  1385. else
  1386. err = skb_copy_datagram_from_iter(skb, 0, from, len);
  1387. if (err) {
  1388. this_cpu_inc(tun->pcpu_stats->rx_dropped);
  1389. kfree_skb(skb);
  1390. if (frags) {
  1391. tfile->napi.skb = NULL;
  1392. mutex_unlock(&tfile->napi_mutex);
  1393. }
  1394. return -EFAULT;
  1395. }
  1396. }
  1397. if (virtio_net_hdr_to_skb(skb, &gso, tun_is_little_endian(tun))) {
  1398. this_cpu_inc(tun->pcpu_stats->rx_frame_errors);
  1399. kfree_skb(skb);
  1400. if (frags) {
  1401. tfile->napi.skb = NULL;
  1402. mutex_unlock(&tfile->napi_mutex);
  1403. }
  1404. return -EINVAL;
  1405. }
  1406. switch (tun->flags & TUN_TYPE_MASK) {
  1407. case IFF_TUN:
  1408. if (tun->flags & IFF_NO_PI) {
  1409. u8 ip_version = skb->len ? (skb->data[0] >> 4) : 0;
  1410. switch (ip_version) {
  1411. case 4:
  1412. pi.proto = htons(ETH_P_IP);
  1413. break;
  1414. case 6:
  1415. pi.proto = htons(ETH_P_IPV6);
  1416. break;
  1417. default:
  1418. this_cpu_inc(tun->pcpu_stats->rx_dropped);
  1419. kfree_skb(skb);
  1420. return -EINVAL;
  1421. }
  1422. }
  1423. skb_reset_mac_header(skb);
  1424. skb->protocol = pi.proto;
  1425. skb->dev = tun->dev;
  1426. break;
  1427. case IFF_TAP:
  1428. if (!frags)
  1429. skb->protocol = eth_type_trans(skb, tun->dev);
  1430. break;
  1431. }
  1432. /* copy skb_ubuf_info for callback when skb has no error */
  1433. if (zerocopy) {
  1434. skb_shinfo(skb)->destructor_arg = msg_control;
  1435. skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
  1436. skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
  1437. } else if (msg_control) {
  1438. struct ubuf_info *uarg = msg_control;
  1439. uarg->callback(uarg, false);
  1440. }
  1441. skb_reset_network_header(skb);
  1442. skb_probe_transport_header(skb, 0);
  1443. if (skb_xdp) {
  1444. struct bpf_prog *xdp_prog;
  1445. int ret;
  1446. rcu_read_lock();
  1447. xdp_prog = rcu_dereference(tun->xdp_prog);
  1448. if (xdp_prog) {
  1449. ret = do_xdp_generic(xdp_prog, skb);
  1450. if (ret != XDP_PASS) {
  1451. rcu_read_unlock();
  1452. return total_len;
  1453. }
  1454. }
  1455. rcu_read_unlock();
  1456. }
  1457. rxhash = __skb_get_hash_symmetric(skb);
  1458. if (frags) {
  1459. /* Exercise flow dissector code path. */
  1460. u32 headlen = eth_get_headlen(skb->data, skb_headlen(skb));
  1461. if (unlikely(headlen > skb_headlen(skb))) {
  1462. this_cpu_inc(tun->pcpu_stats->rx_dropped);
  1463. napi_free_frags(&tfile->napi);
  1464. mutex_unlock(&tfile->napi_mutex);
  1465. WARN_ON(1);
  1466. return -ENOMEM;
  1467. }
  1468. local_bh_disable();
  1469. napi_gro_frags(&tfile->napi);
  1470. local_bh_enable();
  1471. mutex_unlock(&tfile->napi_mutex);
  1472. } else if (tfile->napi_enabled) {
  1473. struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
  1474. int queue_len;
  1475. spin_lock_bh(&queue->lock);
  1476. __skb_queue_tail(queue, skb);
  1477. queue_len = skb_queue_len(queue);
  1478. spin_unlock(&queue->lock);
  1479. if (!more || queue_len > NAPI_POLL_WEIGHT)
  1480. napi_schedule(&tfile->napi);
  1481. local_bh_enable();
  1482. } else if (!IS_ENABLED(CONFIG_4KSTACKS)) {
  1483. tun_rx_batched(tun, tfile, skb, more);
  1484. } else {
  1485. netif_rx_ni(skb);
  1486. }
  1487. stats = get_cpu_ptr(tun->pcpu_stats);
  1488. u64_stats_update_begin(&stats->syncp);
  1489. stats->rx_packets++;
  1490. stats->rx_bytes += len;
  1491. u64_stats_update_end(&stats->syncp);
  1492. put_cpu_ptr(stats);
  1493. tun_flow_update(tun, rxhash, tfile);
  1494. return total_len;
  1495. }
  1496. static ssize_t tun_chr_write_iter(struct kiocb *iocb, struct iov_iter *from)
  1497. {
  1498. struct file *file = iocb->ki_filp;
  1499. struct tun_file *tfile = file->private_data;
  1500. struct tun_struct *tun = tun_get(tfile);
  1501. ssize_t result;
  1502. if (!tun)
  1503. return -EBADFD;
  1504. result = tun_get_user(tun, tfile, NULL, from,
  1505. file->f_flags & O_NONBLOCK, false);
  1506. tun_put(tun);
  1507. return result;
  1508. }
  1509. /* Put packet to the user space buffer */
  1510. static ssize_t tun_put_user(struct tun_struct *tun,
  1511. struct tun_file *tfile,
  1512. struct sk_buff *skb,
  1513. struct iov_iter *iter)
  1514. {
  1515. struct tun_pi pi = { 0, skb->protocol };
  1516. struct tun_pcpu_stats *stats;
  1517. ssize_t total;
  1518. int vlan_offset = 0;
  1519. int vlan_hlen = 0;
  1520. int vnet_hdr_sz = 0;
  1521. if (skb_vlan_tag_present(skb))
  1522. vlan_hlen = VLAN_HLEN;
  1523. if (tun->flags & IFF_VNET_HDR)
  1524. vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
  1525. total = skb->len + vlan_hlen + vnet_hdr_sz;
  1526. if (!(tun->flags & IFF_NO_PI)) {
  1527. if (iov_iter_count(iter) < sizeof(pi))
  1528. return -EINVAL;
  1529. total += sizeof(pi);
  1530. if (iov_iter_count(iter) < total) {
  1531. /* Packet will be striped */
  1532. pi.flags |= TUN_PKT_STRIP;
  1533. }
  1534. if (copy_to_iter(&pi, sizeof(pi), iter) != sizeof(pi))
  1535. return -EFAULT;
  1536. }
  1537. if (vnet_hdr_sz) {
  1538. struct virtio_net_hdr gso;
  1539. if (iov_iter_count(iter) < vnet_hdr_sz)
  1540. return -EINVAL;
  1541. if (virtio_net_hdr_from_skb(skb, &gso,
  1542. tun_is_little_endian(tun), true)) {
  1543. struct skb_shared_info *sinfo = skb_shinfo(skb);
  1544. pr_err("unexpected GSO type: "
  1545. "0x%x, gso_size %d, hdr_len %d\n",
  1546. sinfo->gso_type, tun16_to_cpu(tun, gso.gso_size),
  1547. tun16_to_cpu(tun, gso.hdr_len));
  1548. print_hex_dump(KERN_ERR, "tun: ",
  1549. DUMP_PREFIX_NONE,
  1550. 16, 1, skb->head,
  1551. min((int)tun16_to_cpu(tun, gso.hdr_len), 64), true);
  1552. WARN_ON_ONCE(1);
  1553. return -EINVAL;
  1554. }
  1555. if (copy_to_iter(&gso, sizeof(gso), iter) != sizeof(gso))
  1556. return -EFAULT;
  1557. iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
  1558. }
  1559. if (vlan_hlen) {
  1560. int ret;
  1561. struct {
  1562. __be16 h_vlan_proto;
  1563. __be16 h_vlan_TCI;
  1564. } veth;
  1565. veth.h_vlan_proto = skb->vlan_proto;
  1566. veth.h_vlan_TCI = htons(skb_vlan_tag_get(skb));
  1567. vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
  1568. ret = skb_copy_datagram_iter(skb, 0, iter, vlan_offset);
  1569. if (ret || !iov_iter_count(iter))
  1570. goto done;
  1571. ret = copy_to_iter(&veth, sizeof(veth), iter);
  1572. if (ret != sizeof(veth) || !iov_iter_count(iter))
  1573. goto done;
  1574. }
  1575. skb_copy_datagram_iter(skb, vlan_offset, iter, skb->len - vlan_offset);
  1576. done:
  1577. /* caller is in process context, */
  1578. stats = get_cpu_ptr(tun->pcpu_stats);
  1579. u64_stats_update_begin(&stats->syncp);
  1580. stats->tx_packets++;
  1581. stats->tx_bytes += skb->len + vlan_hlen;
  1582. u64_stats_update_end(&stats->syncp);
  1583. put_cpu_ptr(tun->pcpu_stats);
  1584. return total;
  1585. }
  1586. static struct sk_buff *tun_ring_recv(struct tun_file *tfile, int noblock,
  1587. int *err)
  1588. {
  1589. DECLARE_WAITQUEUE(wait, current);
  1590. struct sk_buff *skb = NULL;
  1591. int error = 0;
  1592. skb = skb_array_consume(&tfile->tx_array);
  1593. if (skb)
  1594. goto out;
  1595. if (noblock) {
  1596. error = -EAGAIN;
  1597. goto out;
  1598. }
  1599. add_wait_queue(&tfile->wq.wait, &wait);
  1600. current->state = TASK_INTERRUPTIBLE;
  1601. while (1) {
  1602. skb = skb_array_consume(&tfile->tx_array);
  1603. if (skb)
  1604. break;
  1605. if (signal_pending(current)) {
  1606. error = -ERESTARTSYS;
  1607. break;
  1608. }
  1609. if (tfile->socket.sk->sk_shutdown & RCV_SHUTDOWN) {
  1610. error = -EFAULT;
  1611. break;
  1612. }
  1613. schedule();
  1614. }
  1615. current->state = TASK_RUNNING;
  1616. remove_wait_queue(&tfile->wq.wait, &wait);
  1617. out:
  1618. *err = error;
  1619. return skb;
  1620. }
  1621. static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
  1622. struct iov_iter *to,
  1623. int noblock, struct sk_buff *skb)
  1624. {
  1625. ssize_t ret;
  1626. int err;
  1627. tun_debug(KERN_INFO, tun, "tun_do_read\n");
  1628. if (!iov_iter_count(to))
  1629. return 0;
  1630. if (!skb) {
  1631. /* Read frames from ring */
  1632. skb = tun_ring_recv(tfile, noblock, &err);
  1633. if (!skb)
  1634. return err;
  1635. }
  1636. ret = tun_put_user(tun, tfile, skb, to);
  1637. if (unlikely(ret < 0))
  1638. kfree_skb(skb);
  1639. else
  1640. consume_skb(skb);
  1641. return ret;
  1642. }
  1643. static ssize_t tun_chr_read_iter(struct kiocb *iocb, struct iov_iter *to)
  1644. {
  1645. struct file *file = iocb->ki_filp;
  1646. struct tun_file *tfile = file->private_data;
  1647. struct tun_struct *tun = tun_get(tfile);
  1648. ssize_t len = iov_iter_count(to), ret;
  1649. if (!tun)
  1650. return -EBADFD;
  1651. ret = tun_do_read(tun, tfile, to, file->f_flags & O_NONBLOCK, NULL);
  1652. ret = min_t(ssize_t, ret, len);
  1653. if (ret > 0)
  1654. iocb->ki_pos = ret;
  1655. tun_put(tun);
  1656. return ret;
  1657. }
  1658. static void tun_free_netdev(struct net_device *dev)
  1659. {
  1660. struct tun_struct *tun = netdev_priv(dev);
  1661. BUG_ON(!(list_empty(&tun->disabled)));
  1662. free_percpu(tun->pcpu_stats);
  1663. tun_flow_uninit(tun);
  1664. security_tun_dev_free_security(tun->security);
  1665. }
  1666. static void tun_setup(struct net_device *dev)
  1667. {
  1668. struct tun_struct *tun = netdev_priv(dev);
  1669. tun->owner = INVALID_UID;
  1670. tun->group = INVALID_GID;
  1671. dev->ethtool_ops = &tun_ethtool_ops;
  1672. dev->needs_free_netdev = true;
  1673. dev->priv_destructor = tun_free_netdev;
  1674. /* We prefer our own queue length */
  1675. dev->tx_queue_len = TUN_READQ_SIZE;
  1676. }
  1677. /* Trivial set of netlink ops to allow deleting tun or tap
  1678. * device with netlink.
  1679. */
  1680. static int tun_validate(struct nlattr *tb[], struct nlattr *data[],
  1681. struct netlink_ext_ack *extack)
  1682. {
  1683. return -EINVAL;
  1684. }
  1685. static struct rtnl_link_ops tun_link_ops __read_mostly = {
  1686. .kind = DRV_NAME,
  1687. .priv_size = sizeof(struct tun_struct),
  1688. .setup = tun_setup,
  1689. .validate = tun_validate,
  1690. };
  1691. static void tun_sock_write_space(struct sock *sk)
  1692. {
  1693. struct tun_file *tfile;
  1694. wait_queue_head_t *wqueue;
  1695. if (!sock_writeable(sk))
  1696. return;
  1697. if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags))
  1698. return;
  1699. wqueue = sk_sleep(sk);
  1700. if (wqueue && waitqueue_active(wqueue))
  1701. wake_up_interruptible_sync_poll(wqueue, POLLOUT |
  1702. POLLWRNORM | POLLWRBAND);
  1703. tfile = container_of(sk, struct tun_file, sk);
  1704. kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
  1705. }
  1706. static int tun_sendmsg(struct socket *sock, struct msghdr *m, size_t total_len)
  1707. {
  1708. int ret;
  1709. struct tun_file *tfile = container_of(sock, struct tun_file, socket);
  1710. struct tun_struct *tun = tun_get(tfile);
  1711. if (!tun)
  1712. return -EBADFD;
  1713. ret = tun_get_user(tun, tfile, m->msg_control, &m->msg_iter,
  1714. m->msg_flags & MSG_DONTWAIT,
  1715. m->msg_flags & MSG_MORE);
  1716. tun_put(tun);
  1717. return ret;
  1718. }
  1719. static int tun_recvmsg(struct socket *sock, struct msghdr *m, size_t total_len,
  1720. int flags)
  1721. {
  1722. struct tun_file *tfile = container_of(sock, struct tun_file, socket);
  1723. struct tun_struct *tun = tun_get(tfile);
  1724. int ret;
  1725. if (!tun)
  1726. return -EBADFD;
  1727. if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) {
  1728. ret = -EINVAL;
  1729. goto out;
  1730. }
  1731. if (flags & MSG_ERRQUEUE) {
  1732. ret = sock_recv_errqueue(sock->sk, m, total_len,
  1733. SOL_PACKET, TUN_TX_TIMESTAMP);
  1734. goto out;
  1735. }
  1736. ret = tun_do_read(tun, tfile, &m->msg_iter, flags & MSG_DONTWAIT,
  1737. m->msg_control);
  1738. if (ret > (ssize_t)total_len) {
  1739. m->msg_flags |= MSG_TRUNC;
  1740. ret = flags & MSG_TRUNC ? ret : total_len;
  1741. }
  1742. out:
  1743. tun_put(tun);
  1744. return ret;
  1745. }
  1746. static int tun_peek_len(struct socket *sock)
  1747. {
  1748. struct tun_file *tfile = container_of(sock, struct tun_file, socket);
  1749. struct tun_struct *tun;
  1750. int ret = 0;
  1751. tun = tun_get(tfile);
  1752. if (!tun)
  1753. return 0;
  1754. ret = skb_array_peek_len(&tfile->tx_array);
  1755. tun_put(tun);
  1756. return ret;
  1757. }
  1758. /* Ops structure to mimic raw sockets with tun */
  1759. static const struct proto_ops tun_socket_ops = {
  1760. .peek_len = tun_peek_len,
  1761. .sendmsg = tun_sendmsg,
  1762. .recvmsg = tun_recvmsg,
  1763. };
  1764. static struct proto tun_proto = {
  1765. .name = "tun",
  1766. .owner = THIS_MODULE,
  1767. .obj_size = sizeof(struct tun_file),
  1768. };
  1769. static int tun_flags(struct tun_struct *tun)
  1770. {
  1771. return tun->flags & (TUN_FEATURES | IFF_PERSIST | IFF_TUN | IFF_TAP);
  1772. }
  1773. static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
  1774. char *buf)
  1775. {
  1776. struct tun_struct *tun = netdev_priv(to_net_dev(dev));
  1777. return sprintf(buf, "0x%x\n", tun_flags(tun));
  1778. }
  1779. static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
  1780. char *buf)
  1781. {
  1782. struct tun_struct *tun = netdev_priv(to_net_dev(dev));
  1783. return uid_valid(tun->owner)?
  1784. sprintf(buf, "%u\n",
  1785. from_kuid_munged(current_user_ns(), tun->owner)):
  1786. sprintf(buf, "-1\n");
  1787. }
  1788. static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
  1789. char *buf)
  1790. {
  1791. struct tun_struct *tun = netdev_priv(to_net_dev(dev));
  1792. return gid_valid(tun->group) ?
  1793. sprintf(buf, "%u\n",
  1794. from_kgid_munged(current_user_ns(), tun->group)):
  1795. sprintf(buf, "-1\n");
  1796. }
  1797. static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
  1798. static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
  1799. static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
  1800. static struct attribute *tun_dev_attrs[] = {
  1801. &dev_attr_tun_flags.attr,
  1802. &dev_attr_owner.attr,
  1803. &dev_attr_group.attr,
  1804. NULL
  1805. };
  1806. static const struct attribute_group tun_attr_group = {
  1807. .attrs = tun_dev_attrs
  1808. };
  1809. static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
  1810. {
  1811. struct tun_struct *tun;
  1812. struct tun_file *tfile = file->private_data;
  1813. struct net_device *dev;
  1814. int err;
  1815. if (tfile->detached)
  1816. return -EINVAL;
  1817. if ((ifr->ifr_flags & IFF_NAPI_FRAGS)) {
  1818. if (!capable(CAP_NET_ADMIN))
  1819. return -EPERM;
  1820. if (!(ifr->ifr_flags & IFF_NAPI) ||
  1821. (ifr->ifr_flags & TUN_TYPE_MASK) != IFF_TAP)
  1822. return -EINVAL;
  1823. }
  1824. dev = __dev_get_by_name(net, ifr->ifr_name);
  1825. if (dev) {
  1826. if (ifr->ifr_flags & IFF_TUN_EXCL)
  1827. return -EBUSY;
  1828. if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
  1829. tun = netdev_priv(dev);
  1830. else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
  1831. tun = netdev_priv(dev);
  1832. else
  1833. return -EINVAL;
  1834. if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
  1835. !!(tun->flags & IFF_MULTI_QUEUE))
  1836. return -EINVAL;
  1837. if (tun_not_capable(tun))
  1838. return -EPERM;
  1839. err = security_tun_dev_open(tun->security);
  1840. if (err < 0)
  1841. return err;
  1842. err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER,
  1843. ifr->ifr_flags & IFF_NAPI);
  1844. if (err < 0)
  1845. return err;
  1846. if (tun->flags & IFF_MULTI_QUEUE &&
  1847. (tun->numqueues + tun->numdisabled > 1)) {
  1848. /* One or more queue has already been attached, no need
  1849. * to initialize the device again.
  1850. */
  1851. return 0;
  1852. }
  1853. }
  1854. else {
  1855. char *name;
  1856. unsigned long flags = 0;
  1857. int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
  1858. MAX_TAP_QUEUES : 1;
  1859. if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
  1860. return -EPERM;
  1861. err = security_tun_dev_create();
  1862. if (err < 0)
  1863. return err;
  1864. /* Set dev type */
  1865. if (ifr->ifr_flags & IFF_TUN) {
  1866. /* TUN device */
  1867. flags |= IFF_TUN;
  1868. name = "tun%d";
  1869. } else if (ifr->ifr_flags & IFF_TAP) {
  1870. /* TAP device */
  1871. flags |= IFF_TAP;
  1872. name = "tap%d";
  1873. } else
  1874. return -EINVAL;
  1875. if (*ifr->ifr_name)
  1876. name = ifr->ifr_name;
  1877. dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
  1878. NET_NAME_UNKNOWN, tun_setup, queues,
  1879. queues);
  1880. if (!dev)
  1881. return -ENOMEM;
  1882. err = dev_get_valid_name(net, dev, name);
  1883. if (err < 0)
  1884. goto err_free_dev;
  1885. dev_net_set(dev, net);
  1886. dev->rtnl_link_ops = &tun_link_ops;
  1887. dev->ifindex = tfile->ifindex;
  1888. dev->sysfs_groups[0] = &tun_attr_group;
  1889. tun = netdev_priv(dev);
  1890. tun->dev = dev;
  1891. tun->flags = flags;
  1892. tun->txflt.count = 0;
  1893. tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
  1894. tun->align = NET_SKB_PAD;
  1895. tun->filter_attached = false;
  1896. tun->sndbuf = tfile->socket.sk->sk_sndbuf;
  1897. tun->rx_batched = 0;
  1898. tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats);
  1899. if (!tun->pcpu_stats) {
  1900. err = -ENOMEM;
  1901. goto err_free_dev;
  1902. }
  1903. spin_lock_init(&tun->lock);
  1904. err = security_tun_dev_alloc_security(&tun->security);
  1905. if (err < 0)
  1906. goto err_free_stat;
  1907. tun_net_init(dev);
  1908. tun_flow_init(tun);
  1909. dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
  1910. TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
  1911. NETIF_F_HW_VLAN_STAG_TX;
  1912. dev->features = dev->hw_features | NETIF_F_LLTX;
  1913. dev->vlan_features = dev->features &
  1914. ~(NETIF_F_HW_VLAN_CTAG_TX |
  1915. NETIF_F_HW_VLAN_STAG_TX);
  1916. INIT_LIST_HEAD(&tun->disabled);
  1917. err = tun_attach(tun, file, false, ifr->ifr_flags & IFF_NAPI);
  1918. if (err < 0)
  1919. goto err_free_flow;
  1920. err = register_netdevice(tun->dev);
  1921. if (err < 0)
  1922. goto err_detach;
  1923. }
  1924. netif_carrier_on(tun->dev);
  1925. tun_debug(KERN_INFO, tun, "tun_set_iff\n");
  1926. tun->flags = (tun->flags & ~TUN_FEATURES) |
  1927. (ifr->ifr_flags & TUN_FEATURES);
  1928. /* Make sure persistent devices do not get stuck in
  1929. * xoff state.
  1930. */
  1931. if (netif_running(tun->dev))
  1932. netif_tx_wake_all_queues(tun->dev);
  1933. strcpy(ifr->ifr_name, tun->dev->name);
  1934. return 0;
  1935. err_detach:
  1936. tun_detach_all(dev);
  1937. /* register_netdevice() already called tun_free_netdev() */
  1938. goto err_free_dev;
  1939. err_free_flow:
  1940. tun_flow_uninit(tun);
  1941. security_tun_dev_free_security(tun->security);
  1942. err_free_stat:
  1943. free_percpu(tun->pcpu_stats);
  1944. err_free_dev:
  1945. free_netdev(dev);
  1946. return err;
  1947. }
  1948. static void tun_get_iff(struct net *net, struct tun_struct *tun,
  1949. struct ifreq *ifr)
  1950. {
  1951. tun_debug(KERN_INFO, tun, "tun_get_iff\n");
  1952. strcpy(ifr->ifr_name, tun->dev->name);
  1953. ifr->ifr_flags = tun_flags(tun);
  1954. }
  1955. /* This is like a cut-down ethtool ops, except done via tun fd so no
  1956. * privs required. */
  1957. static int set_offload(struct tun_struct *tun, unsigned long arg)
  1958. {
  1959. netdev_features_t features = 0;
  1960. if (arg & TUN_F_CSUM) {
  1961. features |= NETIF_F_HW_CSUM;
  1962. arg &= ~TUN_F_CSUM;
  1963. if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
  1964. if (arg & TUN_F_TSO_ECN) {
  1965. features |= NETIF_F_TSO_ECN;
  1966. arg &= ~TUN_F_TSO_ECN;
  1967. }
  1968. if (arg & TUN_F_TSO4)
  1969. features |= NETIF_F_TSO;
  1970. if (arg & TUN_F_TSO6)
  1971. features |= NETIF_F_TSO6;
  1972. arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
  1973. }
  1974. }
  1975. /* This gives the user a way to test for new features in future by
  1976. * trying to set them. */
  1977. if (arg)
  1978. return -EINVAL;
  1979. tun->set_features = features;
  1980. tun->dev->wanted_features &= ~TUN_USER_FEATURES;
  1981. tun->dev->wanted_features |= features;
  1982. netdev_update_features(tun->dev);
  1983. return 0;
  1984. }
  1985. static void tun_detach_filter(struct tun_struct *tun, int n)
  1986. {
  1987. int i;
  1988. struct tun_file *tfile;
  1989. for (i = 0; i < n; i++) {
  1990. tfile = rtnl_dereference(tun->tfiles[i]);
  1991. lock_sock(tfile->socket.sk);
  1992. sk_detach_filter(tfile->socket.sk);
  1993. release_sock(tfile->socket.sk);
  1994. }
  1995. tun->filter_attached = false;
  1996. }
  1997. static int tun_attach_filter(struct tun_struct *tun)
  1998. {
  1999. int i, ret = 0;
  2000. struct tun_file *tfile;
  2001. for (i = 0; i < tun->numqueues; i++) {
  2002. tfile = rtnl_dereference(tun->tfiles[i]);
  2003. lock_sock(tfile->socket.sk);
  2004. ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
  2005. release_sock(tfile->socket.sk);
  2006. if (ret) {
  2007. tun_detach_filter(tun, i);
  2008. return ret;
  2009. }
  2010. }
  2011. tun->filter_attached = true;
  2012. return ret;
  2013. }
  2014. static void tun_set_sndbuf(struct tun_struct *tun)
  2015. {
  2016. struct tun_file *tfile;
  2017. int i;
  2018. for (i = 0; i < tun->numqueues; i++) {
  2019. tfile = rtnl_dereference(tun->tfiles[i]);
  2020. tfile->socket.sk->sk_sndbuf = tun->sndbuf;
  2021. }
  2022. }
  2023. static int tun_set_queue(struct file *file, struct ifreq *ifr)
  2024. {
  2025. struct tun_file *tfile = file->private_data;
  2026. struct tun_struct *tun;
  2027. int ret = 0;
  2028. rtnl_lock();
  2029. if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
  2030. tun = tfile->detached;
  2031. if (!tun) {
  2032. ret = -EINVAL;
  2033. goto unlock;
  2034. }
  2035. ret = security_tun_dev_attach_queue(tun->security);
  2036. if (ret < 0)
  2037. goto unlock;
  2038. ret = tun_attach(tun, file, false, tun->flags & IFF_NAPI);
  2039. } else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
  2040. tun = rtnl_dereference(tfile->tun);
  2041. if (!tun || !(tun->flags & IFF_MULTI_QUEUE) || tfile->detached)
  2042. ret = -EINVAL;
  2043. else
  2044. __tun_detach(tfile, false);
  2045. } else
  2046. ret = -EINVAL;
  2047. unlock:
  2048. rtnl_unlock();
  2049. return ret;
  2050. }
  2051. static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
  2052. unsigned long arg, int ifreq_len)
  2053. {
  2054. struct tun_file *tfile = file->private_data;
  2055. struct tun_struct *tun;
  2056. void __user* argp = (void __user*)arg;
  2057. struct ifreq ifr;
  2058. kuid_t owner;
  2059. kgid_t group;
  2060. int sndbuf;
  2061. int vnet_hdr_sz;
  2062. unsigned int ifindex;
  2063. int le;
  2064. int ret;
  2065. if (cmd == TUNSETIFF || cmd == TUNSETQUEUE || _IOC_TYPE(cmd) == SOCK_IOC_TYPE) {
  2066. if (copy_from_user(&ifr, argp, ifreq_len))
  2067. return -EFAULT;
  2068. } else {
  2069. memset(&ifr, 0, sizeof(ifr));
  2070. }
  2071. if (cmd == TUNGETFEATURES) {
  2072. /* Currently this just means: "what IFF flags are valid?".
  2073. * This is needed because we never checked for invalid flags on
  2074. * TUNSETIFF.
  2075. */
  2076. return put_user(IFF_TUN | IFF_TAP | TUN_FEATURES,
  2077. (unsigned int __user*)argp);
  2078. } else if (cmd == TUNSETQUEUE)
  2079. return tun_set_queue(file, &ifr);
  2080. ret = 0;
  2081. rtnl_lock();
  2082. tun = tun_get(tfile);
  2083. if (cmd == TUNSETIFF) {
  2084. ret = -EEXIST;
  2085. if (tun)
  2086. goto unlock;
  2087. ifr.ifr_name[IFNAMSIZ-1] = '\0';
  2088. ret = tun_set_iff(sock_net(&tfile->sk), file, &ifr);
  2089. if (ret)
  2090. goto unlock;
  2091. if (copy_to_user(argp, &ifr, ifreq_len))
  2092. ret = -EFAULT;
  2093. goto unlock;
  2094. }
  2095. if (cmd == TUNSETIFINDEX) {
  2096. ret = -EPERM;
  2097. if (tun)
  2098. goto unlock;
  2099. ret = -EFAULT;
  2100. if (copy_from_user(&ifindex, argp, sizeof(ifindex)))
  2101. goto unlock;
  2102. ret = 0;
  2103. tfile->ifindex = ifindex;
  2104. goto unlock;
  2105. }
  2106. ret = -EBADFD;
  2107. if (!tun)
  2108. goto unlock;
  2109. tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
  2110. ret = 0;
  2111. switch (cmd) {
  2112. case TUNGETIFF:
  2113. tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
  2114. if (tfile->detached)
  2115. ifr.ifr_flags |= IFF_DETACH_QUEUE;
  2116. if (!tfile->socket.sk->sk_filter)
  2117. ifr.ifr_flags |= IFF_NOFILTER;
  2118. if (copy_to_user(argp, &ifr, ifreq_len))
  2119. ret = -EFAULT;
  2120. break;
  2121. case TUNSETNOCSUM:
  2122. /* Disable/Enable checksum */
  2123. /* [unimplemented] */
  2124. tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
  2125. arg ? "disabled" : "enabled");
  2126. break;
  2127. case TUNSETPERSIST:
  2128. /* Disable/Enable persist mode. Keep an extra reference to the
  2129. * module to prevent the module being unprobed.
  2130. */
  2131. if (arg && !(tun->flags & IFF_PERSIST)) {
  2132. tun->flags |= IFF_PERSIST;
  2133. __module_get(THIS_MODULE);
  2134. }
  2135. if (!arg && (tun->flags & IFF_PERSIST)) {
  2136. tun->flags &= ~IFF_PERSIST;
  2137. module_put(THIS_MODULE);
  2138. }
  2139. tun_debug(KERN_INFO, tun, "persist %s\n",
  2140. arg ? "enabled" : "disabled");
  2141. break;
  2142. case TUNSETOWNER:
  2143. /* Set owner of the device */
  2144. owner = make_kuid(current_user_ns(), arg);
  2145. if (!uid_valid(owner)) {
  2146. ret = -EINVAL;
  2147. break;
  2148. }
  2149. tun->owner = owner;
  2150. tun_debug(KERN_INFO, tun, "owner set to %u\n",
  2151. from_kuid(&init_user_ns, tun->owner));
  2152. break;
  2153. case TUNSETGROUP:
  2154. /* Set group of the device */
  2155. group = make_kgid(current_user_ns(), arg);
  2156. if (!gid_valid(group)) {
  2157. ret = -EINVAL;
  2158. break;
  2159. }
  2160. tun->group = group;
  2161. tun_debug(KERN_INFO, tun, "group set to %u\n",
  2162. from_kgid(&init_user_ns, tun->group));
  2163. break;
  2164. case TUNSETLINK:
  2165. /* Only allow setting the type when the interface is down */
  2166. if (tun->dev->flags & IFF_UP) {
  2167. tun_debug(KERN_INFO, tun,
  2168. "Linktype set failed because interface is up\n");
  2169. ret = -EBUSY;
  2170. } else {
  2171. tun->dev->type = (int) arg;
  2172. tun_debug(KERN_INFO, tun, "linktype set to %d\n",
  2173. tun->dev->type);
  2174. ret = 0;
  2175. }
  2176. break;
  2177. #ifdef TUN_DEBUG
  2178. case TUNSETDEBUG:
  2179. tun->debug = arg;
  2180. break;
  2181. #endif
  2182. case TUNSETOFFLOAD:
  2183. ret = set_offload(tun, arg);
  2184. break;
  2185. case TUNSETTXFILTER:
  2186. /* Can be set only for TAPs */
  2187. ret = -EINVAL;
  2188. if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
  2189. break;
  2190. ret = update_filter(&tun->txflt, (void __user *)arg);
  2191. break;
  2192. case SIOCGIFHWADDR:
  2193. /* Get hw address */
  2194. memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
  2195. ifr.ifr_hwaddr.sa_family = tun->dev->type;
  2196. if (copy_to_user(argp, &ifr, ifreq_len))
  2197. ret = -EFAULT;
  2198. break;
  2199. case SIOCSIFHWADDR:
  2200. /* Set hw address */
  2201. tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
  2202. ifr.ifr_hwaddr.sa_data);
  2203. ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
  2204. break;
  2205. case TUNGETSNDBUF:
  2206. sndbuf = tfile->socket.sk->sk_sndbuf;
  2207. if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
  2208. ret = -EFAULT;
  2209. break;
  2210. case TUNSETSNDBUF:
  2211. if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
  2212. ret = -EFAULT;
  2213. break;
  2214. }
  2215. if (sndbuf <= 0) {
  2216. ret = -EINVAL;
  2217. break;
  2218. }
  2219. tun->sndbuf = sndbuf;
  2220. tun_set_sndbuf(tun);
  2221. break;
  2222. case TUNGETVNETHDRSZ:
  2223. vnet_hdr_sz = tun->vnet_hdr_sz;
  2224. if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
  2225. ret = -EFAULT;
  2226. break;
  2227. case TUNSETVNETHDRSZ:
  2228. if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
  2229. ret = -EFAULT;
  2230. break;
  2231. }
  2232. if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
  2233. ret = -EINVAL;
  2234. break;
  2235. }
  2236. tun->vnet_hdr_sz = vnet_hdr_sz;
  2237. break;
  2238. case TUNGETVNETLE:
  2239. le = !!(tun->flags & TUN_VNET_LE);
  2240. if (put_user(le, (int __user *)argp))
  2241. ret = -EFAULT;
  2242. break;
  2243. case TUNSETVNETLE:
  2244. if (get_user(le, (int __user *)argp)) {
  2245. ret = -EFAULT;
  2246. break;
  2247. }
  2248. if (le)
  2249. tun->flags |= TUN_VNET_LE;
  2250. else
  2251. tun->flags &= ~TUN_VNET_LE;
  2252. break;
  2253. case TUNGETVNETBE:
  2254. ret = tun_get_vnet_be(tun, argp);
  2255. break;
  2256. case TUNSETVNETBE:
  2257. ret = tun_set_vnet_be(tun, argp);
  2258. break;
  2259. case TUNATTACHFILTER:
  2260. /* Can be set only for TAPs */
  2261. ret = -EINVAL;
  2262. if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
  2263. break;
  2264. ret = -EFAULT;
  2265. if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
  2266. break;
  2267. ret = tun_attach_filter(tun);
  2268. break;
  2269. case TUNDETACHFILTER:
  2270. /* Can be set only for TAPs */
  2271. ret = -EINVAL;
  2272. if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
  2273. break;
  2274. ret = 0;
  2275. tun_detach_filter(tun, tun->numqueues);
  2276. break;
  2277. case TUNGETFILTER:
  2278. ret = -EINVAL;
  2279. if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
  2280. break;
  2281. ret = -EFAULT;
  2282. if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog)))
  2283. break;
  2284. ret = 0;
  2285. break;
  2286. default:
  2287. ret = -EINVAL;
  2288. break;
  2289. }
  2290. unlock:
  2291. rtnl_unlock();
  2292. if (tun)
  2293. tun_put(tun);
  2294. return ret;
  2295. }
  2296. static long tun_chr_ioctl(struct file *file,
  2297. unsigned int cmd, unsigned long arg)
  2298. {
  2299. return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
  2300. }
  2301. #ifdef CONFIG_COMPAT
  2302. static long tun_chr_compat_ioctl(struct file *file,
  2303. unsigned int cmd, unsigned long arg)
  2304. {
  2305. switch (cmd) {
  2306. case TUNSETIFF:
  2307. case TUNGETIFF:
  2308. case TUNSETTXFILTER:
  2309. case TUNGETSNDBUF:
  2310. case TUNSETSNDBUF:
  2311. case SIOCGIFHWADDR:
  2312. case SIOCSIFHWADDR:
  2313. arg = (unsigned long)compat_ptr(arg);
  2314. break;
  2315. default:
  2316. arg = (compat_ulong_t)arg;
  2317. break;
  2318. }
  2319. /*
  2320. * compat_ifreq is shorter than ifreq, so we must not access beyond
  2321. * the end of that structure. All fields that are used in this
  2322. * driver are compatible though, we don't need to convert the
  2323. * contents.
  2324. */
  2325. return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
  2326. }
  2327. #endif /* CONFIG_COMPAT */
  2328. static int tun_chr_fasync(int fd, struct file *file, int on)
  2329. {
  2330. struct tun_file *tfile = file->private_data;
  2331. int ret;
  2332. if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
  2333. goto out;
  2334. if (on) {
  2335. __f_setown(file, task_pid(current), PIDTYPE_PID, 0);
  2336. tfile->flags |= TUN_FASYNC;
  2337. } else
  2338. tfile->flags &= ~TUN_FASYNC;
  2339. ret = 0;
  2340. out:
  2341. return ret;
  2342. }
  2343. static int tun_chr_open(struct inode *inode, struct file * file)
  2344. {
  2345. struct net *net = current->nsproxy->net_ns;
  2346. struct tun_file *tfile;
  2347. DBG1(KERN_INFO, "tunX: tun_chr_open\n");
  2348. tfile = (struct tun_file *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
  2349. &tun_proto, 0);
  2350. if (!tfile)
  2351. return -ENOMEM;
  2352. RCU_INIT_POINTER(tfile->tun, NULL);
  2353. tfile->flags = 0;
  2354. tfile->ifindex = 0;
  2355. init_waitqueue_head(&tfile->wq.wait);
  2356. RCU_INIT_POINTER(tfile->socket.wq, &tfile->wq);
  2357. tfile->socket.file = file;
  2358. tfile->socket.ops = &tun_socket_ops;
  2359. sock_init_data(&tfile->socket, &tfile->sk);
  2360. tfile->sk.sk_write_space = tun_sock_write_space;
  2361. tfile->sk.sk_sndbuf = INT_MAX;
  2362. file->private_data = tfile;
  2363. INIT_LIST_HEAD(&tfile->next);
  2364. sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
  2365. return 0;
  2366. }
  2367. static int tun_chr_close(struct inode *inode, struct file *file)
  2368. {
  2369. struct tun_file *tfile = file->private_data;
  2370. tun_detach(tfile, true);
  2371. return 0;
  2372. }
  2373. #ifdef CONFIG_PROC_FS
  2374. static void tun_chr_show_fdinfo(struct seq_file *m, struct file *file)
  2375. {
  2376. struct tun_file *tfile = file->private_data;
  2377. struct tun_struct *tun;
  2378. struct ifreq ifr;
  2379. memset(&ifr, 0, sizeof(ifr));
  2380. rtnl_lock();
  2381. tun = tun_get(tfile);
  2382. if (tun)
  2383. tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
  2384. rtnl_unlock();
  2385. if (tun)
  2386. tun_put(tun);
  2387. seq_printf(m, "iff:\t%s\n", ifr.ifr_name);
  2388. }
  2389. #endif
  2390. static const struct file_operations tun_fops = {
  2391. .owner = THIS_MODULE,
  2392. .llseek = no_llseek,
  2393. .read_iter = tun_chr_read_iter,
  2394. .write_iter = tun_chr_write_iter,
  2395. .poll = tun_chr_poll,
  2396. .unlocked_ioctl = tun_chr_ioctl,
  2397. #ifdef CONFIG_COMPAT
  2398. .compat_ioctl = tun_chr_compat_ioctl,
  2399. #endif
  2400. .open = tun_chr_open,
  2401. .release = tun_chr_close,
  2402. .fasync = tun_chr_fasync,
  2403. #ifdef CONFIG_PROC_FS
  2404. .show_fdinfo = tun_chr_show_fdinfo,
  2405. #endif
  2406. };
  2407. static struct miscdevice tun_miscdev = {
  2408. .minor = TUN_MINOR,
  2409. .name = "tun",
  2410. .nodename = "net/tun",
  2411. .fops = &tun_fops,
  2412. };
  2413. /* ethtool interface */
  2414. static int tun_get_link_ksettings(struct net_device *dev,
  2415. struct ethtool_link_ksettings *cmd)
  2416. {
  2417. ethtool_link_ksettings_zero_link_mode(cmd, supported);
  2418. ethtool_link_ksettings_zero_link_mode(cmd, advertising);
  2419. cmd->base.speed = SPEED_10;
  2420. cmd->base.duplex = DUPLEX_FULL;
  2421. cmd->base.port = PORT_TP;
  2422. cmd->base.phy_address = 0;
  2423. cmd->base.autoneg = AUTONEG_DISABLE;
  2424. return 0;
  2425. }
  2426. static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
  2427. {
  2428. struct tun_struct *tun = netdev_priv(dev);
  2429. strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
  2430. strlcpy(info->version, DRV_VERSION, sizeof(info->version));
  2431. switch (tun->flags & TUN_TYPE_MASK) {
  2432. case IFF_TUN:
  2433. strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
  2434. break;
  2435. case IFF_TAP:
  2436. strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
  2437. break;
  2438. }
  2439. }
  2440. static u32 tun_get_msglevel(struct net_device *dev)
  2441. {
  2442. #ifdef TUN_DEBUG
  2443. struct tun_struct *tun = netdev_priv(dev);
  2444. return tun->debug;
  2445. #else
  2446. return -EOPNOTSUPP;
  2447. #endif
  2448. }
  2449. static void tun_set_msglevel(struct net_device *dev, u32 value)
  2450. {
  2451. #ifdef TUN_DEBUG
  2452. struct tun_struct *tun = netdev_priv(dev);
  2453. tun->debug = value;
  2454. #endif
  2455. }
  2456. static int tun_get_coalesce(struct net_device *dev,
  2457. struct ethtool_coalesce *ec)
  2458. {
  2459. struct tun_struct *tun = netdev_priv(dev);
  2460. ec->rx_max_coalesced_frames = tun->rx_batched;
  2461. return 0;
  2462. }
  2463. static int tun_set_coalesce(struct net_device *dev,
  2464. struct ethtool_coalesce *ec)
  2465. {
  2466. struct tun_struct *tun = netdev_priv(dev);
  2467. if (ec->rx_max_coalesced_frames > NAPI_POLL_WEIGHT)
  2468. tun->rx_batched = NAPI_POLL_WEIGHT;
  2469. else
  2470. tun->rx_batched = ec->rx_max_coalesced_frames;
  2471. return 0;
  2472. }
  2473. static const struct ethtool_ops tun_ethtool_ops = {
  2474. .get_drvinfo = tun_get_drvinfo,
  2475. .get_msglevel = tun_get_msglevel,
  2476. .set_msglevel = tun_set_msglevel,
  2477. .get_link = ethtool_op_get_link,
  2478. .get_ts_info = ethtool_op_get_ts_info,
  2479. .get_coalesce = tun_get_coalesce,
  2480. .set_coalesce = tun_set_coalesce,
  2481. .get_link_ksettings = tun_get_link_ksettings,
  2482. };
  2483. static int tun_queue_resize(struct tun_struct *tun)
  2484. {
  2485. struct net_device *dev = tun->dev;
  2486. struct tun_file *tfile;
  2487. struct skb_array **arrays;
  2488. int n = tun->numqueues + tun->numdisabled;
  2489. int ret, i;
  2490. arrays = kmalloc_array(n, sizeof(*arrays), GFP_KERNEL);
  2491. if (!arrays)
  2492. return -ENOMEM;
  2493. for (i = 0; i < tun->numqueues; i++) {
  2494. tfile = rtnl_dereference(tun->tfiles[i]);
  2495. arrays[i] = &tfile->tx_array;
  2496. }
  2497. list_for_each_entry(tfile, &tun->disabled, next)
  2498. arrays[i++] = &tfile->tx_array;
  2499. ret = skb_array_resize_multiple(arrays, n,
  2500. dev->tx_queue_len, GFP_KERNEL);
  2501. kfree(arrays);
  2502. return ret;
  2503. }
  2504. static int tun_device_event(struct notifier_block *unused,
  2505. unsigned long event, void *ptr)
  2506. {
  2507. struct net_device *dev = netdev_notifier_info_to_dev(ptr);
  2508. struct tun_struct *tun = netdev_priv(dev);
  2509. if (dev->rtnl_link_ops != &tun_link_ops)
  2510. return NOTIFY_DONE;
  2511. switch (event) {
  2512. case NETDEV_CHANGE_TX_QUEUE_LEN:
  2513. if (tun_queue_resize(tun))
  2514. return NOTIFY_BAD;
  2515. break;
  2516. default:
  2517. break;
  2518. }
  2519. return NOTIFY_DONE;
  2520. }
  2521. static struct notifier_block tun_notifier_block __read_mostly = {
  2522. .notifier_call = tun_device_event,
  2523. };
  2524. static int __init tun_init(void)
  2525. {
  2526. int ret = 0;
  2527. pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
  2528. ret = rtnl_link_register(&tun_link_ops);
  2529. if (ret) {
  2530. pr_err("Can't register link_ops\n");
  2531. goto err_linkops;
  2532. }
  2533. ret = misc_register(&tun_miscdev);
  2534. if (ret) {
  2535. pr_err("Can't register misc device %d\n", TUN_MINOR);
  2536. goto err_misc;
  2537. }
  2538. ret = register_netdevice_notifier(&tun_notifier_block);
  2539. if (ret) {
  2540. pr_err("Can't register netdevice notifier\n");
  2541. goto err_notifier;
  2542. }
  2543. return 0;
  2544. err_notifier:
  2545. misc_deregister(&tun_miscdev);
  2546. err_misc:
  2547. rtnl_link_unregister(&tun_link_ops);
  2548. err_linkops:
  2549. return ret;
  2550. }
  2551. static void tun_cleanup(void)
  2552. {
  2553. misc_deregister(&tun_miscdev);
  2554. rtnl_link_unregister(&tun_link_ops);
  2555. unregister_netdevice_notifier(&tun_notifier_block);
  2556. }
  2557. /* Get an underlying socket object from tun file. Returns error unless file is
  2558. * attached to a device. The returned object works like a packet socket, it
  2559. * can be used for sock_sendmsg/sock_recvmsg. The caller is responsible for
  2560. * holding a reference to the file for as long as the socket is in use. */
  2561. struct socket *tun_get_socket(struct file *file)
  2562. {
  2563. struct tun_file *tfile;
  2564. if (file->f_op != &tun_fops)
  2565. return ERR_PTR(-EINVAL);
  2566. tfile = file->private_data;
  2567. if (!tfile)
  2568. return ERR_PTR(-EBADFD);
  2569. return &tfile->socket;
  2570. }
  2571. EXPORT_SYMBOL_GPL(tun_get_socket);
  2572. struct skb_array *tun_get_skb_array(struct file *file)
  2573. {
  2574. struct tun_file *tfile;
  2575. if (file->f_op != &tun_fops)
  2576. return ERR_PTR(-EINVAL);
  2577. tfile = file->private_data;
  2578. if (!tfile)
  2579. return ERR_PTR(-EBADFD);
  2580. return &tfile->tx_array;
  2581. }
  2582. EXPORT_SYMBOL_GPL(tun_get_skb_array);
  2583. module_init(tun_init);
  2584. module_exit(tun_cleanup);
  2585. MODULE_DESCRIPTION(DRV_DESCRIPTION);
  2586. MODULE_AUTHOR(DRV_COPYRIGHT);
  2587. MODULE_LICENSE("GPL");
  2588. MODULE_ALIAS_MISCDEV(TUN_MINOR);
  2589. MODULE_ALIAS("devname:net/tun");