tun.c 84 KB

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