Debian Codegraph @

net/vmw_vsock/af_vsock.c

raw
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * VMware vSockets Driver
4 *
5 * Copyright (C) 2007-2013 VMware, Inc. All rights reserved.
6 */
7
8 /* Implementation notes:
9 *
10 * - There are two kinds of sockets: those created by user action (such as
11 * calling socket(2)) and those created by incoming connection request packets.
12 *
13 * - There are two "global" tables, one for bound sockets (sockets that have
14 * specified an address that they are responsible for) and one for connected
15 * sockets (sockets that have established a connection with another socket).
16 * These tables are "global" in that all sockets on the system are placed
17 * within them. - Note, though, that the bound table contains an extra entry
18 * for a list of unbound sockets and SOCK_DGRAM sockets will always remain in
19 * that list. The bound table is used solely for lookup of sockets when packets
20 * are received and that's not necessary for SOCK_DGRAM sockets since we create
21 * a datagram handle for each and need not perform a lookup. Keeping SOCK_DGRAM
22 * sockets out of the bound hash buckets will reduce the chance of collisions
23 * when looking for SOCK_STREAM sockets and prevents us from having to check the
24 * socket type in the hash table lookups.
25 *
26 * - Sockets created by user action will either be "client" sockets that
27 * initiate a connection or "server" sockets that listen for connections; we do
28 * not support simultaneous connects (two "client" sockets connecting).
29 *
30 * - "Server" sockets are referred to as listener sockets throughout this
31 * implementation because they are in the TCP_LISTEN state. When a
32 * connection request is received (the second kind of socket mentioned above),
33 * we create a new socket and refer to it as a pending socket. These pending
34 * sockets are placed on the pending connection list of the listener socket.
35 * When future packets are received for the address the listener socket is
36 * bound to, we check if the source of the packet is from one that has an
37 * existing pending connection. If it does, we process the packet for the
38 * pending socket. When that socket reaches the connected state, it is removed
39 * from the listener socket's pending list and enqueued in the listener
40 * socket's accept queue. Callers of accept(2) will accept connected sockets
41 * from the listener socket's accept queue. If the socket cannot be accepted
42 * for some reason then it is marked rejected. Once the connection is
43 * accepted, it is owned by the user process and the responsibility for cleanup
44 * falls with that user process.
45 *
46 * - It is possible that these pending sockets will never reach the connected
47 * state; in fact, we may never receive another packet after the connection
48 * request. Because of this, we must schedule a cleanup function to run in the
49 * future, after some amount of time passes where a connection should have been
50 * established. This function ensures that the socket is off all lists so it
51 * cannot be retrieved, then drops all references to the socket so it is cleaned
52 * up (sock_put() -> sk_free() -> our sk_destruct implementation). Note this
53 * function will also cleanup rejected sockets, those that reach the connected
54 * state but leave it before they have been accepted.
55 *
56 * - Lock ordering for pending or accept queue sockets is:
57 *
58 * lock_sock(listener);
59 * lock_sock_nested(pending, SINGLE_DEPTH_NESTING);
60 *
61 * Using explicit nested locking keeps lockdep happy since normally only one
62 * lock of a given class may be taken at a time.
63 *
64 * - Sockets created by user action will be cleaned up when the user process
65 * calls close(2), causing our release implementation to be called. Our release
66 * implementation will perform some cleanup then drop the last reference so our
67 * sk_destruct implementation is invoked. Our sk_destruct implementation will
68 * perform additional cleanup that's common for both types of sockets.
69 *
70 * - A socket's reference count is what ensures that the structure won't be
71 * freed. Each entry in a list (such as the "global" bound and connected tables
72 * and the listener socket's pending list and connected queue) ensures a
73 * reference. When we defer work until process context and pass a socket as our
74 * argument, we must ensure the reference count is increased to ensure the
75 * socket isn't freed before the function is run; the deferred function will
76 * then drop the reference.
77 *
78 * - sk->sk_state uses the TCP state constants because they are widely used by
79 * other address families and exposed to userspace tools like ss(8):
80 *
81 * TCP_CLOSE - unconnected
82 * TCP_SYN_SENT - connecting
83 * TCP_ESTABLISHED - connected
84 * TCP_CLOSING - disconnecting
85 * TCP_LISTEN - listening
86 *
87 * - Namespaces in vsock support two different modes: "local" and "global".
88 * Each mode defines how the namespace interacts with CIDs.
89 * Each namespace exposes two sysctl files:
90 *
91 * - /proc/sys/net/vsock/ns_mode (read-only) reports the current namespace's
92 * mode, which is set at namespace creation and immutable thereafter.
93 * - /proc/sys/net/vsock/child_ns_mode (write-once) controls what mode future
94 * child namespaces will inherit when created. The initial value matches
95 * the namespace's own ns_mode.
96 *
97 * Changing child_ns_mode only affects newly created namespaces, not the
98 * current namespace or existing children. A "local" namespace cannot set
99 * child_ns_mode to "global". child_ns_mode is write-once, so that it may be
100 * configured and locked down by a namespace manager. Writing a different
101 * value after the first write returns -EBUSY. At namespace creation, ns_mode
102 * is inherited from the parent's child_ns_mode.
103 *
104 * The init_net mode is "global" and cannot be modified. The init_net
105 * child_ns_mode is also write-once, so an init process (e.g. systemd) can
106 * set it to "local" to ensure all new namespaces inherit local mode.
107 *
108 * The modes affect the allocation and accessibility of CIDs as follows:
109 *
110 * - global - access and allocation are all system-wide
111 * - all CID allocation from global namespaces draw from the same
112 * system-wide pool.
113 * - if one global namespace has already allocated some CID, another
114 * global namespace will not be able to allocate the same CID.
115 * - global mode AF_VSOCK sockets can reach any VM or socket in any global
116 * namespace, they are not contained to only their own namespace.
117 * - AF_VSOCK sockets in a global mode namespace cannot reach VMs or
118 * sockets in any local mode namespace.
119 * - local - access and allocation are contained within the namespace
120 * - CID allocation draws only from a private pool local only to the
121 * namespace, and does not affect the CIDs available for allocation in any
122 * other namespace (global or local).
123 * - VMs in a local namespace do not collide with CIDs in any other local
124 * namespace or any global namespace. For example, if a VM in a local mode
125 * namespace is given CID 10, then CID 10 is still available for
126 * allocation in any other namespace, but not in the same namespace.
127 * - AF_VSOCK sockets in a local mode namespace can connect only to VMs or
128 * other sockets within their own namespace.
129 * - sockets bound to VMADDR_CID_ANY in local namespaces will never resolve
130 * to any transport that is not compatible with local mode. There is no
131 * error that propagates to the user (as there is for connection attempts)
132 * because it is possible for some packet to reach this socket from
133 * a different transport that *does* support local mode. For
134 * example, virtio-vsock may not support local mode, but the socket
135 * may still accept a connection from vhost-vsock which does.
136 */
137
138 #include <linux/compat.h>
139 #include <linux/types.h>
140 #include <linux/bitops.h>
141 #include <linux/cred.h>
142 #include <linux/errqueue.h>
143 #include <linux/init.h>
144 #include <linux/io.h>
145 #include <linux/kernel.h>
146 #include <linux/sched/signal.h>
147 #include <linux/kmod.h>
148 #include <linux/list.h>
149 #include <linux/miscdevice.h>
150 #include <linux/module.h>
151 #include <linux/mutex.h>
152 #include <linux/net.h>
153 #include <linux/proc_fs.h>
154 #include <linux/poll.h>
155 #include <linux/random.h>
156 #include <linux/skbuff.h>
157 #include <linux/smp.h>
158 #include <linux/socket.h>
159 #include <linux/stddef.h>
160 #include <linux/sysctl.h>
161 #include <linux/unistd.h>
162 #include <linux/wait.h>
163 #include <linux/workqueue.h>
164 #include <net/sock.h>
165 #include <net/af_vsock.h>
166 #include <net/netns/vsock.h>
167 #include <uapi/linux/vm_sockets.h>
168 #include <uapi/asm-generic/ioctls.h>
169
170 #define VSOCK_NET_MODE_STR_GLOBAL "global"
171 #define VSOCK_NET_MODE_STR_LOCAL "local"
172
173 /* 6 chars for "global", 1 for null-terminator, and 1 more for '\n'.
174 * The newline is added by proc_dostring() for read operations.
175 */
176 #define VSOCK_NET_MODE_STR_MAX 8
177
178 static int __vsock_bind(struct sock *sk, struct sockaddr_vm *addr);
179 static void vsock_sk_destruct(struct sock *sk);
180 static int vsock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb);
181 static void vsock_close(struct sock *sk, long timeout);
182
183 /* Protocol family. */
184 struct proto vsock_proto = {
185 .name = "AF_VSOCK",
186 .owner = THIS_MODULE,
187 .obj_size = sizeof(struct vsock_sock),
188 .close = vsock_close,
189 #ifdef CONFIG_BPF_SYSCALL
190 .psock_update_sk_prot = vsock_bpf_update_proto,
191 #endif
192 };
193
194 /* The default peer timeout indicates how long we will wait for a peer response
195 * to a control message.
196 */
197 #define VSOCK_DEFAULT_CONNECT_TIMEOUT (2 * HZ)
198
199 #define VSOCK_DEFAULT_BUFFER_SIZE (1024 * 256)
200 #define VSOCK_DEFAULT_BUFFER_MAX_SIZE (1024 * 256)
201 #define VSOCK_DEFAULT_BUFFER_MIN_SIZE 128
202
203 /* Transport used for host->guest communication */
204 static const struct vsock_transport *transport_h2g;
205 /* Transport used for guest->host communication */
206 static const struct vsock_transport *transport_g2h;
207 /* Transport used for DGRAM communication */
208 static const struct vsock_transport *transport_dgram;
209 /* Transport used for local communication */
210 static const struct vsock_transport *transport_local;
211 static DEFINE_MUTEX(vsock_register_mutex);
212
213 /**** UTILS ****/
214
215 /* Each bound VSocket is stored in the bind hash table and each connected
216 * VSocket is stored in the connected hash table.
217 *
218 * Unbound sockets are all put on the same list attached to the end of the hash
219 * table (vsock_unbound_sockets). Bound sockets are added to the hash table in
220 * the bucket that their local address hashes to (vsock_bound_sockets(addr)
221 * represents the list that addr hashes to).
222 *
223 * Specifically, we initialize the vsock_bind_table array to a size of
224 * VSOCK_HASH_SIZE + 1 so that vsock_bind_table[0] through
225 * vsock_bind_table[VSOCK_HASH_SIZE - 1] are for bound sockets and
226 * vsock_bind_table[VSOCK_HASH_SIZE] is for unbound sockets. The hash function
227 * mods with VSOCK_HASH_SIZE to ensure this.
228 */
229 #define MAX_PORT_RETRIES 24
230
231 #define VSOCK_HASH(addr) ((addr)->svm_port % VSOCK_HASH_SIZE)
232 #define vsock_bound_sockets(addr) (&vsock_bind_table[VSOCK_HASH(addr)])
233 #define vsock_unbound_sockets (&vsock_bind_table[VSOCK_HASH_SIZE])
234
235 /* XXX This can probably be implemented in a better way. */
236 #define VSOCK_CONN_HASH(src, dst) \
237 (((src)->svm_cid ^ (dst)->svm_port) % VSOCK_HASH_SIZE)
238 #define vsock_connected_sockets(src, dst) \
239 (&vsock_connected_table[VSOCK_CONN_HASH(src, dst)])
240 #define vsock_connected_sockets_vsk(vsk) \
241 vsock_connected_sockets(&(vsk)->remote_addr, &(vsk)->local_addr)
242
243 struct list_head vsock_bind_table[VSOCK_HASH_SIZE + 1];
244 EXPORT_SYMBOL_GPL(vsock_bind_table);
245 struct list_head vsock_connected_table[VSOCK_HASH_SIZE];
246 EXPORT_SYMBOL_GPL(vsock_connected_table);
247 DEFINE_SPINLOCK(vsock_table_lock);
248 EXPORT_SYMBOL_GPL(vsock_table_lock);
249
250 /* Autobind this socket to the local address if necessary. */
251 static int vsock_auto_bind(struct vsock_sock *vsk)
252 {
253 struct sock *sk = sk_vsock(vsk);
254 struct sockaddr_vm local_addr;
255
256 if (vsock_addr_bound(&vsk->local_addr))
257 return 0;
258 vsock_addr_init(&local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
259 return __vsock_bind(sk, &local_addr);
260 }
261
262 static void vsock_init_tables(void)
263 {
264 int i;
265
266 for (i = 0; i < ARRAY_SIZE(vsock_bind_table); i++)
267 INIT_LIST_HEAD(&vsock_bind_table[i]);
268
269 for (i = 0; i < ARRAY_SIZE(vsock_connected_table); i++)
270 INIT_LIST_HEAD(&vsock_connected_table[i]);
271 }
272
273 static void __vsock_insert_bound(struct list_head *list,
274 struct vsock_sock *vsk)
275 {
276 sock_hold(&vsk->sk);
277 list_add(&vsk->bound_table, list);
278 }
279
280 static void __vsock_insert_connected(struct list_head *list,
281 struct vsock_sock *vsk)
282 {
283 sock_hold(&vsk->sk);
284 list_add(&vsk->connected_table, list);
285 }
286
287 static void __vsock_remove_bound(struct vsock_sock *vsk)
288 {
289 list_del_init(&vsk->bound_table);
290 sock_put(&vsk->sk);
291 }
292
293 static void __vsock_remove_connected(struct vsock_sock *vsk)
294 {
295 list_del_init(&vsk->connected_table);
296 sock_put(&vsk->sk);
297 }
298
299 static struct sock *__vsock_find_bound_socket_net(struct sockaddr_vm *addr,
300 struct net *net)
301 {
302 struct vsock_sock *vsk;
303
304 list_for_each_entry(vsk, vsock_bound_sockets(addr), bound_table) {
305 struct sock *sk = sk_vsock(vsk);
306
307 if (vsock_addr_equals_addr(addr, &vsk->local_addr) &&
308 vsock_net_check_mode(sock_net(sk), net))
309 return sk;
310
311 if (addr->svm_port == vsk->local_addr.svm_port &&
312 (vsk->local_addr.svm_cid == VMADDR_CID_ANY ||
313 addr->svm_cid == VMADDR_CID_ANY) &&
314 vsock_net_check_mode(sock_net(sk), net))
315 return sk;
316 }
317
318 return NULL;
319 }
320
321 static struct sock *
322 __vsock_find_connected_socket_net(struct sockaddr_vm *src,
323 struct sockaddr_vm *dst, struct net *net)
324 {
325 struct vsock_sock *vsk;
326
327 list_for_each_entry(vsk, vsock_connected_sockets(src, dst),
328 connected_table) {
329 struct sock *sk = sk_vsock(vsk);
330
331 if (vsock_addr_equals_addr(src, &vsk->remote_addr) &&
332 dst->svm_port == vsk->local_addr.svm_port &&
333 vsock_net_check_mode(sock_net(sk), net)) {
334 return sk;
335 }
336 }
337
338 return NULL;
339 }
340
341 static void vsock_insert_unbound(struct vsock_sock *vsk)
342 {
343 spin_lock_bh(&vsock_table_lock);
344 __vsock_insert_bound(vsock_unbound_sockets, vsk);
345 spin_unlock_bh(&vsock_table_lock);
346 }
347
348 void vsock_insert_connected(struct vsock_sock *vsk)
349 {
350 struct list_head *list = vsock_connected_sockets(
351 &vsk->remote_addr, &vsk->local_addr);
352
353 spin_lock_bh(&vsock_table_lock);
354 __vsock_insert_connected(list, vsk);
355 spin_unlock_bh(&vsock_table_lock);
356 }
357 EXPORT_SYMBOL_GPL(vsock_insert_connected);
358
359 void vsock_remove_bound(struct vsock_sock *vsk)
360 {
361 spin_lock_bh(&vsock_table_lock);
362 if (__vsock_in_bound_table(vsk))
363 __vsock_remove_bound(vsk);
364 spin_unlock_bh(&vsock_table_lock);
365 }
366 EXPORT_SYMBOL_GPL(vsock_remove_bound);
367
368 void vsock_remove_connected(struct vsock_sock *vsk)
369 {
370 spin_lock_bh(&vsock_table_lock);
371 if (__vsock_in_connected_table(vsk))
372 __vsock_remove_connected(vsk);
373 spin_unlock_bh(&vsock_table_lock);
374 }
375 EXPORT_SYMBOL_GPL(vsock_remove_connected);
376
377 /* Find a bound socket, filtering by namespace and namespace mode.
378 *
379 * Use this in transports that are namespace-aware and can provide the
380 * network namespace context.
381 */
382 struct sock *vsock_find_bound_socket_net(struct sockaddr_vm *addr,
383 struct net *net)
384 {
385 struct sock *sk;
386
387 spin_lock_bh(&vsock_table_lock);
388 sk = __vsock_find_bound_socket_net(addr, net);
389 if (sk)
390 sock_hold(sk);
391
392 spin_unlock_bh(&vsock_table_lock);
393
394 return sk;
395 }
396 EXPORT_SYMBOL_GPL(vsock_find_bound_socket_net);
397
398 /* Find a bound socket without namespace filtering.
399 *
400 * Use this in transports that lack namespace context. All sockets are
401 * treated as if in global mode.
402 */
403 struct sock *vsock_find_bound_socket(struct sockaddr_vm *addr)
404 {
405 return vsock_find_bound_socket_net(addr, NULL);
406 }
407 EXPORT_SYMBOL_GPL(vsock_find_bound_socket);
408
409 /* Find a connected socket, filtering by namespace and namespace mode.
410 *
411 * Use this in transports that are namespace-aware and can provide the
412 * network namespace context.
413 */
414 struct sock *vsock_find_connected_socket_net(struct sockaddr_vm *src,
415 struct sockaddr_vm *dst,
416 struct net *net)
417 {
418 struct sock *sk;
419
420 spin_lock_bh(&vsock_table_lock);
421 sk = __vsock_find_connected_socket_net(src, dst, net);
422 if (sk)
423 sock_hold(sk);
424
425 spin_unlock_bh(&vsock_table_lock);
426
427 return sk;
428 }
429 EXPORT_SYMBOL_GPL(vsock_find_connected_socket_net);
430
431 /* Find a connected socket without namespace filtering.
432 *
433 * Use this in transports that lack namespace context. All sockets are
434 * treated as if in global mode.
435 */
436 struct sock *vsock_find_connected_socket(struct sockaddr_vm *src,
437 struct sockaddr_vm *dst)
438 {
439 return vsock_find_connected_socket_net(src, dst, NULL);
440 }
441 EXPORT_SYMBOL_GPL(vsock_find_connected_socket);
442
443 void vsock_remove_sock(struct vsock_sock *vsk)
444 {
445 /* Transport reassignment must not remove the binding. */
446 if (sock_flag(sk_vsock(vsk), SOCK_DEAD))
447 vsock_remove_bound(vsk);
448
449 vsock_remove_connected(vsk);
450 }
451 EXPORT_SYMBOL_GPL(vsock_remove_sock);
452
453 void vsock_for_each_connected_socket(struct vsock_transport *transport,
454 void (*fn)(struct sock *sk))
455 {
456 int i;
457
458 spin_lock_bh(&vsock_table_lock);
459
460 for (i = 0; i < ARRAY_SIZE(vsock_connected_table); i++) {
461 struct vsock_sock *vsk;
462 list_for_each_entry(vsk, &vsock_connected_table[i],
463 connected_table) {
464 if (vsk->transport != transport)
465 continue;
466
467 fn(sk_vsock(vsk));
468 }
469 }
470
471 spin_unlock_bh(&vsock_table_lock);
472 }
473 EXPORT_SYMBOL_GPL(vsock_for_each_connected_socket);
474
475 void vsock_add_pending(struct sock *listener, struct sock *pending)
476 {
477 struct vsock_sock *vlistener;
478 struct vsock_sock *vpending;
479
480 vlistener = vsock_sk(listener);
481 vpending = vsock_sk(pending);
482
483 sock_hold(pending);
484 sock_hold(listener);
485 list_add_tail(&vpending->pending_links, &vlistener->pending_links);
486 }
487 EXPORT_SYMBOL_GPL(vsock_add_pending);
488
489 void vsock_remove_pending(struct sock *listener, struct sock *pending)
490 {
491 struct vsock_sock *vpending = vsock_sk(pending);
492
493 list_del_init(&vpending->pending_links);
494 sock_put(listener);
495 sock_put(pending);
496 }
497 EXPORT_SYMBOL_GPL(vsock_remove_pending);
498
499 void vsock_enqueue_accept(struct sock *listener, struct sock *connected)
500 {
501 struct vsock_sock *vlistener;
502 struct vsock_sock *vconnected;
503
504 vlistener = vsock_sk(listener);
505 vconnected = vsock_sk(connected);
506
507 sock_hold(connected);
508 sock_hold(listener);
509 list_add_tail(&vconnected->accept_queue, &vlistener->accept_queue);
510 }
511 EXPORT_SYMBOL_GPL(vsock_enqueue_accept);
512
513 static bool vsock_use_local_transport(unsigned int remote_cid)
514 {
515 lockdep_assert_held(&vsock_register_mutex);
516
517 if (!transport_local)
518 return false;
519
520 if (remote_cid == VMADDR_CID_LOCAL)
521 return true;
522
523 if (transport_g2h) {
524 return remote_cid == transport_g2h->get_local_cid();
525 } else {
526 return remote_cid == VMADDR_CID_HOST;
527 }
528 }
529
530 static void vsock_deassign_transport(struct vsock_sock *vsk)
531 {
532 if (!vsk->transport)
533 return;
534
535 vsk->transport->destruct(vsk);
536 module_put(vsk->transport->module);
537 vsk->transport = NULL;
538 }
539
540 /* Assign a transport to a socket and call the .init transport callback.
541 *
542 * Note: for connection oriented socket this must be called when vsk->remote_addr
543 * is set (e.g. during the connect() or when a connection request on a listener
544 * socket is received).
545 * The vsk->remote_addr is used to decide which transport to use:
546 * - remote CID == VMADDR_CID_LOCAL or g2h->local_cid or VMADDR_CID_HOST if
547 * g2h is not loaded, will use local transport;
548 * - remote CID <= VMADDR_CID_HOST or h2g is not loaded or remote flags field
549 * includes VMADDR_FLAG_TO_HOST flag value, will use guest->host transport;
550 * - remote CID > VMADDR_CID_HOST will use host->guest transport;
551 */
552 int vsock_assign_transport(struct vsock_sock *vsk, struct vsock_sock *psk)
553 {
554 const struct vsock_transport *new_transport;
555 struct sock *sk = sk_vsock(vsk);
556 unsigned int remote_cid = vsk->remote_addr.svm_cid;
557 __u8 remote_flags;
558 int ret;
559
560 /* If the packet is coming with the source and destination CIDs higher
561 * than VMADDR_CID_HOST, then a vsock channel where all the packets are
562 * forwarded to the host should be established. Then the host will
563 * need to forward the packets to the guest.
564 *
565 * The flag is set on the (listen) receive path (psk is not NULL). On
566 * the connect path the flag can be set by the user space application.
567 */
568 if (psk && vsk->local_addr.svm_cid > VMADDR_CID_HOST &&
569 vsk->remote_addr.svm_cid > VMADDR_CID_HOST)
570 vsk->remote_addr.svm_flags |= VMADDR_FLAG_TO_HOST;
571
572 remote_flags = vsk->remote_addr.svm_flags;
573
574 mutex_lock(&vsock_register_mutex);
575
576 switch (sk->sk_type) {
577 case SOCK_DGRAM:
578 new_transport = transport_dgram;
579 break;
580 case SOCK_STREAM:
581 case SOCK_SEQPACKET:
582 if (vsock_use_local_transport(remote_cid))
583 new_transport = transport_local;
584 else if (remote_cid <= VMADDR_CID_HOST || !transport_h2g ||
585 (remote_flags & VMADDR_FLAG_TO_HOST))
586 new_transport = transport_g2h;
587 else
588 new_transport = transport_h2g;
589 break;
590 default:
591 ret = -ESOCKTNOSUPPORT;
592 goto err;
593 }
594
595 if (vsk->transport && vsk->transport == new_transport) {
596 ret = 0;
597 goto err;
598 }
599
600 /* We increase the module refcnt to prevent the transport unloading
601 * while there are open sockets assigned to it.
602 */
603 if (!new_transport || !try_module_get(new_transport->module)) {
604 ret = -ENODEV;
605 goto err;
606 }
607
608 /* It's safe to release the mutex after a successful try_module_get().
609 * Whichever transport `new_transport` points at, it won't go away until
610 * the last module_put() below or in vsock_deassign_transport().
611 */
612 mutex_unlock(&vsock_register_mutex);
613
614 if (vsk->transport) {
615 /* transport->release() must be called with sock lock acquired.
616 * This path can only be taken during vsock_connect(), where we
617 * have already held the sock lock. In the other cases, this
618 * function is called on a new socket which is not assigned to
619 * any transport.
620 */
621 vsk->transport->release(vsk);
622 vsock_deassign_transport(vsk);
623
624 /* transport's release() and destruct() can touch some socket
625 * state, since we are reassigning the socket to a new transport
626 * during vsock_connect(), let's reset these fields to have a
627 * clean state.
628 */
629 sock_reset_flag(sk, SOCK_DONE);
630 sk->sk_state = TCP_CLOSE;
631 WRITE_ONCE(vsk->peer_shutdown, 0);
632 }
633
634 if (sk->sk_type == SOCK_SEQPACKET) {
635 if (!new_transport->seqpacket_allow ||
636 !new_transport->seqpacket_allow(vsk, remote_cid)) {
637 module_put(new_transport->module);
638 return -ESOCKTNOSUPPORT;
639 }
640 }
641
642 ret = new_transport->init(vsk, psk);
643 if (ret) {
644 module_put(new_transport->module);
645 return ret;
646 }
647
648 vsk->transport = new_transport;
649
650 return 0;
651 err:
652 mutex_unlock(&vsock_register_mutex);
653 return ret;
654 }
655 EXPORT_SYMBOL_GPL(vsock_assign_transport);
656
657 /*
658 * Provide safe access to static transport_{h2g,g2h,dgram,local} callbacks.
659 * Otherwise we may race with module removal. Do not use on `vsk->transport`.
660 */
661 static u32 vsock_registered_transport_cid(const struct vsock_transport **transport)
662 {
663 u32 cid = VMADDR_CID_ANY;
664
665 mutex_lock(&vsock_register_mutex);
666 if (*transport)
667 cid = (*transport)->get_local_cid();
668 mutex_unlock(&vsock_register_mutex);
669
670 return cid;
671 }
672
673 bool vsock_find_cid(unsigned int cid)
674 {
675 if (cid == vsock_registered_transport_cid(&transport_g2h))
676 return true;
677
678 if (transport_h2g && cid == VMADDR_CID_HOST)
679 return true;
680
681 if (transport_local && cid == VMADDR_CID_LOCAL)
682 return true;
683
684 return false;
685 }
686 EXPORT_SYMBOL_GPL(vsock_find_cid);
687
688 static struct sock *vsock_dequeue_accept(struct sock *listener)
689 {
690 struct vsock_sock *vlistener;
691 struct vsock_sock *vconnected;
692
693 vlistener = vsock_sk(listener);
694
695 if (list_empty(&vlistener->accept_queue))
696 return NULL;
697
698 vconnected = list_entry(vlistener->accept_queue.next,
699 struct vsock_sock, accept_queue);
700
701 list_del_init(&vconnected->accept_queue);
702 sock_put(listener);
703 /* The caller will need a reference on the connected socket so we let
704 * it call sock_put().
705 */
706
707 return sk_vsock(vconnected);
708 }
709
710 static bool vsock_is_accept_queue_empty(struct sock *sk)
711 {
712 struct vsock_sock *vsk = vsock_sk(sk);
713 return list_empty(&vsk->accept_queue);
714 }
715
716 static bool vsock_is_pending(struct sock *sk)
717 {
718 struct vsock_sock *vsk = vsock_sk(sk);
719 return !list_empty(&vsk->pending_links);
720 }
721
722 static int vsock_send_shutdown(struct sock *sk, int mode)
723 {
724 struct vsock_sock *vsk = vsock_sk(sk);
725
726 if (!vsk->transport)
727 return -ENODEV;
728
729 return vsk->transport->shutdown(vsk, mode);
730 }
731
732 static void vsock_pending_work(struct work_struct *work)
733 {
734 struct sock *sk;
735 struct sock *listener;
736 struct vsock_sock *vsk;
737 bool cleanup;
738
739 vsk = container_of(work, struct vsock_sock, pending_work.work);
740 sk = sk_vsock(vsk);
741 listener = vsk->listener;
742 cleanup = true;
743
744 lock_sock(listener);
745 lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
746
747 if (vsock_is_pending(sk)) {
748 vsock_remove_pending(listener, sk);
749
750 sk_acceptq_removed(listener);
751 } else if (!vsk->rejected) {
752 /* We are not on the pending list and accept() did not reject
753 * us, so we must have been accepted by our user process. We
754 * just need to drop our references to the sockets and be on
755 * our way.
756 */
757 cleanup = false;
758 goto out;
759 }
760
761 /* We need to remove ourself from the global connected sockets list so
762 * incoming packets can't find this socket, and to reduce the reference
763 * count.
764 */
765 vsock_remove_connected(vsk);
766
767 sk->sk_state = TCP_CLOSE;
768
769 out:
770 release_sock(sk);
771 release_sock(listener);
772 if (cleanup)
773 sock_put(sk);
774
775 sock_put(sk);
776 sock_put(listener);
777 }
778
779 /**** SOCKET OPERATIONS ****/
780
781 static int __vsock_bind_connectible(struct vsock_sock *vsk,
782 struct sockaddr_vm *addr)
783 {
784 struct net *net = sock_net(sk_vsock(vsk));
785 struct sockaddr_vm new_addr;
786
787 if (!net->vsock.port)
788 net->vsock.port = get_random_u32_above(LAST_RESERVED_PORT);
789
790 vsock_addr_init(&new_addr, addr->svm_cid, addr->svm_port);
791
792 if (addr->svm_port == VMADDR_PORT_ANY) {
793 bool found = false;
794 unsigned int i;
795
796 for (i = 0; i < MAX_PORT_RETRIES; i++) {
797 if (net->vsock.port == VMADDR_PORT_ANY ||
798 net->vsock.port <= LAST_RESERVED_PORT)
799 net->vsock.port = LAST_RESERVED_PORT + 1;
800
801 new_addr.svm_port = net->vsock.port++;
802
803 if (!__vsock_find_bound_socket_net(&new_addr, net)) {
804 found = true;
805 break;
806 }
807 }
808
809 if (!found)
810 return -EADDRNOTAVAIL;
811 } else {
812 /* If port is in reserved range, ensure caller
813 * has necessary privileges.
814 */
815 if (addr->svm_port <= LAST_RESERVED_PORT &&
816 !capable(CAP_NET_BIND_SERVICE)) {
817 return -EACCES;
818 }
819
820 if (__vsock_find_bound_socket_net(&new_addr, net))
821 return -EADDRINUSE;
822 }
823
824 vsock_addr_init(&vsk->local_addr, new_addr.svm_cid, new_addr.svm_port);
825
826 /* Remove connection oriented sockets from the unbound list and add them
827 * to the hash table for easy lookup by its address. The unbound list
828 * is simply an extra entry at the end of the hash table, a trick used
829 * by AF_UNIX.
830 */
831 __vsock_remove_bound(vsk);
832 __vsock_insert_bound(vsock_bound_sockets(&vsk->local_addr), vsk);
833
834 return 0;
835 }
836
837 static int __vsock_bind_dgram(struct vsock_sock *vsk,
838 struct sockaddr_vm *addr)
839 {
840 return vsk->transport->dgram_bind(vsk, addr);
841 }
842
843 static int __vsock_bind(struct sock *sk, struct sockaddr_vm *addr)
844 {
845 struct vsock_sock *vsk = vsock_sk(sk);
846 int retval;
847
848 /* First ensure this socket isn't already bound. */
849 if (vsock_addr_bound(&vsk->local_addr))
850 return -EINVAL;
851
852 /* Now bind to the provided address or select appropriate values if
853 * none are provided (VMADDR_CID_ANY and VMADDR_PORT_ANY). Note that
854 * like AF_INET prevents binding to a non-local IP address (in most
855 * cases), we only allow binding to a local CID.
856 */
857 if (addr->svm_cid != VMADDR_CID_ANY && !vsock_find_cid(addr->svm_cid))
858 return -EADDRNOTAVAIL;
859
860 switch (sk->sk_socket->type) {
861 case SOCK_STREAM:
862 case SOCK_SEQPACKET:
863 spin_lock_bh(&vsock_table_lock);
864 retval = __vsock_bind_connectible(vsk, addr);
865 spin_unlock_bh(&vsock_table_lock);
866 break;
867
868 case SOCK_DGRAM:
869 retval = __vsock_bind_dgram(vsk, addr);
870 break;
871
872 default:
873 retval = -EINVAL;
874 break;
875 }
876
877 return retval;
878 }
879
880 static void vsock_connect_timeout(struct work_struct *work);
881
882 static struct sock *__vsock_create(struct net *net,
883 struct socket *sock,
884 struct sock *parent,
885 gfp_t priority,
886 unsigned short type,
887 int kern)
888 {
889 struct sock *sk;
890 struct vsock_sock *psk;
891 struct vsock_sock *vsk;
892
893 sk = sk_alloc(net, AF_VSOCK, priority, &vsock_proto, kern);
894 if (!sk)
895 return NULL;
896
897 sock_init_data(sock, sk);
898
899 /* sk->sk_type is normally set in sock_init_data, but only if sock is
900 * non-NULL. We make sure that our sockets always have a type by
901 * setting it here if needed.
902 */
903 if (!sock)
904 sk->sk_type = type;
905
906 vsk = vsock_sk(sk);
907 vsock_addr_init(&vsk->local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
908 vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
909
910 sk->sk_destruct = vsock_sk_destruct;
911 sk->sk_backlog_rcv = vsock_queue_rcv_skb;
912 sock_reset_flag(sk, SOCK_DONE);
913
914 INIT_LIST_HEAD(&vsk->bound_table);
915 INIT_LIST_HEAD(&vsk->connected_table);
916 vsk->listener = NULL;
917 INIT_LIST_HEAD(&vsk->pending_links);
918 INIT_LIST_HEAD(&vsk->accept_queue);
919 vsk->rejected = false;
920 vsk->sent_request = false;
921 vsk->ignore_connecting_rst = false;
922 WRITE_ONCE(vsk->peer_shutdown, 0);
923 INIT_DELAYED_WORK(&vsk->connect_work, vsock_connect_timeout);
924 INIT_DELAYED_WORK(&vsk->pending_work, vsock_pending_work);
925
926 psk = parent ? vsock_sk(parent) : NULL;
927 if (parent) {
928 vsk->trusted = psk->trusted;
929 vsk->owner = get_cred(psk->owner);
930 vsk->connect_timeout = psk->connect_timeout;
931 vsk->buffer_size = psk->buffer_size;
932 vsk->buffer_min_size = psk->buffer_min_size;
933 vsk->buffer_max_size = psk->buffer_max_size;
934 security_sk_clone(parent, sk);
935 } else {
936 vsk->trusted = ns_capable_noaudit(&init_user_ns, CAP_NET_ADMIN);
937 vsk->owner = get_current_cred();
938 vsk->connect_timeout = VSOCK_DEFAULT_CONNECT_TIMEOUT;
939 vsk->buffer_size = VSOCK_DEFAULT_BUFFER_SIZE;
940 vsk->buffer_min_size = VSOCK_DEFAULT_BUFFER_MIN_SIZE;
941 vsk->buffer_max_size = VSOCK_DEFAULT_BUFFER_MAX_SIZE;
942 }
943
944 return sk;
945 }
946
947 static bool sock_type_connectible(u16 type)
948 {
949 return (type == SOCK_STREAM) || (type == SOCK_SEQPACKET);
950 }
951
952 static void __vsock_release(struct sock *sk, int level)
953 {
954 struct vsock_sock *vsk;
955 struct sock *pending;
956
957 vsk = vsock_sk(sk);
958 pending = NULL; /* Compiler warning. */
959
960 /* When "level" is SINGLE_DEPTH_NESTING, use the nested
961 * version to avoid the warning "possible recursive locking
962 * detected". When "level" is 0, lock_sock_nested(sk, level)
963 * is the same as lock_sock(sk).
964 */
965 lock_sock_nested(sk, level);
966
967 /* Indicate to vsock_remove_sock() that the socket is being released and
968 * can be removed from the bound_table. Unlike transport reassignment
969 * case, where the socket must remain bound despite vsock_remove_sock()
970 * being called from the transport release() callback.
971 */
972 sock_set_flag(sk, SOCK_DEAD);
973
974 if (vsk->transport)
975 vsk->transport->release(vsk);
976 else if (sock_type_connectible(sk->sk_type))
977 vsock_remove_sock(vsk);
978
979 sock_orphan(sk);
980 sk->sk_shutdown = SHUTDOWN_MASK;
981
982 skb_queue_purge(&sk->sk_receive_queue);
983
984 /* Clean up any sockets that never were accepted. */
985 while ((pending = vsock_dequeue_accept(sk)) != NULL) {
986 __vsock_release(pending, SINGLE_DEPTH_NESTING);
987 sock_put(pending);
988 }
989
990 release_sock(sk);
991 sock_put(sk);
992 }
993
994 static void vsock_sk_destruct(struct sock *sk)
995 {
996 struct vsock_sock *vsk = vsock_sk(sk);
997
998 /* Flush MSG_ZEROCOPY leftovers. */
999 __skb_queue_purge(&sk->sk_error_queue);
1000
1001 vsock_deassign_transport(vsk);
1002
1003 /* When clearing these addresses, there's no need to set the family and
1004 * possibly register the address family with the kernel.
1005 */
1006 vsock_addr_init(&vsk->local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
1007 vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
1008
1009 put_cred(vsk->owner);
1010 }
1011
1012 static int vsock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
1013 {
1014 int err;
1015
1016 err = sock_queue_rcv_skb(sk, skb);
1017 if (err)
1018 kfree_skb(skb);
1019
1020 return err;
1021 }
1022
1023 struct sock *vsock_create_connected(struct sock *parent)
1024 {
1025 return __vsock_create(sock_net(parent), NULL, parent, GFP_KERNEL,
1026 parent->sk_type, 0);
1027 }
1028 EXPORT_SYMBOL_GPL(vsock_create_connected);
1029
1030 s64 vsock_stream_has_data(struct vsock_sock *vsk)
1031 {
1032 if (WARN_ON(!vsk->transport))
1033 return 0;
1034
1035 return vsk->transport->stream_has_data(vsk);
1036 }
1037 EXPORT_SYMBOL_GPL(vsock_stream_has_data);
1038
1039 s64 vsock_connectible_has_data(struct vsock_sock *vsk)
1040 {
1041 struct sock *sk = sk_vsock(vsk);
1042
1043 if (WARN_ON(!vsk->transport))
1044 return 0;
1045
1046 if (sk->sk_type == SOCK_SEQPACKET)
1047 return vsk->transport->seqpacket_has_data(vsk);
1048 else
1049 return vsock_stream_has_data(vsk);
1050 }
1051 EXPORT_SYMBOL_GPL(vsock_connectible_has_data);
1052
1053 s64 vsock_stream_has_space(struct vsock_sock *vsk)
1054 {
1055 if (WARN_ON(!vsk->transport))
1056 return 0;
1057
1058 return vsk->transport->stream_has_space(vsk);
1059 }
1060 EXPORT_SYMBOL_GPL(vsock_stream_has_space);
1061
1062 void vsock_data_ready(struct sock *sk)
1063 {
1064 struct vsock_sock *vsk = vsock_sk(sk);
1065
1066 if (vsock_stream_has_data(vsk) >= sk->sk_rcvlowat ||
1067 sock_flag(sk, SOCK_DONE))
1068 sk->sk_data_ready(sk);
1069 }
1070 EXPORT_SYMBOL_GPL(vsock_data_ready);
1071
1072 /* Dummy callback required by sockmap.
1073 * See unconditional call of saved_close() in sock_map_close().
1074 */
1075 static void vsock_close(struct sock *sk, long timeout)
1076 {
1077 }
1078
1079 static int vsock_release(struct socket *sock)
1080 {
1081 struct sock *sk = sock->sk;
1082
1083 if (!sk)
1084 return 0;
1085
1086 sk->sk_prot->close(sk, 0);
1087 __vsock_release(sk, 0);
1088 sock->sk = NULL;
1089 sock->state = SS_FREE;
1090
1091 return 0;
1092 }
1093
1094 static int
1095 vsock_bind(struct socket *sock, struct sockaddr_unsized *addr, int addr_len)
1096 {
1097 int err;
1098 struct sock *sk;
1099 struct sockaddr_vm *vm_addr;
1100
1101 sk = sock->sk;
1102
1103 if (vsock_addr_cast(addr, addr_len, &vm_addr) != 0)
1104 return -EINVAL;
1105
1106 lock_sock(sk);
1107 err = __vsock_bind(sk, vm_addr);
1108 release_sock(sk);
1109
1110 return err;
1111 }
1112
1113 static int vsock_getname(struct socket *sock,
1114 struct sockaddr *addr, int peer)
1115 {
1116 int err;
1117 struct sock *sk;
1118 struct vsock_sock *vsk;
1119 struct sockaddr_vm *vm_addr;
1120
1121 sk = sock->sk;
1122 vsk = vsock_sk(sk);
1123 err = 0;
1124
1125 lock_sock(sk);
1126
1127 if (peer) {
1128 if (sock->state != SS_CONNECTED) {
1129 err = -ENOTCONN;
1130 goto out;
1131 }
1132 vm_addr = &vsk->remote_addr;
1133 } else {
1134 vm_addr = &vsk->local_addr;
1135 }
1136
1137 BUILD_BUG_ON(sizeof(*vm_addr) > sizeof(struct sockaddr_storage));
1138 memcpy(addr, vm_addr, sizeof(*vm_addr));
1139 err = sizeof(*vm_addr);
1140
1141 out:
1142 release_sock(sk);
1143 return err;
1144 }
1145
1146 void vsock_linger(struct sock *sk)
1147 {
1148 DEFINE_WAIT_FUNC(wait, woken_wake_function);
1149 ssize_t (*unsent)(struct vsock_sock *vsk);
1150 struct vsock_sock *vsk = vsock_sk(sk);
1151 long timeout;
1152
1153 if (!sock_flag(sk, SOCK_LINGER))
1154 return;
1155
1156 timeout = sk->sk_lingertime;
1157 if (!timeout)
1158 return;
1159
1160 /* Transports must implement `unsent_bytes` if they want to support
1161 * SOCK_LINGER through `vsock_linger()` since we use it to check when
1162 * the socket can be closed.
1163 */
1164 unsent = vsk->transport->unsent_bytes;
1165 if (!unsent)
1166 return;
1167
1168 add_wait_queue(sk_sleep(sk), &wait);
1169
1170 do {
1171 if (sk_wait_event(sk, &timeout, unsent(vsk) == 0, &wait))
1172 break;
1173 } while (!signal_pending(current) && timeout);
1174
1175 remove_wait_queue(sk_sleep(sk), &wait);
1176 }
1177 EXPORT_SYMBOL_GPL(vsock_linger);
1178
1179 static int vsock_shutdown(struct socket *sock, int mode)
1180 {
1181 int err;
1182 struct sock *sk;
1183
1184 /* User level uses SHUT_RD (0) and SHUT_WR (1), but the kernel uses
1185 * RCV_SHUTDOWN (1) and SEND_SHUTDOWN (2), so we must increment mode
1186 * here like the other address families do. Note also that the
1187 * increment makes SHUT_RDWR (2) into RCV_SHUTDOWN | SEND_SHUTDOWN (3),
1188 * which is what we want.
1189 */
1190 mode++;
1191
1192 if ((mode & ~SHUTDOWN_MASK) || !mode)
1193 return -EINVAL;
1194
1195 /* If this is a connection oriented socket and it is not connected then
1196 * bail out immediately. If it is a DGRAM socket then we must first
1197 * kick the socket so that it wakes up from any sleeping calls, for
1198 * example recv(), and then afterwards return the error.
1199 */
1200
1201 sk = sock->sk;
1202
1203 lock_sock(sk);
1204 if (sock->state == SS_UNCONNECTED) {
1205 err = -ENOTCONN;
1206 if (sock_type_connectible(sk->sk_type))
1207 goto out;
1208 } else {
1209 sock->state = SS_DISCONNECTING;
1210 err = 0;
1211 }
1212
1213 /* Receive and send shutdowns are treated alike. */
1214 mode = mode & (RCV_SHUTDOWN | SEND_SHUTDOWN);
1215 if (mode) {
1216 sk->sk_shutdown |= mode;
1217 sk->sk_state_change(sk);
1218
1219 if (sock_type_connectible(sk->sk_type)) {
1220 sock_reset_flag(sk, SOCK_DONE);
1221 vsock_send_shutdown(sk, mode);
1222 }
1223 }
1224
1225 out:
1226 release_sock(sk);
1227 return err;
1228 }
1229
1230 static __poll_t vsock_poll_shutdown(struct sock *sk, u32 peer_shutdown)
1231 {
1232 __poll_t mask = 0;
1233
1234 /* INET sockets treat local write shutdown and peer write shutdown as a
1235 * case of EPOLLHUP set.
1236 */
1237 if (sk->sk_shutdown == SHUTDOWN_MASK ||
1238 ((sk->sk_shutdown & SEND_SHUTDOWN) &&
1239 (peer_shutdown & SEND_SHUTDOWN)))
1240 mask |= EPOLLHUP;
1241
1242 if (sk->sk_shutdown & RCV_SHUTDOWN ||
1243 peer_shutdown & SEND_SHUTDOWN)
1244 mask |= EPOLLRDHUP;
1245
1246 return mask;
1247 }
1248
1249 static __poll_t vsock_poll(struct file *file, struct socket *sock,
1250 poll_table *wait)
1251 {
1252 struct sock *sk;
1253 __poll_t mask;
1254 struct vsock_sock *vsk;
1255
1256 sk = sock->sk;
1257 vsk = vsock_sk(sk);
1258
1259 poll_wait(file, sk_sleep(sk), wait);
1260 mask = 0;
1261
1262 if (sk->sk_err || !skb_queue_empty_lockless(&sk->sk_error_queue))
1263 /* Signify that there has been an error on this socket. */
1264 mask |= EPOLLERR;
1265
1266 if (sk_is_readable(sk))
1267 mask |= EPOLLIN | EPOLLRDNORM;
1268
1269 if (sock->type == SOCK_DGRAM) {
1270 u32 peer_shutdown = READ_ONCE(vsk->peer_shutdown);
1271
1272 /* DGRAM sockets do not take lock_sock() in poll(), so use one
1273 * lockless snapshot for all shutdown-derived mask bits.
1274 */
1275 mask |= vsock_poll_shutdown(sk, peer_shutdown);
1276
1277 /* For datagram sockets we can read if there is something in
1278 * the queue and write as long as the socket isn't shutdown for
1279 * sending.
1280 */
1281 if (!skb_queue_empty_lockless(&sk->sk_receive_queue) ||
1282 (sk->sk_shutdown & RCV_SHUTDOWN)) {
1283 mask |= EPOLLIN | EPOLLRDNORM;
1284 }
1285
1286 if (!(sk->sk_shutdown & SEND_SHUTDOWN))
1287 mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
1288
1289 } else if (sock_type_connectible(sk->sk_type)) {
1290 const struct vsock_transport *transport;
1291 u32 peer_shutdown;
1292
1293 lock_sock(sk);
1294
1295 transport = vsk->transport;
1296
1297 /* Listening sockets that have connections in their accept
1298 * queue can be read.
1299 */
1300 if (sk->sk_state == TCP_LISTEN
1301 && !vsock_is_accept_queue_empty(sk))
1302 mask |= EPOLLIN | EPOLLRDNORM;
1303
1304 /* If there is something in the queue then we can read. */
1305 if (transport && transport->stream_is_active(vsk) &&
1306 !(sk->sk_shutdown & RCV_SHUTDOWN)) {
1307 bool data_ready_now = false;
1308 int target = sock_rcvlowat(sk, 0, INT_MAX);
1309 int ret = transport->notify_poll_in(
1310 vsk, target, &data_ready_now);
1311 if (ret < 0) {
1312 mask |= EPOLLERR;
1313 } else {
1314 if (data_ready_now)
1315 mask |= EPOLLIN | EPOLLRDNORM;
1316
1317 }
1318 }
1319
1320 /* Sockets whose connections have been closed, reset, or
1321 * terminated should also be considered read, and we check the
1322 * shutdown flag for that.
1323 */
1324 peer_shutdown = READ_ONCE(vsk->peer_shutdown);
1325 mask |= vsock_poll_shutdown(sk, peer_shutdown);
1326 if (sk->sk_shutdown & RCV_SHUTDOWN ||
1327 peer_shutdown & SEND_SHUTDOWN) {
1328 mask |= EPOLLIN | EPOLLRDNORM;
1329 }
1330
1331 /* Connected sockets that can produce data can be written. */
1332 if (transport && sk->sk_state == TCP_ESTABLISHED) {
1333 if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
1334 bool space_avail_now = false;
1335 int ret = transport->notify_poll_out(
1336 vsk, 1, &space_avail_now);
1337 if (ret < 0) {
1338 mask |= EPOLLERR;
1339 } else {
1340 if (space_avail_now)
1341 /* Remove EPOLLWRBAND since INET
1342 * sockets are not setting it.
1343 */
1344 mask |= EPOLLOUT | EPOLLWRNORM;
1345
1346 }
1347 }
1348 }
1349
1350 /* Simulate INET socket poll behaviors, which sets
1351 * EPOLLOUT|EPOLLWRNORM when peer is closed and nothing to read,
1352 * but local send is not shutdown.
1353 */
1354 if (sk->sk_state == TCP_CLOSE || sk->sk_state == TCP_CLOSING) {
1355 if (!(sk->sk_shutdown & SEND_SHUTDOWN))
1356 mask |= EPOLLOUT | EPOLLWRNORM;
1357
1358 }
1359
1360 release_sock(sk);
1361 }
1362
1363 return mask;
1364 }
1365
1366 static int vsock_read_skb(struct sock *sk, skb_read_actor_t read_actor)
1367 {
1368 struct vsock_sock *vsk = vsock_sk(sk);
1369
1370 if (WARN_ON_ONCE(!vsk->transport))
1371 return -ENODEV;
1372
1373 return vsk->transport->read_skb(vsk, read_actor);
1374 }
1375
1376 static int vsock_dgram_sendmsg(struct socket *sock, struct msghdr *msg,
1377 size_t len)
1378 {
1379 int err;
1380 struct sock *sk;
1381 struct vsock_sock *vsk;
1382 struct sockaddr_vm *remote_addr;
1383 const struct vsock_transport *transport;
1384
1385 if (msg->msg_flags & MSG_OOB)
1386 return -EOPNOTSUPP;
1387
1388 /* For now, MSG_DONTWAIT is always assumed... */
1389 err = 0;
1390 sk = sock->sk;
1391 vsk = vsock_sk(sk);
1392
1393 lock_sock(sk);
1394
1395 transport = vsk->transport;
1396
1397 err = vsock_auto_bind(vsk);
1398 if (err)
1399 goto out;
1400
1401
1402 /* If the provided message contains an address, use that. Otherwise
1403 * fall back on the socket's remote handle (if it has been connected).
1404 */
1405 if (msg->msg_name &&
1406 vsock_addr_cast(msg->msg_name, msg->msg_namelen,
1407 &remote_addr) == 0) {
1408 /* Ensure this address is of the right type and is a valid
1409 * destination.
1410 */
1411
1412 if (remote_addr->svm_cid == VMADDR_CID_ANY)
1413 remote_addr->svm_cid = transport->get_local_cid();
1414
1415 if (!vsock_addr_bound(remote_addr)) {
1416 err = -EINVAL;
1417 goto out;
1418 }
1419 } else if (sock->state == SS_CONNECTED) {
1420 remote_addr = &vsk->remote_addr;
1421
1422 if (remote_addr->svm_cid == VMADDR_CID_ANY)
1423 remote_addr->svm_cid = transport->get_local_cid();
1424
1425 /* XXX Should connect() or this function ensure remote_addr is
1426 * bound?
1427 */
1428 if (!vsock_addr_bound(&vsk->remote_addr)) {
1429 err = -EINVAL;
1430 goto out;
1431 }
1432 } else {
1433 err = -EINVAL;
1434 goto out;
1435 }
1436
1437 if (!transport->dgram_allow(vsk, remote_addr->svm_cid,
1438 remote_addr->svm_port)) {
1439 err = -EINVAL;
1440 goto out;
1441 }
1442
1443 err = transport->dgram_enqueue(vsk, remote_addr, msg, len);
1444
1445 out:
1446 release_sock(sk);
1447 return err;
1448 }
1449
1450 static int vsock_dgram_connect(struct socket *sock,
1451 struct sockaddr_unsized *addr, int addr_len, int flags)
1452 {
1453 int err;
1454 struct sock *sk;
1455 struct vsock_sock *vsk;
1456 struct sockaddr_vm *remote_addr;
1457
1458 sk = sock->sk;
1459 vsk = vsock_sk(sk);
1460
1461 err = vsock_addr_cast(addr, addr_len, &remote_addr);
1462 if (err == -EAFNOSUPPORT && remote_addr->svm_family == AF_UNSPEC) {
1463 lock_sock(sk);
1464 vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY,
1465 VMADDR_PORT_ANY);
1466 sock->state = SS_UNCONNECTED;
1467 release_sock(sk);
1468 return 0;
1469 } else if (err != 0)
1470 return -EINVAL;
1471
1472 lock_sock(sk);
1473
1474 err = vsock_auto_bind(vsk);
1475 if (err)
1476 goto out;
1477
1478 if (!vsk->transport->dgram_allow(vsk, remote_addr->svm_cid,
1479 remote_addr->svm_port)) {
1480 err = -EINVAL;
1481 goto out;
1482 }
1483
1484 memcpy(&vsk->remote_addr, remote_addr, sizeof(vsk->remote_addr));
1485 sock->state = SS_CONNECTED;
1486
1487 /* sock map disallows redirection of non-TCP sockets with sk_state !=
1488 * TCP_ESTABLISHED (see sock_map_redirect_allowed()), so we set
1489 * TCP_ESTABLISHED here to allow redirection of connected vsock dgrams.
1490 *
1491 * This doesn't seem to be abnormal state for datagram sockets, as the
1492 * same approach can be see in other datagram socket types as well
1493 * (such as unix sockets).
1494 */
1495 sk->sk_state = TCP_ESTABLISHED;
1496
1497 out:
1498 release_sock(sk);
1499 return err;
1500 }
1501
1502 int __vsock_dgram_recvmsg(struct socket *sock, struct msghdr *msg,
1503 size_t len, int flags)
1504 {
1505 struct sock *sk = sock->sk;
1506 struct vsock_sock *vsk = vsock_sk(sk);
1507
1508 return vsk->transport->dgram_dequeue(vsk, msg, len, flags);
1509 }
1510
1511 int vsock_dgram_recvmsg(struct socket *sock, struct msghdr *msg,
1512 size_t len, int flags)
1513 {
1514 #ifdef CONFIG_BPF_SYSCALL
1515 struct sock *sk = sock->sk;
1516 const struct proto *prot;
1517
1518 prot = READ_ONCE(sk->sk_prot);
1519 if (prot != &vsock_proto)
1520 return prot->recvmsg(sk, msg, len, flags, NULL);
1521 #endif
1522
1523 return __vsock_dgram_recvmsg(sock, msg, len, flags);
1524 }
1525 EXPORT_SYMBOL_GPL(vsock_dgram_recvmsg);
1526
1527 static int vsock_do_ioctl(struct socket *sock, unsigned int cmd,
1528 int __user *arg)
1529 {
1530 struct sock *sk = sock->sk;
1531 struct vsock_sock *vsk;
1532 int ret;
1533
1534 vsk = vsock_sk(sk);
1535
1536 switch (cmd) {
1537 case SIOCINQ: {
1538 ssize_t n_bytes;
1539
1540 if (!vsk->transport) {
1541 ret = -EOPNOTSUPP;
1542 break;
1543 }
1544
1545 if (sock_type_connectible(sk->sk_type) &&
1546 sk->sk_state == TCP_LISTEN) {
1547 ret = -EINVAL;
1548 break;
1549 }
1550
1551 n_bytes = vsock_stream_has_data(vsk);
1552 if (n_bytes < 0) {
1553 ret = n_bytes;
1554 break;
1555 }
1556 ret = put_user(n_bytes, arg);
1557 break;
1558 }
1559 case SIOCOUTQ: {
1560 ssize_t n_bytes;
1561
1562 if (!vsk->transport || !vsk->transport->unsent_bytes) {
1563 ret = -EOPNOTSUPP;
1564 break;
1565 }
1566
1567 if (sock_type_connectible(sk->sk_type) && sk->sk_state == TCP_LISTEN) {
1568 ret = -EINVAL;
1569 break;
1570 }
1571
1572 n_bytes = vsk->transport->unsent_bytes(vsk);
1573 if (n_bytes < 0) {
1574 ret = n_bytes;
1575 break;
1576 }
1577
1578 ret = put_user(n_bytes, arg);
1579 break;
1580 }
1581 default:
1582 ret = -ENOIOCTLCMD;
1583 }
1584
1585 return ret;
1586 }
1587
1588 static int vsock_ioctl(struct socket *sock, unsigned int cmd,
1589 unsigned long arg)
1590 {
1591 int ret;
1592
1593 lock_sock(sock->sk);
1594 ret = vsock_do_ioctl(sock, cmd, (int __user *)arg);
1595 release_sock(sock->sk);
1596
1597 return ret;
1598 }
1599
1600 static const struct proto_ops vsock_dgram_ops = {
1601 .family = PF_VSOCK,
1602 .owner = THIS_MODULE,
1603 .release = vsock_release,
1604 .bind = vsock_bind,
1605 .connect = vsock_dgram_connect,
1606 .socketpair = sock_no_socketpair,
1607 .accept = sock_no_accept,
1608 .getname = vsock_getname,
1609 .poll = vsock_poll,
1610 .ioctl = vsock_ioctl,
1611 .listen = sock_no_listen,
1612 .shutdown = vsock_shutdown,
1613 .sendmsg = vsock_dgram_sendmsg,
1614 .recvmsg = vsock_dgram_recvmsg,
1615 .mmap = sock_no_mmap,
1616 .read_skb = vsock_read_skb,
1617 };
1618
1619 static int vsock_transport_cancel_pkt(struct vsock_sock *vsk)
1620 {
1621 const struct vsock_transport *transport = vsk->transport;
1622
1623 if (!transport || !transport->cancel_pkt)
1624 return -EOPNOTSUPP;
1625
1626 return transport->cancel_pkt(vsk);
1627 }
1628
1629 static void vsock_connect_timeout(struct work_struct *work)
1630 {
1631 struct sock *sk;
1632 struct vsock_sock *vsk;
1633
1634 vsk = container_of(work, struct vsock_sock, connect_work.work);
1635 sk = sk_vsock(vsk);
1636
1637 lock_sock(sk);
1638 if (sk->sk_state == TCP_SYN_SENT &&
1639 (sk->sk_shutdown != SHUTDOWN_MASK)) {
1640 sk->sk_state = TCP_CLOSE;
1641 sk->sk_socket->state = SS_UNCONNECTED;
1642 sk->sk_err = ETIMEDOUT;
1643 sk_error_report(sk);
1644 vsock_transport_cancel_pkt(vsk);
1645 }
1646 release_sock(sk);
1647
1648 sock_put(sk);
1649 }
1650
1651 static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,
1652 int addr_len, int flags)
1653 {
1654 int err;
1655 struct sock *sk;
1656 struct vsock_sock *vsk;
1657 const struct vsock_transport *transport;
1658 struct sockaddr_vm *remote_addr;
1659 long timeout;
1660 DEFINE_WAIT(wait);
1661
1662 err = 0;
1663 sk = sock->sk;
1664 vsk = vsock_sk(sk);
1665
1666 lock_sock(sk);
1667
1668 /* XXX AF_UNSPEC should make us disconnect like AF_INET. */
1669 switch (sock->state) {
1670 case SS_CONNECTED:
1671 err = -EISCONN;
1672 goto out;
1673 case SS_DISCONNECTING:
1674 err = -EINVAL;
1675 goto out;
1676 case SS_CONNECTING:
1677 /* This continues on so we can move sock into the SS_CONNECTED
1678 * state once the connection has completed (at which point err
1679 * will be set to zero also). Otherwise, we will either wait
1680 * for the connection or return -EALREADY should this be a
1681 * non-blocking call.
1682 */
1683 err = -EALREADY;
1684 if (flags & O_NONBLOCK)
1685 goto out;
1686 break;
1687 default:
1688 if ((sk->sk_state == TCP_LISTEN) ||
1689 vsock_addr_cast(addr, addr_len, &remote_addr) != 0) {
1690 err = -EINVAL;
1691 goto out;
1692 }
1693
1694 /* Set the remote address that we are connecting to. */
1695 memcpy(&vsk->remote_addr, remote_addr,
1696 sizeof(vsk->remote_addr));
1697
1698 err = vsock_assign_transport(vsk, NULL);
1699 if (err)
1700 goto out;
1701
1702 transport = vsk->transport;
1703
1704 /* The hypervisor and well-known contexts do not have socket
1705 * endpoints.
1706 */
1707 if (!transport ||
1708 !transport->stream_allow(vsk, remote_addr->svm_cid,
1709 remote_addr->svm_port)) {
1710 err = -ENETUNREACH;
1711 goto out;
1712 }
1713
1714 if (vsock_msgzerocopy_allow(transport)) {
1715 set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags);
1716 } else if (sock_flag(sk, SOCK_ZEROCOPY)) {
1717 /* If this option was set before 'connect()',
1718 * when transport was unknown, check that this
1719 * feature is supported here.
1720 */
1721 err = -EOPNOTSUPP;
1722 goto out;
1723 }
1724
1725 err = vsock_auto_bind(vsk);
1726 if (err)
1727 goto out;
1728
1729 sk->sk_state = TCP_SYN_SENT;
1730
1731 err = transport->connect(vsk);
1732 if (err < 0)
1733 goto out;
1734
1735 /* sk_err might have been set as a result of an earlier
1736 * (failed) connect attempt.
1737 */
1738 sk->sk_err = 0;
1739
1740 /* Mark sock as connecting and set the error code to in
1741 * progress in case this is a non-blocking connect.
1742 */
1743 sock->state = SS_CONNECTING;
1744 err = -EINPROGRESS;
1745 }
1746
1747 /* The receive path will handle all communication until we are able to
1748 * enter the connected state. Here we wait for the connection to be
1749 * completed or a notification of an error.
1750 */
1751 timeout = vsk->connect_timeout;
1752 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1753
1754 /* If the socket is already closing or it is in an error state, there
1755 * is no point in waiting.
1756 */
1757 while (sk->sk_state != TCP_ESTABLISHED &&
1758 sk->sk_state != TCP_CLOSING && sk->sk_err == 0) {
1759 if (flags & O_NONBLOCK) {
1760 /* If we're not going to block, we schedule a timeout
1761 * function to generate a timeout on the connection
1762 * attempt, in case the peer doesn't respond in a
1763 * timely manner. We hold on to the socket until the
1764 * timeout fires.
1765 */
1766 sock_hold(sk);
1767
1768 /* If the timeout function is already scheduled,
1769 * reschedule it, then ungrab the socket refcount to
1770 * keep it balanced.
1771 */
1772 if (mod_delayed_work(system_percpu_wq, &vsk->connect_work,
1773 timeout))
1774 sock_put(sk);
1775
1776 /* Skip ahead to preserve error code set above. */
1777 goto out_wait;
1778 }
1779
1780 release_sock(sk);
1781 timeout = schedule_timeout(timeout);
1782 lock_sock(sk);
1783
1784 /* Connection established. Whatever happens to socket once we
1785 * release it, that's not connect()'s concern. No need to go
1786 * into signal and timeout handling. Call it a day.
1787 *
1788 * Note that allowing to "reset" an already established socket
1789 * here is racy and insecure.
1790 */
1791 if (sk->sk_state == TCP_ESTABLISHED)
1792 break;
1793
1794 /* If connection was _not_ established and a signal/timeout came
1795 * to be, we want the socket's state reset. User space may want
1796 * to retry.
1797 *
1798 * sk_state != TCP_ESTABLISHED implies that socket is not on
1799 * vsock_connected_table. We keep the binding and the transport
1800 * assigned.
1801 */
1802 if (signal_pending(current) || timeout == 0) {
1803 err = timeout == 0 ? -ETIMEDOUT : sock_intr_errno(timeout);
1804
1805 /* Listener might have already responded with
1806 * VIRTIO_VSOCK_OP_RESPONSE. Its handling expects our
1807 * sk_state == TCP_SYN_SENT, which hereby we break.
1808 * In such case VIRTIO_VSOCK_OP_RST will follow.
1809 */
1810 sk->sk_state = TCP_CLOSE;
1811 sock->state = SS_UNCONNECTED;
1812
1813 /* Try to cancel VIRTIO_VSOCK_OP_REQUEST skb sent out by
1814 * transport->connect().
1815 */
1816 vsock_transport_cancel_pkt(vsk);
1817
1818 goto out_wait;
1819 }
1820
1821 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1822 }
1823
1824 if (sk->sk_err) {
1825 err = -sk->sk_err;
1826 sk->sk_state = TCP_CLOSE;
1827 sock->state = SS_UNCONNECTED;
1828 } else {
1829 err = 0;
1830 }
1831
1832 out_wait:
1833 finish_wait(sk_sleep(sk), &wait);
1834 out:
1835 release_sock(sk);
1836 return err;
1837 }
1838
1839 static int vsock_accept(struct socket *sock, struct socket *newsock,
1840 struct proto_accept_arg *arg)
1841 {
1842 struct sock *listener;
1843 int err;
1844 struct sock *connected;
1845 struct vsock_sock *vconnected;
1846 long timeout;
1847 DEFINE_WAIT(wait);
1848
1849 err = 0;
1850 listener = sock->sk;
1851
1852 lock_sock(listener);
1853
1854 if (!sock_type_connectible(sock->type)) {
1855 err = -EOPNOTSUPP;
1856 goto out;
1857 }
1858
1859 if (listener->sk_state != TCP_LISTEN) {
1860 err = -EINVAL;
1861 goto out;
1862 }
1863
1864 /* Wait for children sockets to appear; these are the new sockets
1865 * created upon connection establishment.
1866 */
1867 timeout = sock_rcvtimeo(listener, arg->flags & O_NONBLOCK);
1868 prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);
1869
1870 while ((connected = vsock_dequeue_accept(listener)) == NULL &&
1871 listener->sk_err == 0) {
1872 release_sock(listener);
1873 timeout = schedule_timeout(timeout);
1874 finish_wait(sk_sleep(listener), &wait);
1875 lock_sock(listener);
1876
1877 if (signal_pending(current)) {
1878 err = sock_intr_errno(timeout);
1879 goto out;
1880 } else if (timeout == 0) {
1881 err = -EAGAIN;
1882 goto out;
1883 }
1884
1885 prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);
1886 }
1887 finish_wait(sk_sleep(listener), &wait);
1888
1889 if (listener->sk_err)
1890 err = -listener->sk_err;
1891
1892 if (connected) {
1893 sk_acceptq_removed(listener);
1894
1895 lock_sock_nested(connected, SINGLE_DEPTH_NESTING);
1896 vconnected = vsock_sk(connected);
1897
1898 /* If the listener socket has received an error, then we should
1899 * reject this socket and return. Note that we simply mark the
1900 * socket rejected, drop our reference, and let the cleanup
1901 * function handle the cleanup; the fact that we found it in
1902 * the listener's accept queue guarantees that the cleanup
1903 * function hasn't run yet.
1904 */
1905 if (err) {
1906 vconnected->rejected = true;
1907 } else {
1908 newsock->state = SS_CONNECTED;
1909 sock_graft(connected, newsock);
1910
1911 set_bit(SOCK_CUSTOM_SOCKOPT,
1912 &connected->sk_socket->flags);
1913
1914 if (vsock_msgzerocopy_allow(vconnected->transport))
1915 set_bit(SOCK_SUPPORT_ZC,
1916 &connected->sk_socket->flags);
1917 }
1918
1919 release_sock(connected);
1920 sock_put(connected);
1921 }
1922
1923 out:
1924 release_sock(listener);
1925 return err;
1926 }
1927
1928 static int vsock_listen(struct socket *sock, int backlog)
1929 {
1930 int err;
1931 struct sock *sk;
1932 struct vsock_sock *vsk;
1933
1934 sk = sock->sk;
1935
1936 lock_sock(sk);
1937
1938 if (!sock_type_connectible(sk->sk_type)) {
1939 err = -EOPNOTSUPP;
1940 goto out;
1941 }
1942
1943 if (sock->state != SS_UNCONNECTED) {
1944 err = -EINVAL;
1945 goto out;
1946 }
1947
1948 vsk = vsock_sk(sk);
1949
1950 if (!vsock_addr_bound(&vsk->local_addr)) {
1951 err = -EINVAL;
1952 goto out;
1953 }
1954
1955 sk->sk_max_ack_backlog = backlog;
1956 sk->sk_state = TCP_LISTEN;
1957
1958 err = 0;
1959
1960 out:
1961 release_sock(sk);
1962 return err;
1963 }
1964
1965 static void vsock_update_buffer_size(struct vsock_sock *vsk,
1966 const struct vsock_transport *transport,
1967 u64 val)
1968 {
1969 if (val < vsk->buffer_min_size)
1970 val = vsk->buffer_min_size;
1971
1972 if (val > vsk->buffer_max_size)
1973 val = vsk->buffer_max_size;
1974
1975 if (val != vsk->buffer_size &&
1976 transport && transport->notify_buffer_size)
1977 transport->notify_buffer_size(vsk, &val);
1978
1979 vsk->buffer_size = val;
1980 }
1981
1982 static int vsock_connectible_setsockopt(struct socket *sock,
1983 int level,
1984 int optname,
1985 sockptr_t optval,
1986 unsigned int optlen)
1987 {
1988 int err;
1989 struct sock *sk;
1990 struct vsock_sock *vsk;
1991 const struct vsock_transport *transport;
1992 u64 val;
1993
1994 if (level != AF_VSOCK && level != SOL_SOCKET)
1995 return -ENOPROTOOPT;
1996
1997 #define COPY_IN(_v) \
1998 do { \
1999 if (optlen < sizeof(_v)) { \
2000 err = -EINVAL; \
2001 goto exit; \
2002 } \
2003 if (copy_from_sockptr(&_v, optval, sizeof(_v)) != 0) { \
2004 err = -EFAULT; \
2005 goto exit; \
2006 } \
2007 } while (0)
2008
2009 err = 0;
2010 sk = sock->sk;
2011 vsk = vsock_sk(sk);
2012
2013 lock_sock(sk);
2014
2015 transport = vsk->transport;
2016
2017 if (level == SOL_SOCKET) {
2018 int zerocopy;
2019
2020 if (optname != SO_ZEROCOPY) {
2021 release_sock(sk);
2022 return sock_setsockopt(sock, level, optname, optval, optlen);
2023 }
2024
2025 /* Use 'int' type here, because variable to
2026 * set this option usually has this type.
2027 */
2028 COPY_IN(zerocopy);
2029
2030 if (zerocopy < 0 || zerocopy > 1) {
2031 err = -EINVAL;
2032 goto exit;
2033 }
2034
2035 if (transport && !vsock_msgzerocopy_allow(transport)) {
2036 err = -EOPNOTSUPP;
2037 goto exit;
2038 }
2039
2040 sock_valbool_flag(sk, SOCK_ZEROCOPY, zerocopy);
2041 goto exit;
2042 }
2043
2044 switch (optname) {
2045 case SO_VM_SOCKETS_BUFFER_SIZE:
2046 COPY_IN(val);
2047 vsock_update_buffer_size(vsk, transport, val);
2048 break;
2049
2050 case SO_VM_SOCKETS_BUFFER_MAX_SIZE:
2051 COPY_IN(val);
2052 vsk->buffer_max_size = val;
2053 vsock_update_buffer_size(vsk, transport, vsk->buffer_size);
2054 break;
2055
2056 case SO_VM_SOCKETS_BUFFER_MIN_SIZE:
2057 COPY_IN(val);
2058 vsk->buffer_min_size = val;
2059 vsock_update_buffer_size(vsk, transport, vsk->buffer_size);
2060 break;
2061
2062 case SO_VM_SOCKETS_CONNECT_TIMEOUT_NEW:
2063 case SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD: {
2064 struct __kernel_sock_timeval tv;
2065
2066 err = sock_copy_user_timeval(&tv, optval, optlen,
2067 optname == SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD);
2068 if (err)
2069 break;
2070 if (tv.tv_sec >= 0 && tv.tv_usec < USEC_PER_SEC &&
2071 tv.tv_sec < (MAX_SCHEDULE_TIMEOUT / HZ - 1)) {
2072 vsk->connect_timeout = tv.tv_sec * HZ +
2073 DIV_ROUND_UP((unsigned long)tv.tv_usec, (USEC_PER_SEC / HZ));
2074 if (vsk->connect_timeout == 0)
2075 vsk->connect_timeout =
2076 VSOCK_DEFAULT_CONNECT_TIMEOUT;
2077
2078 } else {
2079 err = -ERANGE;
2080 }
2081 break;
2082 }
2083
2084 default:
2085 err = -ENOPROTOOPT;
2086 break;
2087 }
2088
2089 #undef COPY_IN
2090
2091 exit:
2092 release_sock(sk);
2093 return err;
2094 }
2095
2096 static int vsock_connectible_getsockopt(struct socket *sock,
2097 int level, int optname,
2098 char __user *optval,
2099 int __user *optlen)
2100 {
2101 struct sock *sk = sock->sk;
2102 struct vsock_sock *vsk = vsock_sk(sk);
2103
2104 union {
2105 u64 val64;
2106 struct old_timeval32 tm32;
2107 struct __kernel_old_timeval tm;
2108 struct __kernel_sock_timeval stm;
2109 } v;
2110
2111 int lv = sizeof(v.val64);
2112 int len;
2113
2114 if (level != AF_VSOCK)
2115 return -ENOPROTOOPT;
2116
2117 if (get_user(len, optlen))
2118 return -EFAULT;
2119
2120 memset(&v, 0, sizeof(v));
2121
2122 switch (optname) {
2123 case SO_VM_SOCKETS_BUFFER_SIZE:
2124 v.val64 = vsk->buffer_size;
2125 break;
2126
2127 case SO_VM_SOCKETS_BUFFER_MAX_SIZE:
2128 v.val64 = vsk->buffer_max_size;
2129 break;
2130
2131 case SO_VM_SOCKETS_BUFFER_MIN_SIZE:
2132 v.val64 = vsk->buffer_min_size;
2133 break;
2134
2135 case SO_VM_SOCKETS_CONNECT_TIMEOUT_NEW:
2136 case SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD:
2137 lv = sock_get_timeout(vsk->connect_timeout, &v,
2138 optname == SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD);
2139 break;
2140
2141 default:
2142 return -ENOPROTOOPT;
2143 }
2144
2145 if (len < lv)
2146 return -EINVAL;
2147 if (len > lv)
2148 len = lv;
2149 if (copy_to_user(optval, &v, len))
2150 return -EFAULT;
2151
2152 if (put_user(len, optlen))
2153 return -EFAULT;
2154
2155 return 0;
2156 }
2157
2158 static int vsock_connectible_sendmsg(struct socket *sock, struct msghdr *msg,
2159 size_t len)
2160 {
2161 struct sock *sk;
2162 struct vsock_sock *vsk;
2163 const struct vsock_transport *transport;
2164 ssize_t total_written;
2165 long timeout;
2166 int err;
2167 struct vsock_transport_send_notify_data send_data;
2168 DEFINE_WAIT_FUNC(wait, woken_wake_function);
2169
2170 sk = sock->sk;
2171 vsk = vsock_sk(sk);
2172 total_written = 0;
2173 err = 0;
2174
2175 if (msg->msg_flags & MSG_OOB)
2176 return -EOPNOTSUPP;
2177
2178 lock_sock(sk);
2179
2180 transport = vsk->transport;
2181
2182 /* Callers should not provide a destination with connection oriented
2183 * sockets.
2184 */
2185 if (msg->msg_namelen) {
2186 err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
2187 goto out;
2188 }
2189
2190 /* Send data only if both sides are not shutdown in the direction. */
2191 if (sk->sk_shutdown & SEND_SHUTDOWN ||
2192 vsk->peer_shutdown & RCV_SHUTDOWN) {
2193 err = -EPIPE;
2194 goto out;
2195 }
2196
2197 if (!transport || sk->sk_state != TCP_ESTABLISHED ||
2198 !vsock_addr_bound(&vsk->local_addr)) {
2199 err = -ENOTCONN;
2200 goto out;
2201 }
2202
2203 if (!vsock_addr_bound(&vsk->remote_addr)) {
2204 err = -EDESTADDRREQ;
2205 goto out;
2206 }
2207
2208 if (msg->msg_flags & MSG_ZEROCOPY &&
2209 !vsock_msgzerocopy_allow(transport)) {
2210 err = -EOPNOTSUPP;
2211 goto out;
2212 }
2213
2214 /* Wait for room in the produce queue to enqueue our user's data. */
2215 timeout = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
2216
2217 err = transport->notify_send_init(vsk, &send_data);
2218 if (err < 0)
2219 goto out;
2220
2221 while (total_written < len) {
2222 ssize_t written;
2223
2224 add_wait_queue(sk_sleep(sk), &wait);
2225 while (vsock_stream_has_space(vsk) == 0 &&
2226 sk->sk_err == 0 &&
2227 !(sk->sk_shutdown & SEND_SHUTDOWN) &&
2228 !(vsk->peer_shutdown & RCV_SHUTDOWN)) {
2229
2230 /* Don't wait for non-blocking sockets. */
2231 if (timeout == 0) {
2232 err = -EAGAIN;
2233 remove_wait_queue(sk_sleep(sk), &wait);
2234 goto out_err;
2235 }
2236
2237 err = transport->notify_send_pre_block(vsk, &send_data);
2238 if (err < 0) {
2239 remove_wait_queue(sk_sleep(sk), &wait);
2240 goto out_err;
2241 }
2242
2243 release_sock(sk);
2244 timeout = wait_woken(&wait, TASK_INTERRUPTIBLE, timeout);
2245 lock_sock(sk);
2246 if (signal_pending(current)) {
2247 err = sock_intr_errno(timeout);
2248 remove_wait_queue(sk_sleep(sk), &wait);
2249 goto out_err;
2250 } else if (timeout == 0) {
2251 err = -EAGAIN;
2252 remove_wait_queue(sk_sleep(sk), &wait);
2253 goto out_err;
2254 }
2255 }
2256 remove_wait_queue(sk_sleep(sk), &wait);
2257
2258 /* These checks occur both as part of and after the loop
2259 * conditional since we need to check before and after
2260 * sleeping.
2261 */
2262 if (sk->sk_err) {
2263 err = -sk->sk_err;
2264 goto out_err;
2265 } else if ((sk->sk_shutdown & SEND_SHUTDOWN) ||
2266 (vsk->peer_shutdown & RCV_SHUTDOWN)) {
2267 err = -EPIPE;
2268 goto out_err;
2269 }
2270
2271 err = transport->notify_send_pre_enqueue(vsk, &send_data);
2272 if (err < 0)
2273 goto out_err;
2274
2275 /* Note that enqueue will only write as many bytes as are free
2276 * in the produce queue, so we don't need to ensure len is
2277 * smaller than the queue size. It is the caller's
2278 * responsibility to check how many bytes we were able to send.
2279 */
2280
2281 if (sk->sk_type == SOCK_SEQPACKET) {
2282 written = transport->seqpacket_enqueue(vsk,
2283 msg, len - total_written);
2284 } else {
2285 written = transport->stream_enqueue(vsk,
2286 msg, len - total_written);
2287 }
2288
2289 if (written < 0) {
2290 err = written;
2291 goto out_err;
2292 }
2293
2294 total_written += written;
2295
2296 err = transport->notify_send_post_enqueue(
2297 vsk, written, &send_data);
2298 if (err < 0)
2299 goto out_err;
2300
2301 }
2302
2303 out_err:
2304 if (total_written > 0) {
2305 /* Return number of written bytes only if:
2306 * 1) SOCK_STREAM socket.
2307 * 2) SOCK_SEQPACKET socket when whole buffer is sent.
2308 */
2309 if (sk->sk_type == SOCK_STREAM || total_written == len)
2310 err = total_written;
2311 }
2312 out:
2313 if (sk->sk_type == SOCK_STREAM)
2314 err = sk_stream_error(sk, msg->msg_flags, err);
2315
2316 release_sock(sk);
2317 return err;
2318 }
2319
2320 static int vsock_connectible_wait_data(struct sock *sk,
2321 struct wait_queue_entry *wait,
2322 long timeout,
2323 struct vsock_transport_recv_notify_data *recv_data,
2324 size_t target)
2325 {
2326 const struct vsock_transport *transport;
2327 struct vsock_sock *vsk;
2328 s64 data;
2329 int err;
2330
2331 vsk = vsock_sk(sk);
2332 err = 0;
2333 transport = vsk->transport;
2334
2335 while (1) {
2336 prepare_to_wait(sk_sleep(sk), wait, TASK_INTERRUPTIBLE);
2337 data = vsock_connectible_has_data(vsk);
2338 if (data != 0)
2339 break;
2340
2341 if (sk->sk_err != 0 ||
2342 (sk->sk_shutdown & RCV_SHUTDOWN) ||
2343 (vsk->peer_shutdown & SEND_SHUTDOWN)) {
2344 break;
2345 }
2346
2347 /* Don't wait for non-blocking sockets. */
2348 if (timeout == 0) {
2349 err = -EAGAIN;
2350 break;
2351 }
2352
2353 if (recv_data) {
2354 err = transport->notify_recv_pre_block(vsk, target, recv_data);
2355 if (err < 0)
2356 break;
2357 }
2358
2359 release_sock(sk);
2360 timeout = schedule_timeout(timeout);
2361 lock_sock(sk);
2362
2363 if (signal_pending(current)) {
2364 err = sock_intr_errno(timeout);
2365 break;
2366 } else if (timeout == 0) {
2367 err = -EAGAIN;
2368 break;
2369 }
2370 }
2371
2372 finish_wait(sk_sleep(sk), wait);
2373
2374 if (err)
2375 return err;
2376
2377 /* Internal transport error when checking for available
2378 * data. XXX This should be changed to a connection
2379 * reset in a later change.
2380 */
2381 if (data < 0)
2382 return -ENOMEM;
2383
2384 return data;
2385 }
2386
2387 static int __vsock_stream_recvmsg(struct sock *sk, struct msghdr *msg,
2388 size_t len, int flags)
2389 {
2390 struct vsock_transport_recv_notify_data recv_data;
2391 const struct vsock_transport *transport;
2392 struct vsock_sock *vsk;
2393 ssize_t copied;
2394 size_t target;
2395 long timeout;
2396 int err;
2397
2398 DEFINE_WAIT(wait);
2399
2400 vsk = vsock_sk(sk);
2401 transport = vsk->transport;
2402
2403 /* We must not copy less than target bytes into the user's buffer
2404 * before returning successfully, so we wait for the consume queue to
2405 * have that much data to consume before dequeueing. Note that this
2406 * makes it impossible to handle cases where target is greater than the
2407 * queue size.
2408 */
2409 target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
2410 if (target >= transport->stream_rcvhiwat(vsk)) {
2411 err = -ENOMEM;
2412 goto out;
2413 }
2414 timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2415 copied = 0;
2416
2417 err = transport->notify_recv_init(vsk, target, &recv_data);
2418 if (err < 0)
2419 goto out;
2420
2421
2422 while (1) {
2423 ssize_t read;
2424
2425 err = vsock_connectible_wait_data(sk, &wait, timeout,
2426 &recv_data, target);
2427 if (err <= 0)
2428 break;
2429
2430 err = transport->notify_recv_pre_dequeue(vsk, target,
2431 &recv_data);
2432 if (err < 0)
2433 break;
2434
2435 read = transport->stream_dequeue(vsk, msg, len - copied, flags);
2436 if (read < 0) {
2437 err = read;
2438 break;
2439 }
2440
2441 copied += read;
2442
2443 err = transport->notify_recv_post_dequeue(vsk, target, read,
2444 !(flags & MSG_PEEK), &recv_data);
2445 if (err < 0)
2446 goto out;
2447
2448 if (read >= target || flags & MSG_PEEK)
2449 break;
2450
2451 target -= read;
2452 }
2453
2454 if (sk->sk_err)
2455 err = -sk->sk_err;
2456 else if (sk->sk_shutdown & RCV_SHUTDOWN)
2457 err = 0;
2458
2459 if (copied > 0)
2460 err = copied;
2461
2462 out:
2463 return err;
2464 }
2465
2466 static int __vsock_seqpacket_recvmsg(struct sock *sk, struct msghdr *msg,
2467 size_t len, int flags)
2468 {
2469 const struct vsock_transport *transport;
2470 struct vsock_sock *vsk;
2471 ssize_t msg_len;
2472 long timeout;
2473 int err = 0;
2474 DEFINE_WAIT(wait);
2475
2476 vsk = vsock_sk(sk);
2477 transport = vsk->transport;
2478
2479 timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2480
2481 err = vsock_connectible_wait_data(sk, &wait, timeout, NULL, 0);
2482 if (err <= 0)
2483 goto out;
2484
2485 msg_len = transport->seqpacket_dequeue(vsk, msg, flags);
2486
2487 if (msg_len < 0) {
2488 err = msg_len;
2489 goto out;
2490 }
2491
2492 if (sk->sk_err) {
2493 err = -sk->sk_err;
2494 } else if (sk->sk_shutdown & RCV_SHUTDOWN) {
2495 err = 0;
2496 } else {
2497 /* User sets MSG_TRUNC, so return real length of
2498 * packet.
2499 */
2500 if (flags & MSG_TRUNC)
2501 err = msg_len;
2502 else
2503 err = len - msg_data_left(msg);
2504
2505 /* Always set MSG_TRUNC if real length of packet is
2506 * bigger than user's buffer.
2507 */
2508 if (msg_len > len)
2509 msg->msg_flags |= MSG_TRUNC;
2510 }
2511
2512 out:
2513 return err;
2514 }
2515
2516 int
2517 __vsock_connectible_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
2518 int flags)
2519 {
2520 struct sock *sk;
2521 struct vsock_sock *vsk;
2522 const struct vsock_transport *transport;
2523 int err;
2524
2525 sk = sock->sk;
2526
2527 if (unlikely(flags & MSG_ERRQUEUE))
2528 return sock_recv_errqueue(sk, msg, len, SOL_VSOCK, VSOCK_RECVERR);
2529
2530 vsk = vsock_sk(sk);
2531 err = 0;
2532
2533 lock_sock(sk);
2534
2535 transport = vsk->transport;
2536
2537 if (!transport || sk->sk_state != TCP_ESTABLISHED) {
2538 /* Recvmsg is supposed to return 0 if a peer performs an
2539 * orderly shutdown. Differentiate between that case and when a
2540 * peer has not connected or a local shutdown occurred with the
2541 * SOCK_DONE flag.
2542 */
2543 if (sock_flag(sk, SOCK_DONE))
2544 err = 0;
2545 else
2546 err = -ENOTCONN;
2547
2548 goto out;
2549 }
2550
2551 if (flags & MSG_OOB) {
2552 err = -EOPNOTSUPP;
2553 goto out;
2554 }
2555
2556 /* We don't check peer_shutdown flag here since peer may actually shut
2557 * down, but there can be data in the queue that a local socket can
2558 * receive.
2559 */
2560 if (sk->sk_shutdown & RCV_SHUTDOWN) {
2561 err = 0;
2562 goto out;
2563 }
2564
2565 /* It is valid on Linux to pass in a zero-length receive buffer. This
2566 * is not an error. We may as well bail out now.
2567 */
2568 if (!len) {
2569 err = 0;
2570 goto out;
2571 }
2572
2573 if (sk->sk_type == SOCK_STREAM)
2574 err = __vsock_stream_recvmsg(sk, msg, len, flags);
2575 else
2576 err = __vsock_seqpacket_recvmsg(sk, msg, len, flags);
2577
2578 out:
2579 release_sock(sk);
2580 return err;
2581 }
2582
2583 int
2584 vsock_connectible_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
2585 int flags)
2586 {
2587 #ifdef CONFIG_BPF_SYSCALL
2588 struct sock *sk = sock->sk;
2589 const struct proto *prot;
2590
2591 prot = READ_ONCE(sk->sk_prot);
2592 if (prot != &vsock_proto)
2593 return prot->recvmsg(sk, msg, len, flags, NULL);
2594 #endif
2595
2596 return __vsock_connectible_recvmsg(sock, msg, len, flags);
2597 }
2598 EXPORT_SYMBOL_GPL(vsock_connectible_recvmsg);
2599
2600 static int vsock_set_rcvlowat(struct sock *sk, int val)
2601 {
2602 const struct vsock_transport *transport;
2603 struct vsock_sock *vsk;
2604
2605 vsk = vsock_sk(sk);
2606
2607 if (val > vsk->buffer_size)
2608 return -EINVAL;
2609
2610 transport = vsk->transport;
2611
2612 if (transport && transport->notify_set_rcvlowat) {
2613 int err;
2614
2615 err = transport->notify_set_rcvlowat(vsk, val);
2616 if (err)
2617 return err;
2618 }
2619
2620 WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
2621 return 0;
2622 }
2623
2624 static const struct proto_ops vsock_stream_ops = {
2625 .family = PF_VSOCK,
2626 .owner = THIS_MODULE,
2627 .release = vsock_release,
2628 .bind = vsock_bind,
2629 .connect = vsock_connect,
2630 .socketpair = sock_no_socketpair,
2631 .accept = vsock_accept,
2632 .getname = vsock_getname,
2633 .poll = vsock_poll,
2634 .ioctl = vsock_ioctl,
2635 .listen = vsock_listen,
2636 .shutdown = vsock_shutdown,
2637 .setsockopt = vsock_connectible_setsockopt,
2638 .getsockopt = vsock_connectible_getsockopt,
2639 .sendmsg = vsock_connectible_sendmsg,
2640 .recvmsg = vsock_connectible_recvmsg,
2641 .mmap = sock_no_mmap,
2642 .set_rcvlowat = vsock_set_rcvlowat,
2643 .read_skb = vsock_read_skb,
2644 };
2645
2646 static const struct proto_ops vsock_seqpacket_ops = {
2647 .family = PF_VSOCK,
2648 .owner = THIS_MODULE,
2649 .release = vsock_release,
2650 .bind = vsock_bind,
2651 .connect = vsock_connect,
2652 .socketpair = sock_no_socketpair,
2653 .accept = vsock_accept,
2654 .getname = vsock_getname,
2655 .poll = vsock_poll,
2656 .ioctl = vsock_ioctl,
2657 .listen = vsock_listen,
2658 .shutdown = vsock_shutdown,
2659 .setsockopt = vsock_connectible_setsockopt,
2660 .getsockopt = vsock_connectible_getsockopt,
2661 .sendmsg = vsock_connectible_sendmsg,
2662 .recvmsg = vsock_connectible_recvmsg,
2663 .mmap = sock_no_mmap,
2664 .read_skb = vsock_read_skb,
2665 };
2666
2667 static int vsock_create(struct net *net, struct socket *sock,
2668 int protocol, int kern)
2669 {
2670 struct vsock_sock *vsk;
2671 struct sock *sk;
2672 int ret;
2673
2674 if (!sock)
2675 return -EINVAL;
2676
2677 if (protocol && protocol != PF_VSOCK)
2678 return -EPROTONOSUPPORT;
2679
2680 switch (sock->type) {
2681 case SOCK_DGRAM:
2682 sock->ops = &vsock_dgram_ops;
2683 break;
2684 case SOCK_STREAM:
2685 sock->ops = &vsock_stream_ops;
2686 break;
2687 case SOCK_SEQPACKET:
2688 sock->ops = &vsock_seqpacket_ops;
2689 break;
2690 default:
2691 return -ESOCKTNOSUPPORT;
2692 }
2693
2694 sock->state = SS_UNCONNECTED;
2695
2696 sk = __vsock_create(net, sock, NULL, GFP_KERNEL, 0, kern);
2697 if (!sk)
2698 return -ENOMEM;
2699
2700 vsk = vsock_sk(sk);
2701
2702 if (sock->type == SOCK_DGRAM) {
2703 ret = vsock_assign_transport(vsk, NULL);
2704 if (ret < 0) {
2705 sock->sk = NULL;
2706 sock_put(sk);
2707 return ret;
2708 }
2709 }
2710
2711 /* SOCK_DGRAM doesn't have 'setsockopt' callback set in its
2712 * proto_ops, so there is no handler for custom logic.
2713 */
2714 if (sock_type_connectible(sock->type))
2715 set_bit(SOCK_CUSTOM_SOCKOPT, &sk->sk_socket->flags);
2716
2717 vsock_insert_unbound(vsk);
2718
2719 return 0;
2720 }
2721
2722 static const struct net_proto_family vsock_family_ops = {
2723 .family = AF_VSOCK,
2724 .create = vsock_create,
2725 .owner = THIS_MODULE,
2726 };
2727
2728 static long vsock_dev_do_ioctl(struct file *filp,
2729 unsigned int cmd, void __user *ptr)
2730 {
2731 u32 __user *p = ptr;
2732 int retval = 0;
2733 u32 cid;
2734
2735 switch (cmd) {
2736 case IOCTL_VM_SOCKETS_GET_LOCAL_CID:
2737 /* To be compatible with the VMCI behavior, we prioritize the
2738 * guest CID instead of well-know host CID (VMADDR_CID_HOST).
2739 */
2740 cid = vsock_registered_transport_cid(&transport_g2h);
2741 if (cid == VMADDR_CID_ANY)
2742 cid = vsock_registered_transport_cid(&transport_h2g);
2743 if (cid == VMADDR_CID_ANY)
2744 cid = vsock_registered_transport_cid(&transport_local);
2745
2746 if (put_user(cid, p) != 0)
2747 retval = -EFAULT;
2748 break;
2749
2750 default:
2751 retval = -ENOIOCTLCMD;
2752 }
2753
2754 return retval;
2755 }
2756
2757 static long vsock_dev_ioctl(struct file *filp,
2758 unsigned int cmd, unsigned long arg)
2759 {
2760 return vsock_dev_do_ioctl(filp, cmd, (void __user *)arg);
2761 }
2762
2763 #ifdef CONFIG_COMPAT
2764 static long vsock_dev_compat_ioctl(struct file *filp,
2765 unsigned int cmd, unsigned long arg)
2766 {
2767 return vsock_dev_do_ioctl(filp, cmd, compat_ptr(arg));
2768 }
2769 #endif
2770
2771 static const struct file_operations vsock_device_ops = {
2772 .owner = THIS_MODULE,
2773 .unlocked_ioctl = vsock_dev_ioctl,
2774 #ifdef CONFIG_COMPAT
2775 .compat_ioctl = vsock_dev_compat_ioctl,
2776 #endif
2777 .open = nonseekable_open,
2778 };
2779
2780 static struct miscdevice vsock_device = {
2781 .name = "vsock",
2782 .fops = &vsock_device_ops,
2783 };
2784
2785 static int __vsock_net_mode_string(const struct ctl_table *table, int write,
2786 void *buffer, size_t *lenp, loff_t *ppos,
2787 enum vsock_net_mode mode,
2788 enum vsock_net_mode *new_mode)
2789 {
2790 char data[VSOCK_NET_MODE_STR_MAX] = {0};
2791 struct ctl_table tmp;
2792 int ret;
2793
2794 if (!table->data || !table->maxlen || !*lenp) {
2795 *lenp = 0;
2796 return 0;
2797 }
2798
2799 tmp = *table;
2800 tmp.data = data;
2801
2802 if (!write) {
2803 const char *p;
2804
2805 switch (mode) {
2806 case VSOCK_NET_MODE_GLOBAL:
2807 p = VSOCK_NET_MODE_STR_GLOBAL;
2808 break;
2809 case VSOCK_NET_MODE_LOCAL:
2810 p = VSOCK_NET_MODE_STR_LOCAL;
2811 break;
2812 default:
2813 WARN_ONCE(true, "netns has invalid vsock mode");
2814 *lenp = 0;
2815 return 0;
2816 }
2817
2818 strscpy(data, p, sizeof(data));
2819 tmp.maxlen = strlen(p);
2820 }
2821
2822 ret = proc_dostring(&tmp, write, buffer, lenp, ppos);
2823 if (ret || !write)
2824 return ret;
2825
2826 if (*lenp >= sizeof(data))
2827 return -EINVAL;
2828
2829 if (!strncmp(data, VSOCK_NET_MODE_STR_GLOBAL, sizeof(data)))
2830 *new_mode = VSOCK_NET_MODE_GLOBAL;
2831 else if (!strncmp(data, VSOCK_NET_MODE_STR_LOCAL, sizeof(data)))
2832 *new_mode = VSOCK_NET_MODE_LOCAL;
2833 else
2834 return -EINVAL;
2835
2836 return 0;
2837 }
2838
2839 static int vsock_net_mode_string(const struct ctl_table *table, int write,
2840 void *buffer, size_t *lenp, loff_t *ppos)
2841 {
2842 struct net *net;
2843
2844 if (write)
2845 return -EPERM;
2846
2847 net = container_of(table->data, struct net, vsock.mode);
2848
2849 return __vsock_net_mode_string(table, write, buffer, lenp, ppos,
2850 vsock_net_mode(net), NULL);
2851 }
2852
2853 static int vsock_net_child_mode_string(const struct ctl_table *table, int write,
2854 void *buffer, size_t *lenp, loff_t *ppos)
2855 {
2856 enum vsock_net_mode new_mode;
2857 struct net *net;
2858 int ret;
2859
2860 net = container_of(table->data, struct net, vsock.child_ns_mode);
2861
2862 ret = __vsock_net_mode_string(table, write, buffer, lenp, ppos,
2863 vsock_net_child_mode(net), &new_mode);
2864 if (ret)
2865 return ret;
2866
2867 if (write) {
2868 /* Prevent a "local" namespace from escalating to "global",
2869 * which would give nested namespaces access to global CIDs.
2870 */
2871 if (vsock_net_mode(net) == VSOCK_NET_MODE_LOCAL &&
2872 new_mode == VSOCK_NET_MODE_GLOBAL)
2873 return -EPERM;
2874
2875 if (!vsock_net_set_child_mode(net, new_mode))
2876 return -EBUSY;
2877 }
2878
2879 return 0;
2880 }
2881
2882 static struct ctl_table vsock_table[] = {
2883 {
2884 .procname = "ns_mode",
2885 .data = &init_net.vsock.mode,
2886 .maxlen = VSOCK_NET_MODE_STR_MAX,
2887 .mode = 0444,
2888 .proc_handler = vsock_net_mode_string
2889 },
2890 {
2891 .procname = "child_ns_mode",
2892 .data = &init_net.vsock.child_ns_mode,
2893 .maxlen = VSOCK_NET_MODE_STR_MAX,
2894 .mode = 0644,
2895 .proc_handler = vsock_net_child_mode_string
2896 },
2897 };
2898
2899 static int __net_init vsock_sysctl_register(struct net *net)
2900 {
2901 struct ctl_table *table;
2902
2903 if (net_eq(net, &init_net)) {
2904 table = vsock_table;
2905 } else {
2906 table = kmemdup(vsock_table, sizeof(vsock_table), GFP_KERNEL);
2907 if (!table)
2908 goto err_alloc;
2909
2910 table[0].data = &net->vsock.mode;
2911 table[1].data = &net->vsock.child_ns_mode;
2912 }
2913
2914 net->vsock.sysctl_hdr = register_net_sysctl_sz(net, "net/vsock", table,
2915 ARRAY_SIZE(vsock_table));
2916 if (!net->vsock.sysctl_hdr)
2917 goto err_reg;
2918
2919 return 0;
2920
2921 err_reg:
2922 if (!net_eq(net, &init_net))
2923 kfree(table);
2924 err_alloc:
2925 return -ENOMEM;
2926 }
2927
2928 static void vsock_sysctl_unregister(struct net *net)
2929 {
2930 const struct ctl_table *table;
2931
2932 table = net->vsock.sysctl_hdr->ctl_table_arg;
2933 unregister_net_sysctl_table(net->vsock.sysctl_hdr);
2934 if (!net_eq(net, &init_net))
2935 kfree(table);
2936 }
2937
2938 static void vsock_net_init(struct net *net)
2939 {
2940 if (net_eq(net, &init_net))
2941 net->vsock.mode = VSOCK_NET_MODE_GLOBAL;
2942 else
2943 net->vsock.mode = vsock_net_child_mode(current->nsproxy->net_ns);
2944
2945 net->vsock.child_ns_mode = net->vsock.mode;
2946 net->vsock.child_ns_mode_locked = 0;
2947 }
2948
2949 static __net_init int vsock_sysctl_init_net(struct net *net)
2950 {
2951 vsock_net_init(net);
2952
2953 if (vsock_sysctl_register(net))
2954 return -ENOMEM;
2955
2956 return 0;
2957 }
2958
2959 static __net_exit void vsock_sysctl_exit_net(struct net *net)
2960 {
2961 vsock_sysctl_unregister(net);
2962 }
2963
2964 static struct pernet_operations vsock_sysctl_ops = {
2965 .init = vsock_sysctl_init_net,
2966 .exit = vsock_sysctl_exit_net,
2967 };
2968
2969 static int __init vsock_init(void)
2970 {
2971 int err = 0;
2972
2973 vsock_init_tables();
2974
2975 vsock_proto.owner = THIS_MODULE;
2976 vsock_device.minor = MISC_DYNAMIC_MINOR;
2977 err = misc_register(&vsock_device);
2978 if (err) {
2979 pr_err("Failed to register misc device\n");
2980 goto err_reset_transport;
2981 }
2982
2983 err = proto_register(&vsock_proto, 1); /* we want our slab */
2984 if (err) {
2985 pr_err("Cannot register vsock protocol\n");
2986 goto err_deregister_misc;
2987 }
2988
2989 err = sock_register(&vsock_family_ops);
2990 if (err) {
2991 pr_err("could not register af_vsock (%d) address family: %d\n",
2992 AF_VSOCK, err);
2993 goto err_unregister_proto;
2994 }
2995
2996 if (register_pernet_subsys(&vsock_sysctl_ops)) {
2997 err = -ENOMEM;
2998 goto err_unregister_sock;
2999 }
3000
3001 vsock_bpf_build_proto();
3002
3003 return 0;
3004
3005 err_unregister_sock:
3006 sock_unregister(AF_VSOCK);
3007 err_unregister_proto:
3008 proto_unregister(&vsock_proto);
3009 err_deregister_misc:
3010 misc_deregister(&vsock_device);
3011 err_reset_transport:
3012 return err;
3013 }
3014
3015 static void __exit vsock_exit(void)
3016 {
3017 misc_deregister(&vsock_device);
3018 sock_unregister(AF_VSOCK);
3019 proto_unregister(&vsock_proto);
3020 unregister_pernet_subsys(&vsock_sysctl_ops);
3021 }
3022
3023 const struct vsock_transport *vsock_core_get_transport(struct vsock_sock *vsk)
3024 {
3025 return vsk->transport;
3026 }
3027 EXPORT_SYMBOL_GPL(vsock_core_get_transport);
3028
3029 int vsock_core_register(const struct vsock_transport *t, int features)
3030 {
3031 const struct vsock_transport *t_h2g, *t_g2h, *t_dgram, *t_local;
3032 int err = mutex_lock_interruptible(&vsock_register_mutex);
3033
3034 if (err)
3035 return err;
3036
3037 t_h2g = transport_h2g;
3038 t_g2h = transport_g2h;
3039 t_dgram = transport_dgram;
3040 t_local = transport_local;
3041
3042 if (features & VSOCK_TRANSPORT_F_H2G) {
3043 if (t_h2g) {
3044 err = -EBUSY;
3045 goto err_busy;
3046 }
3047 t_h2g = t;
3048 }
3049
3050 if (features & VSOCK_TRANSPORT_F_G2H) {
3051 if (t_g2h) {
3052 err = -EBUSY;
3053 goto err_busy;
3054 }
3055 t_g2h = t;
3056 }
3057
3058 if (features & VSOCK_TRANSPORT_F_DGRAM) {
3059 if (t_dgram) {
3060 err = -EBUSY;
3061 goto err_busy;
3062 }
3063 t_dgram = t;
3064 }
3065
3066 if (features & VSOCK_TRANSPORT_F_LOCAL) {
3067 if (t_local) {
3068 err = -EBUSY;
3069 goto err_busy;
3070 }
3071 t_local = t;
3072 }
3073
3074 transport_h2g = t_h2g;
3075 transport_g2h = t_g2h;
3076 transport_dgram = t_dgram;
3077 transport_local = t_local;
3078
3079 err_busy:
3080 mutex_unlock(&vsock_register_mutex);
3081 return err;
3082 }
3083 EXPORT_SYMBOL_GPL(vsock_core_register);
3084
3085 void vsock_core_unregister(const struct vsock_transport *t)
3086 {
3087 mutex_lock(&vsock_register_mutex);
3088
3089 if (transport_h2g == t)
3090 transport_h2g = NULL;
3091
3092 if (transport_g2h == t)
3093 transport_g2h = NULL;
3094
3095 if (transport_dgram == t)
3096 transport_dgram = NULL;
3097
3098 if (transport_local == t)
3099 transport_local = NULL;
3100
3101 mutex_unlock(&vsock_register_mutex);
3102 }
3103 EXPORT_SYMBOL_GPL(vsock_core_unregister);
3104
3105 module_init(vsock_init);
3106 module_exit(vsock_exit);
3107
3108 MODULE_AUTHOR("VMware, Inc.");
3109 MODULE_DESCRIPTION("VMware Virtual Socket Family");
3110 MODULE_VERSION("1.0.2.0-k");
3111 MODULE_LICENSE("GPL v2");