tun.c 81 KB

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