tun.c 82 KB

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