tun.c 66 KB

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