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
88 #include <linux/types.h>
89 #include <linux/bitops.h>
90 #include <linux/cred.h>
91 #include <linux/init.h>
92 #include <linux/io.h>
93 #include <linux/kernel.h>
94 #include <linux/sched/signal.h>
95 #include <linux/kmod.h>
96 #include <linux/list.h>
97 #include <linux/miscdevice.h>
98 #include <linux/module.h>
99 #include <linux/mutex.h>
100 #include <linux/net.h>
101 #include <linux/poll.h>
102 #include <linux/random.h>
103 #include <linux/skbuff.h>
104 #include <linux/smp.h>
105 #include <linux/socket.h>
106 #include <linux/stddef.h>
107 #include <linux/unistd.h>
108 #include <linux/wait.h>
109 #include <linux/workqueue.h>
110 #include <net/sock.h>
111 #include <net/af_vsock.h>
112
113 static int __vsock_bind(struct sock *sk, struct sockaddr_vm *addr);
114 static void vsock_sk_destruct(struct sock *sk);
115 static int vsock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb);
116
117 /* Protocol family. */
118 static struct proto vsock_proto = {
119 .name = "AF_VSOCK",
120 .owner = THIS_MODULE,
121 .obj_size = sizeof(struct vsock_sock),
122 };
123
124 /* The default peer timeout indicates how long we will wait for a peer response
125 * to a control message.
126 */
127 #define VSOCK_DEFAULT_CONNECT_TIMEOUT (2 * HZ)
128
129 static const struct vsock_transport *transport;
130 static DEFINE_MUTEX(vsock_register_mutex);
131
132 /**** EXPORTS ****/
133
134 /* Get the ID of the local context. This is transport dependent. */
135
vm_sockets_get_local_cid(void)136 int vm_sockets_get_local_cid(void)
137 {
138 return transport->get_local_cid();
139 }
140 EXPORT_SYMBOL_GPL(vm_sockets_get_local_cid);
141
142 /**** UTILS ****/
143
144 /* Each bound VSocket is stored in the bind hash table and each connected
145 * VSocket is stored in the connected hash table.
146 *
147 * Unbound sockets are all put on the same list attached to the end of the hash
148 * table (vsock_unbound_sockets). Bound sockets are added to the hash table in
149 * the bucket that their local address hashes to (vsock_bound_sockets(addr)
150 * represents the list that addr hashes to).
151 *
152 * Specifically, we initialize the vsock_bind_table array to a size of
153 * VSOCK_HASH_SIZE + 1 so that vsock_bind_table[0] through
154 * vsock_bind_table[VSOCK_HASH_SIZE - 1] are for bound sockets and
155 * vsock_bind_table[VSOCK_HASH_SIZE] is for unbound sockets. The hash function
156 * mods with VSOCK_HASH_SIZE to ensure this.
157 */
158 #define MAX_PORT_RETRIES 24
159
160 #define VSOCK_HASH(addr) ((addr)->svm_port % VSOCK_HASH_SIZE)
161 #define vsock_bound_sockets(addr) (&vsock_bind_table[VSOCK_HASH(addr)])
162 #define vsock_unbound_sockets (&vsock_bind_table[VSOCK_HASH_SIZE])
163
164 /* XXX This can probably be implemented in a better way. */
165 #define VSOCK_CONN_HASH(src, dst) \
166 (((src)->svm_cid ^ (dst)->svm_port) % VSOCK_HASH_SIZE)
167 #define vsock_connected_sockets(src, dst) \
168 (&vsock_connected_table[VSOCK_CONN_HASH(src, dst)])
169 #define vsock_connected_sockets_vsk(vsk) \
170 vsock_connected_sockets(&(vsk)->remote_addr, &(vsk)->local_addr)
171
172 struct list_head vsock_bind_table[VSOCK_HASH_SIZE + 1];
173 EXPORT_SYMBOL_GPL(vsock_bind_table);
174 struct list_head vsock_connected_table[VSOCK_HASH_SIZE];
175 EXPORT_SYMBOL_GPL(vsock_connected_table);
176 DEFINE_SPINLOCK(vsock_table_lock);
177 EXPORT_SYMBOL_GPL(vsock_table_lock);
178
179 /* Autobind this socket to the local address if necessary. */
vsock_auto_bind(struct vsock_sock * vsk)180 static int vsock_auto_bind(struct vsock_sock *vsk)
181 {
182 struct sock *sk = sk_vsock(vsk);
183 struct sockaddr_vm local_addr;
184
185 if (vsock_addr_bound(&vsk->local_addr))
186 return 0;
187 vsock_addr_init(&local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
188 return __vsock_bind(sk, &local_addr);
189 }
190
vsock_init_tables(void)191 static int __init vsock_init_tables(void)
192 {
193 int i;
194
195 for (i = 0; i < ARRAY_SIZE(vsock_bind_table); i++)
196 INIT_LIST_HEAD(&vsock_bind_table[i]);
197
198 for (i = 0; i < ARRAY_SIZE(vsock_connected_table); i++)
199 INIT_LIST_HEAD(&vsock_connected_table[i]);
200 return 0;
201 }
202
__vsock_insert_bound(struct list_head * list,struct vsock_sock * vsk)203 static void __vsock_insert_bound(struct list_head *list,
204 struct vsock_sock *vsk)
205 {
206 sock_hold(&vsk->sk);
207 list_add(&vsk->bound_table, list);
208 }
209
__vsock_insert_connected(struct list_head * list,struct vsock_sock * vsk)210 static void __vsock_insert_connected(struct list_head *list,
211 struct vsock_sock *vsk)
212 {
213 sock_hold(&vsk->sk);
214 list_add(&vsk->connected_table, list);
215 }
216
__vsock_remove_bound(struct vsock_sock * vsk)217 static void __vsock_remove_bound(struct vsock_sock *vsk)
218 {
219 list_del_init(&vsk->bound_table);
220 sock_put(&vsk->sk);
221 }
222
__vsock_remove_connected(struct vsock_sock * vsk)223 static void __vsock_remove_connected(struct vsock_sock *vsk)
224 {
225 list_del_init(&vsk->connected_table);
226 sock_put(&vsk->sk);
227 }
228
__vsock_find_bound_socket(struct sockaddr_vm * addr)229 static struct sock *__vsock_find_bound_socket(struct sockaddr_vm *addr)
230 {
231 struct vsock_sock *vsk;
232
233 list_for_each_entry(vsk, vsock_bound_sockets(addr), bound_table)
234 if (addr->svm_port == vsk->local_addr.svm_port)
235 return sk_vsock(vsk);
236
237 return NULL;
238 }
239
__vsock_find_connected_socket(struct sockaddr_vm * src,struct sockaddr_vm * dst)240 static struct sock *__vsock_find_connected_socket(struct sockaddr_vm *src,
241 struct sockaddr_vm *dst)
242 {
243 struct vsock_sock *vsk;
244
245 list_for_each_entry(vsk, vsock_connected_sockets(src, dst),
246 connected_table) {
247 if (vsock_addr_equals_addr(src, &vsk->remote_addr) &&
248 dst->svm_port == vsk->local_addr.svm_port) {
249 return sk_vsock(vsk);
250 }
251 }
252
253 return NULL;
254 }
255
vsock_insert_unbound(struct vsock_sock * vsk)256 static void vsock_insert_unbound(struct vsock_sock *vsk)
257 {
258 spin_lock_bh(&vsock_table_lock);
259 __vsock_insert_bound(vsock_unbound_sockets, vsk);
260 spin_unlock_bh(&vsock_table_lock);
261 }
262
vsock_insert_connected(struct vsock_sock * vsk)263 void vsock_insert_connected(struct vsock_sock *vsk)
264 {
265 struct list_head *list = vsock_connected_sockets(
266 &vsk->remote_addr, &vsk->local_addr);
267
268 spin_lock_bh(&vsock_table_lock);
269 __vsock_insert_connected(list, vsk);
270 spin_unlock_bh(&vsock_table_lock);
271 }
272 EXPORT_SYMBOL_GPL(vsock_insert_connected);
273
vsock_remove_bound(struct vsock_sock * vsk)274 void vsock_remove_bound(struct vsock_sock *vsk)
275 {
276 spin_lock_bh(&vsock_table_lock);
277 if (__vsock_in_bound_table(vsk))
278 __vsock_remove_bound(vsk);
279 spin_unlock_bh(&vsock_table_lock);
280 }
281 EXPORT_SYMBOL_GPL(vsock_remove_bound);
282
vsock_remove_connected(struct vsock_sock * vsk)283 void vsock_remove_connected(struct vsock_sock *vsk)
284 {
285 spin_lock_bh(&vsock_table_lock);
286 if (__vsock_in_connected_table(vsk))
287 __vsock_remove_connected(vsk);
288 spin_unlock_bh(&vsock_table_lock);
289 }
290 EXPORT_SYMBOL_GPL(vsock_remove_connected);
291
vsock_find_bound_socket(struct sockaddr_vm * addr)292 struct sock *vsock_find_bound_socket(struct sockaddr_vm *addr)
293 {
294 struct sock *sk;
295
296 spin_lock_bh(&vsock_table_lock);
297 sk = __vsock_find_bound_socket(addr);
298 if (sk)
299 sock_hold(sk);
300
301 spin_unlock_bh(&vsock_table_lock);
302
303 return sk;
304 }
305 EXPORT_SYMBOL_GPL(vsock_find_bound_socket);
306
vsock_find_connected_socket(struct sockaddr_vm * src,struct sockaddr_vm * dst)307 struct sock *vsock_find_connected_socket(struct sockaddr_vm *src,
308 struct sockaddr_vm *dst)
309 {
310 struct sock *sk;
311
312 spin_lock_bh(&vsock_table_lock);
313 sk = __vsock_find_connected_socket(src, dst);
314 if (sk)
315 sock_hold(sk);
316
317 spin_unlock_bh(&vsock_table_lock);
318
319 return sk;
320 }
321 EXPORT_SYMBOL_GPL(vsock_find_connected_socket);
322
vsock_remove_sock(struct vsock_sock * vsk)323 void vsock_remove_sock(struct vsock_sock *vsk)
324 {
325 vsock_remove_bound(vsk);
326 vsock_remove_connected(vsk);
327 }
328 EXPORT_SYMBOL_GPL(vsock_remove_sock);
329
vsock_for_each_connected_socket(void (* fn)(struct sock * sk))330 void vsock_for_each_connected_socket(void (*fn)(struct sock *sk))
331 {
332 int i;
333
334 spin_lock_bh(&vsock_table_lock);
335
336 for (i = 0; i < ARRAY_SIZE(vsock_connected_table); i++) {
337 struct vsock_sock *vsk;
338 list_for_each_entry(vsk, &vsock_connected_table[i],
339 connected_table)
340 fn(sk_vsock(vsk));
341 }
342
343 spin_unlock_bh(&vsock_table_lock);
344 }
345 EXPORT_SYMBOL_GPL(vsock_for_each_connected_socket);
346
vsock_add_pending(struct sock * listener,struct sock * pending)347 void vsock_add_pending(struct sock *listener, struct sock *pending)
348 {
349 struct vsock_sock *vlistener;
350 struct vsock_sock *vpending;
351
352 vlistener = vsock_sk(listener);
353 vpending = vsock_sk(pending);
354
355 sock_hold(pending);
356 sock_hold(listener);
357 list_add_tail(&vpending->pending_links, &vlistener->pending_links);
358 }
359 EXPORT_SYMBOL_GPL(vsock_add_pending);
360
vsock_remove_pending(struct sock * listener,struct sock * pending)361 void vsock_remove_pending(struct sock *listener, struct sock *pending)
362 {
363 struct vsock_sock *vpending = vsock_sk(pending);
364
365 list_del_init(&vpending->pending_links);
366 sock_put(listener);
367 sock_put(pending);
368 }
369 EXPORT_SYMBOL_GPL(vsock_remove_pending);
370
vsock_enqueue_accept(struct sock * listener,struct sock * connected)371 void vsock_enqueue_accept(struct sock *listener, struct sock *connected)
372 {
373 struct vsock_sock *vlistener;
374 struct vsock_sock *vconnected;
375
376 vlistener = vsock_sk(listener);
377 vconnected = vsock_sk(connected);
378
379 sock_hold(connected);
380 sock_hold(listener);
381 list_add_tail(&vconnected->accept_queue, &vlistener->accept_queue);
382 }
383 EXPORT_SYMBOL_GPL(vsock_enqueue_accept);
384
vsock_dequeue_accept(struct sock * listener)385 static struct sock *vsock_dequeue_accept(struct sock *listener)
386 {
387 struct vsock_sock *vlistener;
388 struct vsock_sock *vconnected;
389
390 vlistener = vsock_sk(listener);
391
392 if (list_empty(&vlistener->accept_queue))
393 return NULL;
394
395 vconnected = list_entry(vlistener->accept_queue.next,
396 struct vsock_sock, accept_queue);
397
398 list_del_init(&vconnected->accept_queue);
399 sock_put(listener);
400 /* The caller will need a reference on the connected socket so we let
401 * it call sock_put().
402 */
403
404 return sk_vsock(vconnected);
405 }
406
vsock_is_accept_queue_empty(struct sock * sk)407 static bool vsock_is_accept_queue_empty(struct sock *sk)
408 {
409 struct vsock_sock *vsk = vsock_sk(sk);
410 return list_empty(&vsk->accept_queue);
411 }
412
vsock_is_pending(struct sock * sk)413 static bool vsock_is_pending(struct sock *sk)
414 {
415 struct vsock_sock *vsk = vsock_sk(sk);
416 return !list_empty(&vsk->pending_links);
417 }
418
vsock_send_shutdown(struct sock * sk,int mode)419 static int vsock_send_shutdown(struct sock *sk, int mode)
420 {
421 return transport->shutdown(vsock_sk(sk), mode);
422 }
423
vsock_pending_work(struct work_struct * work)424 static void vsock_pending_work(struct work_struct *work)
425 {
426 struct sock *sk;
427 struct sock *listener;
428 struct vsock_sock *vsk;
429 bool cleanup;
430
431 vsk = container_of(work, struct vsock_sock, pending_work.work);
432 sk = sk_vsock(vsk);
433 listener = vsk->listener;
434 cleanup = true;
435
436 lock_sock(listener);
437 lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
438
439 if (vsock_is_pending(sk)) {
440 vsock_remove_pending(listener, sk);
441
442 listener->sk_ack_backlog--;
443 } else if (!vsk->rejected) {
444 /* We are not on the pending list and accept() did not reject
445 * us, so we must have been accepted by our user process. We
446 * just need to drop our references to the sockets and be on
447 * our way.
448 */
449 cleanup = false;
450 goto out;
451 }
452
453 /* We need to remove ourself from the global connected sockets list so
454 * incoming packets can't find this socket, and to reduce the reference
455 * count.
456 */
457 vsock_remove_connected(vsk);
458
459 sk->sk_state = TCP_CLOSE;
460
461 out:
462 release_sock(sk);
463 release_sock(listener);
464 if (cleanup)
465 sock_put(sk);
466
467 sock_put(sk);
468 sock_put(listener);
469 }
470
471 /**** SOCKET OPERATIONS ****/
472
__vsock_bind_stream(struct vsock_sock * vsk,struct sockaddr_vm * addr)473 static int __vsock_bind_stream(struct vsock_sock *vsk,
474 struct sockaddr_vm *addr)
475 {
476 static u32 port;
477 struct sockaddr_vm new_addr;
478
479 if (!port)
480 port = LAST_RESERVED_PORT + 1 +
481 prandom_u32_max(U32_MAX - LAST_RESERVED_PORT);
482
483 vsock_addr_init(&new_addr, addr->svm_cid, addr->svm_port);
484
485 if (addr->svm_port == VMADDR_PORT_ANY) {
486 bool found = false;
487 unsigned int i;
488
489 for (i = 0; i < MAX_PORT_RETRIES; i++) {
490 if (port <= LAST_RESERVED_PORT)
491 port = LAST_RESERVED_PORT + 1;
492
493 new_addr.svm_port = port++;
494
495 if (!__vsock_find_bound_socket(&new_addr)) {
496 found = true;
497 break;
498 }
499 }
500
501 if (!found)
502 return -EADDRNOTAVAIL;
503 } else {
504 /* If port is in reserved range, ensure caller
505 * has necessary privileges.
506 */
507 if (addr->svm_port <= LAST_RESERVED_PORT &&
508 !capable(CAP_NET_BIND_SERVICE)) {
509 return -EACCES;
510 }
511
512 if (__vsock_find_bound_socket(&new_addr))
513 return -EADDRINUSE;
514 }
515
516 vsock_addr_init(&vsk->local_addr, new_addr.svm_cid, new_addr.svm_port);
517
518 /* Remove stream sockets from the unbound list and add them to the hash
519 * table for easy lookup by its address. The unbound list is simply an
520 * extra entry at the end of the hash table, a trick used by AF_UNIX.
521 */
522 __vsock_remove_bound(vsk);
523 __vsock_insert_bound(vsock_bound_sockets(&vsk->local_addr), vsk);
524
525 return 0;
526 }
527
__vsock_bind_dgram(struct vsock_sock * vsk,struct sockaddr_vm * addr)528 static int __vsock_bind_dgram(struct vsock_sock *vsk,
529 struct sockaddr_vm *addr)
530 {
531 return transport->dgram_bind(vsk, addr);
532 }
533
__vsock_bind(struct sock * sk,struct sockaddr_vm * addr)534 static int __vsock_bind(struct sock *sk, struct sockaddr_vm *addr)
535 {
536 struct vsock_sock *vsk = vsock_sk(sk);
537 u32 cid;
538 int retval;
539
540 /* First ensure this socket isn't already bound. */
541 if (vsock_addr_bound(&vsk->local_addr))
542 return -EINVAL;
543
544 /* Now bind to the provided address or select appropriate values if
545 * none are provided (VMADDR_CID_ANY and VMADDR_PORT_ANY). Note that
546 * like AF_INET prevents binding to a non-local IP address (in most
547 * cases), we only allow binding to the local CID.
548 */
549 cid = transport->get_local_cid();
550 if (addr->svm_cid != cid && addr->svm_cid != VMADDR_CID_ANY)
551 return -EADDRNOTAVAIL;
552
553 switch (sk->sk_socket->type) {
554 case SOCK_STREAM:
555 spin_lock_bh(&vsock_table_lock);
556 retval = __vsock_bind_stream(vsk, addr);
557 spin_unlock_bh(&vsock_table_lock);
558 break;
559
560 case SOCK_DGRAM:
561 retval = __vsock_bind_dgram(vsk, addr);
562 break;
563
564 default:
565 retval = -EINVAL;
566 break;
567 }
568
569 return retval;
570 }
571
572 static void vsock_connect_timeout(struct work_struct *work);
573
__vsock_create(struct net * net,struct socket * sock,struct sock * parent,gfp_t priority,unsigned short type,int kern)574 struct sock *__vsock_create(struct net *net,
575 struct socket *sock,
576 struct sock *parent,
577 gfp_t priority,
578 unsigned short type,
579 int kern)
580 {
581 struct sock *sk;
582 struct vsock_sock *psk;
583 struct vsock_sock *vsk;
584
585 sk = sk_alloc(net, AF_VSOCK, priority, &vsock_proto, kern);
586 if (!sk)
587 return NULL;
588
589 sock_init_data(sock, sk);
590
591 /* sk->sk_type is normally set in sock_init_data, but only if sock is
592 * non-NULL. We make sure that our sockets always have a type by
593 * setting it here if needed.
594 */
595 if (!sock)
596 sk->sk_type = type;
597
598 vsk = vsock_sk(sk);
599 vsock_addr_init(&vsk->local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
600 vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
601
602 sk->sk_destruct = vsock_sk_destruct;
603 sk->sk_backlog_rcv = vsock_queue_rcv_skb;
604 sock_reset_flag(sk, SOCK_DONE);
605
606 INIT_LIST_HEAD(&vsk->bound_table);
607 INIT_LIST_HEAD(&vsk->connected_table);
608 vsk->listener = NULL;
609 INIT_LIST_HEAD(&vsk->pending_links);
610 INIT_LIST_HEAD(&vsk->accept_queue);
611 vsk->rejected = false;
612 vsk->sent_request = false;
613 vsk->ignore_connecting_rst = false;
614 vsk->peer_shutdown = 0;
615 INIT_DELAYED_WORK(&vsk->connect_work, vsock_connect_timeout);
616 INIT_DELAYED_WORK(&vsk->pending_work, vsock_pending_work);
617
618 psk = parent ? vsock_sk(parent) : NULL;
619 if (parent) {
620 vsk->trusted = psk->trusted;
621 vsk->owner = get_cred(psk->owner);
622 vsk->connect_timeout = psk->connect_timeout;
623 } else {
624 vsk->trusted = capable(CAP_NET_ADMIN);
625 vsk->owner = get_current_cred();
626 vsk->connect_timeout = VSOCK_DEFAULT_CONNECT_TIMEOUT;
627 }
628
629 if (transport->init(vsk, psk) < 0) {
630 sk_free(sk);
631 return NULL;
632 }
633
634 if (sock)
635 vsock_insert_unbound(vsk);
636
637 return sk;
638 }
639 EXPORT_SYMBOL_GPL(__vsock_create);
640
__vsock_release(struct sock * sk,int level)641 static void __vsock_release(struct sock *sk, int level)
642 {
643 if (sk) {
644 struct sk_buff *skb;
645 struct sock *pending;
646 struct vsock_sock *vsk;
647
648 vsk = vsock_sk(sk);
649 pending = NULL; /* Compiler warning. */
650
651 /* The release call is supposed to use lock_sock_nested()
652 * rather than lock_sock(), if a sock lock should be acquired.
653 */
654 transport->release(vsk);
655
656 /* When "level" is SINGLE_DEPTH_NESTING, use the nested
657 * version to avoid the warning "possible recursive locking
658 * detected". When "level" is 0, lock_sock_nested(sk, level)
659 * is the same as lock_sock(sk).
660 */
661 lock_sock_nested(sk, level);
662 sock_orphan(sk);
663 sk->sk_shutdown = SHUTDOWN_MASK;
664
665 while ((skb = skb_dequeue(&sk->sk_receive_queue)))
666 kfree_skb(skb);
667
668 /* Clean up any sockets that never were accepted. */
669 while ((pending = vsock_dequeue_accept(sk)) != NULL) {
670 __vsock_release(pending, SINGLE_DEPTH_NESTING);
671 sock_put(pending);
672 }
673
674 release_sock(sk);
675 sock_put(sk);
676 }
677 }
678
vsock_sk_destruct(struct sock * sk)679 static void vsock_sk_destruct(struct sock *sk)
680 {
681 struct vsock_sock *vsk = vsock_sk(sk);
682
683 transport->destruct(vsk);
684
685 /* When clearing these addresses, there's no need to set the family and
686 * possibly register the address family with the kernel.
687 */
688 vsock_addr_init(&vsk->local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
689 vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
690
691 put_cred(vsk->owner);
692 }
693
vsock_queue_rcv_skb(struct sock * sk,struct sk_buff * skb)694 static int vsock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
695 {
696 int err;
697
698 err = sock_queue_rcv_skb(sk, skb);
699 if (err)
700 kfree_skb(skb);
701
702 return err;
703 }
704
vsock_stream_has_data(struct vsock_sock * vsk)705 s64 vsock_stream_has_data(struct vsock_sock *vsk)
706 {
707 return transport->stream_has_data(vsk);
708 }
709 EXPORT_SYMBOL_GPL(vsock_stream_has_data);
710
vsock_stream_has_space(struct vsock_sock * vsk)711 s64 vsock_stream_has_space(struct vsock_sock *vsk)
712 {
713 return transport->stream_has_space(vsk);
714 }
715 EXPORT_SYMBOL_GPL(vsock_stream_has_space);
716
vsock_release(struct socket * sock)717 static int vsock_release(struct socket *sock)
718 {
719 __vsock_release(sock->sk, 0);
720 sock->sk = NULL;
721 sock->state = SS_FREE;
722
723 return 0;
724 }
725
726 static int
vsock_bind(struct socket * sock,struct sockaddr * addr,int addr_len)727 vsock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
728 {
729 int err;
730 struct sock *sk;
731 struct sockaddr_vm *vm_addr;
732
733 sk = sock->sk;
734
735 if (vsock_addr_cast(addr, addr_len, &vm_addr) != 0)
736 return -EINVAL;
737
738 lock_sock(sk);
739 err = __vsock_bind(sk, vm_addr);
740 release_sock(sk);
741
742 return err;
743 }
744
vsock_getname(struct socket * sock,struct sockaddr * addr,int peer)745 static int vsock_getname(struct socket *sock,
746 struct sockaddr *addr, int peer)
747 {
748 int err;
749 struct sock *sk;
750 struct vsock_sock *vsk;
751 struct sockaddr_vm *vm_addr;
752
753 sk = sock->sk;
754 vsk = vsock_sk(sk);
755 err = 0;
756
757 lock_sock(sk);
758
759 if (peer) {
760 if (sock->state != SS_CONNECTED) {
761 err = -ENOTCONN;
762 goto out;
763 }
764 vm_addr = &vsk->remote_addr;
765 } else {
766 vm_addr = &vsk->local_addr;
767 }
768
769 if (!vm_addr) {
770 err = -EINVAL;
771 goto out;
772 }
773
774 /* sys_getsockname() and sys_getpeername() pass us a
775 * MAX_SOCK_ADDR-sized buffer and don't set addr_len. Unfortunately
776 * that macro is defined in socket.c instead of .h, so we hardcode its
777 * value here.
778 */
779 BUILD_BUG_ON(sizeof(*vm_addr) > 128);
780 memcpy(addr, vm_addr, sizeof(*vm_addr));
781 err = sizeof(*vm_addr);
782
783 out:
784 release_sock(sk);
785 return err;
786 }
787
vsock_shutdown(struct socket * sock,int mode)788 static int vsock_shutdown(struct socket *sock, int mode)
789 {
790 int err;
791 struct sock *sk;
792
793 /* User level uses SHUT_RD (0) and SHUT_WR (1), but the kernel uses
794 * RCV_SHUTDOWN (1) and SEND_SHUTDOWN (2), so we must increment mode
795 * here like the other address families do. Note also that the
796 * increment makes SHUT_RDWR (2) into RCV_SHUTDOWN | SEND_SHUTDOWN (3),
797 * which is what we want.
798 */
799 mode++;
800
801 if ((mode & ~SHUTDOWN_MASK) || !mode)
802 return -EINVAL;
803
804 /* If this is a STREAM socket and it is not connected then bail out
805 * immediately. If it is a DGRAM socket then we must first kick the
806 * socket so that it wakes up from any sleeping calls, for example
807 * recv(), and then afterwards return the error.
808 */
809
810 sk = sock->sk;
811 if (sock->state == SS_UNCONNECTED) {
812 err = -ENOTCONN;
813 if (sk->sk_type == SOCK_STREAM)
814 return err;
815 } else {
816 sock->state = SS_DISCONNECTING;
817 err = 0;
818 }
819
820 /* Receive and send shutdowns are treated alike. */
821 mode = mode & (RCV_SHUTDOWN | SEND_SHUTDOWN);
822 if (mode) {
823 lock_sock(sk);
824 sk->sk_shutdown |= mode;
825 sk->sk_state_change(sk);
826 release_sock(sk);
827
828 if (sk->sk_type == SOCK_STREAM) {
829 sock_reset_flag(sk, SOCK_DONE);
830 vsock_send_shutdown(sk, mode);
831 }
832 }
833
834 return err;
835 }
836
vsock_poll(struct file * file,struct socket * sock,poll_table * wait)837 static __poll_t vsock_poll(struct file *file, struct socket *sock,
838 poll_table *wait)
839 {
840 struct sock *sk;
841 __poll_t mask;
842 struct vsock_sock *vsk;
843
844 sk = sock->sk;
845 vsk = vsock_sk(sk);
846
847 poll_wait(file, sk_sleep(sk), wait);
848 mask = 0;
849
850 if (sk->sk_err)
851 /* Signify that there has been an error on this socket. */
852 mask |= EPOLLERR;
853
854 /* INET sockets treat local write shutdown and peer write shutdown as a
855 * case of EPOLLHUP set.
856 */
857 if ((sk->sk_shutdown == SHUTDOWN_MASK) ||
858 ((sk->sk_shutdown & SEND_SHUTDOWN) &&
859 (vsk->peer_shutdown & SEND_SHUTDOWN))) {
860 mask |= EPOLLHUP;
861 }
862
863 if (sk->sk_shutdown & RCV_SHUTDOWN ||
864 vsk->peer_shutdown & SEND_SHUTDOWN) {
865 mask |= EPOLLRDHUP;
866 }
867
868 if (sock->type == SOCK_DGRAM) {
869 /* For datagram sockets we can read if there is something in
870 * the queue and write as long as the socket isn't shutdown for
871 * sending.
872 */
873 if (!skb_queue_empty_lockless(&sk->sk_receive_queue) ||
874 (sk->sk_shutdown & RCV_SHUTDOWN)) {
875 mask |= EPOLLIN | EPOLLRDNORM;
876 }
877
878 if (!(sk->sk_shutdown & SEND_SHUTDOWN))
879 mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
880
881 } else if (sock->type == SOCK_STREAM) {
882 lock_sock(sk);
883
884 /* Listening sockets that have connections in their accept
885 * queue can be read.
886 */
887 if (sk->sk_state == TCP_LISTEN
888 && !vsock_is_accept_queue_empty(sk))
889 mask |= EPOLLIN | EPOLLRDNORM;
890
891 /* If there is something in the queue then we can read. */
892 if (transport->stream_is_active(vsk) &&
893 !(sk->sk_shutdown & RCV_SHUTDOWN)) {
894 bool data_ready_now = false;
895 int ret = transport->notify_poll_in(
896 vsk, 1, &data_ready_now);
897 if (ret < 0) {
898 mask |= EPOLLERR;
899 } else {
900 if (data_ready_now)
901 mask |= EPOLLIN | EPOLLRDNORM;
902
903 }
904 }
905
906 /* Sockets whose connections have been closed, reset, or
907 * terminated should also be considered read, and we check the
908 * shutdown flag for that.
909 */
910 if (sk->sk_shutdown & RCV_SHUTDOWN ||
911 vsk->peer_shutdown & SEND_SHUTDOWN) {
912 mask |= EPOLLIN | EPOLLRDNORM;
913 }
914
915 /* Connected sockets that can produce data can be written. */
916 if (sk->sk_state == TCP_ESTABLISHED) {
917 if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
918 bool space_avail_now = false;
919 int ret = transport->notify_poll_out(
920 vsk, 1, &space_avail_now);
921 if (ret < 0) {
922 mask |= EPOLLERR;
923 } else {
924 if (space_avail_now)
925 /* Remove EPOLLWRBAND since INET
926 * sockets are not setting it.
927 */
928 mask |= EPOLLOUT | EPOLLWRNORM;
929
930 }
931 }
932 }
933
934 /* Simulate INET socket poll behaviors, which sets
935 * EPOLLOUT|EPOLLWRNORM when peer is closed and nothing to read,
936 * but local send is not shutdown.
937 */
938 if (sk->sk_state == TCP_CLOSE || sk->sk_state == TCP_CLOSING) {
939 if (!(sk->sk_shutdown & SEND_SHUTDOWN))
940 mask |= EPOLLOUT | EPOLLWRNORM;
941
942 }
943
944 release_sock(sk);
945 }
946
947 return mask;
948 }
949
vsock_dgram_sendmsg(struct socket * sock,struct msghdr * msg,size_t len)950 static int vsock_dgram_sendmsg(struct socket *sock, struct msghdr *msg,
951 size_t len)
952 {
953 int err;
954 struct sock *sk;
955 struct vsock_sock *vsk;
956 struct sockaddr_vm *remote_addr;
957
958 if (msg->msg_flags & MSG_OOB)
959 return -EOPNOTSUPP;
960
961 /* For now, MSG_DONTWAIT is always assumed... */
962 err = 0;
963 sk = sock->sk;
964 vsk = vsock_sk(sk);
965
966 lock_sock(sk);
967
968 err = vsock_auto_bind(vsk);
969 if (err)
970 goto out;
971
972
973 /* If the provided message contains an address, use that. Otherwise
974 * fall back on the socket's remote handle (if it has been connected).
975 */
976 if (msg->msg_name &&
977 vsock_addr_cast(msg->msg_name, msg->msg_namelen,
978 &remote_addr) == 0) {
979 /* Ensure this address is of the right type and is a valid
980 * destination.
981 */
982
983 if (remote_addr->svm_cid == VMADDR_CID_ANY)
984 remote_addr->svm_cid = transport->get_local_cid();
985
986 if (!vsock_addr_bound(remote_addr)) {
987 err = -EINVAL;
988 goto out;
989 }
990 } else if (sock->state == SS_CONNECTED) {
991 remote_addr = &vsk->remote_addr;
992
993 if (remote_addr->svm_cid == VMADDR_CID_ANY)
994 remote_addr->svm_cid = transport->get_local_cid();
995
996 /* XXX Should connect() or this function ensure remote_addr is
997 * bound?
998 */
999 if (!vsock_addr_bound(&vsk->remote_addr)) {
1000 err = -EINVAL;
1001 goto out;
1002 }
1003 } else {
1004 err = -EINVAL;
1005 goto out;
1006 }
1007
1008 if (!transport->dgram_allow(remote_addr->svm_cid,
1009 remote_addr->svm_port)) {
1010 err = -EINVAL;
1011 goto out;
1012 }
1013
1014 err = transport->dgram_enqueue(vsk, remote_addr, msg, len);
1015
1016 out:
1017 release_sock(sk);
1018 return err;
1019 }
1020
vsock_dgram_connect(struct socket * sock,struct sockaddr * addr,int addr_len,int flags)1021 static int vsock_dgram_connect(struct socket *sock,
1022 struct sockaddr *addr, int addr_len, int flags)
1023 {
1024 int err;
1025 struct sock *sk;
1026 struct vsock_sock *vsk;
1027 struct sockaddr_vm *remote_addr;
1028
1029 sk = sock->sk;
1030 vsk = vsock_sk(sk);
1031
1032 err = vsock_addr_cast(addr, addr_len, &remote_addr);
1033 if (err == -EAFNOSUPPORT && remote_addr->svm_family == AF_UNSPEC) {
1034 lock_sock(sk);
1035 vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY,
1036 VMADDR_PORT_ANY);
1037 sock->state = SS_UNCONNECTED;
1038 release_sock(sk);
1039 return 0;
1040 } else if (err != 0)
1041 return -EINVAL;
1042
1043 lock_sock(sk);
1044
1045 err = vsock_auto_bind(vsk);
1046 if (err)
1047 goto out;
1048
1049 if (!transport->dgram_allow(remote_addr->svm_cid,
1050 remote_addr->svm_port)) {
1051 err = -EINVAL;
1052 goto out;
1053 }
1054
1055 memcpy(&vsk->remote_addr, remote_addr, sizeof(vsk->remote_addr));
1056 sock->state = SS_CONNECTED;
1057
1058 out:
1059 release_sock(sk);
1060 return err;
1061 }
1062
vsock_dgram_recvmsg(struct socket * sock,struct msghdr * msg,size_t len,int flags)1063 static int vsock_dgram_recvmsg(struct socket *sock, struct msghdr *msg,
1064 size_t len, int flags)
1065 {
1066 return transport->dgram_dequeue(vsock_sk(sock->sk), msg, len, flags);
1067 }
1068
1069 static const struct proto_ops vsock_dgram_ops = {
1070 .family = PF_VSOCK,
1071 .owner = THIS_MODULE,
1072 .release = vsock_release,
1073 .bind = vsock_bind,
1074 .connect = vsock_dgram_connect,
1075 .socketpair = sock_no_socketpair,
1076 .accept = sock_no_accept,
1077 .getname = vsock_getname,
1078 .poll = vsock_poll,
1079 .ioctl = sock_no_ioctl,
1080 .listen = sock_no_listen,
1081 .shutdown = vsock_shutdown,
1082 .setsockopt = sock_no_setsockopt,
1083 .getsockopt = sock_no_getsockopt,
1084 .sendmsg = vsock_dgram_sendmsg,
1085 .recvmsg = vsock_dgram_recvmsg,
1086 .mmap = sock_no_mmap,
1087 .sendpage = sock_no_sendpage,
1088 };
1089
vsock_transport_cancel_pkt(struct vsock_sock * vsk)1090 static int vsock_transport_cancel_pkt(struct vsock_sock *vsk)
1091 {
1092 if (!transport->cancel_pkt)
1093 return -EOPNOTSUPP;
1094
1095 return transport->cancel_pkt(vsk);
1096 }
1097
vsock_connect_timeout(struct work_struct * work)1098 static void vsock_connect_timeout(struct work_struct *work)
1099 {
1100 struct sock *sk;
1101 struct vsock_sock *vsk;
1102 int cancel = 0;
1103
1104 vsk = container_of(work, struct vsock_sock, connect_work.work);
1105 sk = sk_vsock(vsk);
1106
1107 lock_sock(sk);
1108 if (sk->sk_state == TCP_SYN_SENT &&
1109 (sk->sk_shutdown != SHUTDOWN_MASK)) {
1110 sk->sk_state = TCP_CLOSE;
1111 sk->sk_err = ETIMEDOUT;
1112 sk->sk_error_report(sk);
1113 cancel = 1;
1114 }
1115 release_sock(sk);
1116 if (cancel)
1117 vsock_transport_cancel_pkt(vsk);
1118
1119 sock_put(sk);
1120 }
1121
vsock_stream_connect(struct socket * sock,struct sockaddr * addr,int addr_len,int flags)1122 static int vsock_stream_connect(struct socket *sock, struct sockaddr *addr,
1123 int addr_len, int flags)
1124 {
1125 int err;
1126 struct sock *sk;
1127 struct vsock_sock *vsk;
1128 struct sockaddr_vm *remote_addr;
1129 long timeout;
1130 DEFINE_WAIT(wait);
1131
1132 err = 0;
1133 sk = sock->sk;
1134 vsk = vsock_sk(sk);
1135
1136 lock_sock(sk);
1137
1138 /* XXX AF_UNSPEC should make us disconnect like AF_INET. */
1139 switch (sock->state) {
1140 case SS_CONNECTED:
1141 err = -EISCONN;
1142 goto out;
1143 case SS_DISCONNECTING:
1144 err = -EINVAL;
1145 goto out;
1146 case SS_CONNECTING:
1147 /* This continues on so we can move sock into the SS_CONNECTED
1148 * state once the connection has completed (at which point err
1149 * will be set to zero also). Otherwise, we will either wait
1150 * for the connection or return -EALREADY should this be a
1151 * non-blocking call.
1152 */
1153 err = -EALREADY;
1154 break;
1155 default:
1156 if ((sk->sk_state == TCP_LISTEN) ||
1157 vsock_addr_cast(addr, addr_len, &remote_addr) != 0) {
1158 err = -EINVAL;
1159 goto out;
1160 }
1161
1162 /* The hypervisor and well-known contexts do not have socket
1163 * endpoints.
1164 */
1165 if (!transport->stream_allow(remote_addr->svm_cid,
1166 remote_addr->svm_port)) {
1167 err = -ENETUNREACH;
1168 goto out;
1169 }
1170
1171 /* Set the remote address that we are connecting to. */
1172 memcpy(&vsk->remote_addr, remote_addr,
1173 sizeof(vsk->remote_addr));
1174
1175 err = vsock_auto_bind(vsk);
1176 if (err)
1177 goto out;
1178
1179 sk->sk_state = TCP_SYN_SENT;
1180
1181 err = transport->connect(vsk);
1182 if (err < 0)
1183 goto out;
1184
1185 /* Mark sock as connecting and set the error code to in
1186 * progress in case this is a non-blocking connect.
1187 */
1188 sock->state = SS_CONNECTING;
1189 err = -EINPROGRESS;
1190 }
1191
1192 /* The receive path will handle all communication until we are able to
1193 * enter the connected state. Here we wait for the connection to be
1194 * completed or a notification of an error.
1195 */
1196 timeout = vsk->connect_timeout;
1197 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1198
1199 while (sk->sk_state != TCP_ESTABLISHED && sk->sk_err == 0) {
1200 if (flags & O_NONBLOCK) {
1201 /* If we're not going to block, we schedule a timeout
1202 * function to generate a timeout on the connection
1203 * attempt, in case the peer doesn't respond in a
1204 * timely manner. We hold on to the socket until the
1205 * timeout fires.
1206 */
1207 sock_hold(sk);
1208 schedule_delayed_work(&vsk->connect_work, timeout);
1209
1210 /* Skip ahead to preserve error code set above. */
1211 goto out_wait;
1212 }
1213
1214 release_sock(sk);
1215 timeout = schedule_timeout(timeout);
1216 lock_sock(sk);
1217
1218 if (signal_pending(current)) {
1219 err = sock_intr_errno(timeout);
1220 sk->sk_state = TCP_CLOSE;
1221 sock->state = SS_UNCONNECTED;
1222 vsock_transport_cancel_pkt(vsk);
1223 goto out_wait;
1224 } else if (timeout == 0) {
1225 err = -ETIMEDOUT;
1226 sk->sk_state = TCP_CLOSE;
1227 sock->state = SS_UNCONNECTED;
1228 vsock_transport_cancel_pkt(vsk);
1229 goto out_wait;
1230 }
1231
1232 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1233 }
1234
1235 if (sk->sk_err) {
1236 err = -sk->sk_err;
1237 sk->sk_state = TCP_CLOSE;
1238 sock->state = SS_UNCONNECTED;
1239 } else {
1240 err = 0;
1241 }
1242
1243 out_wait:
1244 finish_wait(sk_sleep(sk), &wait);
1245 out:
1246 release_sock(sk);
1247 return err;
1248 }
1249
vsock_accept(struct socket * sock,struct socket * newsock,int flags,bool kern)1250 static int vsock_accept(struct socket *sock, struct socket *newsock, int flags,
1251 bool kern)
1252 {
1253 struct sock *listener;
1254 int err;
1255 struct sock *connected;
1256 struct vsock_sock *vconnected;
1257 long timeout;
1258 DEFINE_WAIT(wait);
1259
1260 err = 0;
1261 listener = sock->sk;
1262
1263 lock_sock(listener);
1264
1265 if (sock->type != SOCK_STREAM) {
1266 err = -EOPNOTSUPP;
1267 goto out;
1268 }
1269
1270 if (listener->sk_state != TCP_LISTEN) {
1271 err = -EINVAL;
1272 goto out;
1273 }
1274
1275 /* Wait for children sockets to appear; these are the new sockets
1276 * created upon connection establishment.
1277 */
1278 timeout = sock_sndtimeo(listener, flags & O_NONBLOCK);
1279 prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);
1280
1281 while ((connected = vsock_dequeue_accept(listener)) == NULL &&
1282 listener->sk_err == 0) {
1283 release_sock(listener);
1284 timeout = schedule_timeout(timeout);
1285 finish_wait(sk_sleep(listener), &wait);
1286 lock_sock(listener);
1287
1288 if (signal_pending(current)) {
1289 err = sock_intr_errno(timeout);
1290 goto out;
1291 } else if (timeout == 0) {
1292 err = -EAGAIN;
1293 goto out;
1294 }
1295
1296 prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);
1297 }
1298 finish_wait(sk_sleep(listener), &wait);
1299
1300 if (listener->sk_err)
1301 err = -listener->sk_err;
1302
1303 if (connected) {
1304 listener->sk_ack_backlog--;
1305
1306 lock_sock_nested(connected, SINGLE_DEPTH_NESTING);
1307 vconnected = vsock_sk(connected);
1308
1309 /* If the listener socket has received an error, then we should
1310 * reject this socket and return. Note that we simply mark the
1311 * socket rejected, drop our reference, and let the cleanup
1312 * function handle the cleanup; the fact that we found it in
1313 * the listener's accept queue guarantees that the cleanup
1314 * function hasn't run yet.
1315 */
1316 if (err) {
1317 vconnected->rejected = true;
1318 } else {
1319 newsock->state = SS_CONNECTED;
1320 sock_graft(connected, newsock);
1321 }
1322
1323 release_sock(connected);
1324 sock_put(connected);
1325 }
1326
1327 out:
1328 release_sock(listener);
1329 return err;
1330 }
1331
vsock_listen(struct socket * sock,int backlog)1332 static int vsock_listen(struct socket *sock, int backlog)
1333 {
1334 int err;
1335 struct sock *sk;
1336 struct vsock_sock *vsk;
1337
1338 sk = sock->sk;
1339
1340 lock_sock(sk);
1341
1342 if (sock->type != SOCK_STREAM) {
1343 err = -EOPNOTSUPP;
1344 goto out;
1345 }
1346
1347 if (sock->state != SS_UNCONNECTED) {
1348 err = -EINVAL;
1349 goto out;
1350 }
1351
1352 vsk = vsock_sk(sk);
1353
1354 if (!vsock_addr_bound(&vsk->local_addr)) {
1355 err = -EINVAL;
1356 goto out;
1357 }
1358
1359 sk->sk_max_ack_backlog = backlog;
1360 sk->sk_state = TCP_LISTEN;
1361
1362 err = 0;
1363
1364 out:
1365 release_sock(sk);
1366 return err;
1367 }
1368
vsock_stream_setsockopt(struct socket * sock,int level,int optname,char __user * optval,unsigned int optlen)1369 static int vsock_stream_setsockopt(struct socket *sock,
1370 int level,
1371 int optname,
1372 char __user *optval,
1373 unsigned int optlen)
1374 {
1375 int err;
1376 struct sock *sk;
1377 struct vsock_sock *vsk;
1378 u64 val;
1379
1380 if (level != AF_VSOCK)
1381 return -ENOPROTOOPT;
1382
1383 #define COPY_IN(_v) \
1384 do { \
1385 if (optlen < sizeof(_v)) { \
1386 err = -EINVAL; \
1387 goto exit; \
1388 } \
1389 if (copy_from_user(&_v, optval, sizeof(_v)) != 0) { \
1390 err = -EFAULT; \
1391 goto exit; \
1392 } \
1393 } while (0)
1394
1395 err = 0;
1396 sk = sock->sk;
1397 vsk = vsock_sk(sk);
1398
1399 lock_sock(sk);
1400
1401 switch (optname) {
1402 case SO_VM_SOCKETS_BUFFER_SIZE:
1403 COPY_IN(val);
1404 transport->set_buffer_size(vsk, val);
1405 break;
1406
1407 case SO_VM_SOCKETS_BUFFER_MAX_SIZE:
1408 COPY_IN(val);
1409 transport->set_max_buffer_size(vsk, val);
1410 break;
1411
1412 case SO_VM_SOCKETS_BUFFER_MIN_SIZE:
1413 COPY_IN(val);
1414 transport->set_min_buffer_size(vsk, val);
1415 break;
1416
1417 case SO_VM_SOCKETS_CONNECT_TIMEOUT: {
1418 struct __kernel_old_timeval tv;
1419 COPY_IN(tv);
1420 if (tv.tv_sec >= 0 && tv.tv_usec < USEC_PER_SEC &&
1421 tv.tv_sec < (MAX_SCHEDULE_TIMEOUT / HZ - 1)) {
1422 vsk->connect_timeout = tv.tv_sec * HZ +
1423 DIV_ROUND_UP(tv.tv_usec, (1000000 / HZ));
1424 if (vsk->connect_timeout == 0)
1425 vsk->connect_timeout =
1426 VSOCK_DEFAULT_CONNECT_TIMEOUT;
1427
1428 } else {
1429 err = -ERANGE;
1430 }
1431 break;
1432 }
1433
1434 default:
1435 err = -ENOPROTOOPT;
1436 break;
1437 }
1438
1439 #undef COPY_IN
1440
1441 exit:
1442 release_sock(sk);
1443 return err;
1444 }
1445
vsock_stream_getsockopt(struct socket * sock,int level,int optname,char __user * optval,int __user * optlen)1446 static int vsock_stream_getsockopt(struct socket *sock,
1447 int level, int optname,
1448 char __user *optval,
1449 int __user *optlen)
1450 {
1451 int err;
1452 int len;
1453 struct sock *sk;
1454 struct vsock_sock *vsk;
1455 u64 val;
1456
1457 if (level != AF_VSOCK)
1458 return -ENOPROTOOPT;
1459
1460 err = get_user(len, optlen);
1461 if (err != 0)
1462 return err;
1463
1464 #define COPY_OUT(_v) \
1465 do { \
1466 if (len < sizeof(_v)) \
1467 return -EINVAL; \
1468 \
1469 len = sizeof(_v); \
1470 if (copy_to_user(optval, &_v, len) != 0) \
1471 return -EFAULT; \
1472 \
1473 } while (0)
1474
1475 err = 0;
1476 sk = sock->sk;
1477 vsk = vsock_sk(sk);
1478
1479 switch (optname) {
1480 case SO_VM_SOCKETS_BUFFER_SIZE:
1481 val = transport->get_buffer_size(vsk);
1482 COPY_OUT(val);
1483 break;
1484
1485 case SO_VM_SOCKETS_BUFFER_MAX_SIZE:
1486 val = transport->get_max_buffer_size(vsk);
1487 COPY_OUT(val);
1488 break;
1489
1490 case SO_VM_SOCKETS_BUFFER_MIN_SIZE:
1491 val = transport->get_min_buffer_size(vsk);
1492 COPY_OUT(val);
1493 break;
1494
1495 case SO_VM_SOCKETS_CONNECT_TIMEOUT: {
1496 struct __kernel_old_timeval tv;
1497 tv.tv_sec = vsk->connect_timeout / HZ;
1498 tv.tv_usec =
1499 (vsk->connect_timeout -
1500 tv.tv_sec * HZ) * (1000000 / HZ);
1501 COPY_OUT(tv);
1502 break;
1503 }
1504 default:
1505 return -ENOPROTOOPT;
1506 }
1507
1508 err = put_user(len, optlen);
1509 if (err != 0)
1510 return -EFAULT;
1511
1512 #undef COPY_OUT
1513
1514 return 0;
1515 }
1516
vsock_stream_sendmsg(struct socket * sock,struct msghdr * msg,size_t len)1517 static int vsock_stream_sendmsg(struct socket *sock, struct msghdr *msg,
1518 size_t len)
1519 {
1520 struct sock *sk;
1521 struct vsock_sock *vsk;
1522 ssize_t total_written;
1523 long timeout;
1524 int err;
1525 struct vsock_transport_send_notify_data send_data;
1526 DEFINE_WAIT_FUNC(wait, woken_wake_function);
1527
1528 sk = sock->sk;
1529 vsk = vsock_sk(sk);
1530 total_written = 0;
1531 err = 0;
1532
1533 if (msg->msg_flags & MSG_OOB)
1534 return -EOPNOTSUPP;
1535
1536 lock_sock(sk);
1537
1538 /* Callers should not provide a destination with stream sockets. */
1539 if (msg->msg_namelen) {
1540 err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
1541 goto out;
1542 }
1543
1544 /* Send data only if both sides are not shutdown in the direction. */
1545 if (sk->sk_shutdown & SEND_SHUTDOWN ||
1546 vsk->peer_shutdown & RCV_SHUTDOWN) {
1547 err = -EPIPE;
1548 goto out;
1549 }
1550
1551 if (sk->sk_state != TCP_ESTABLISHED ||
1552 !vsock_addr_bound(&vsk->local_addr)) {
1553 err = -ENOTCONN;
1554 goto out;
1555 }
1556
1557 if (!vsock_addr_bound(&vsk->remote_addr)) {
1558 err = -EDESTADDRREQ;
1559 goto out;
1560 }
1561
1562 /* Wait for room in the produce queue to enqueue our user's data. */
1563 timeout = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1564
1565 err = transport->notify_send_init(vsk, &send_data);
1566 if (err < 0)
1567 goto out;
1568
1569 while (total_written < len) {
1570 ssize_t written;
1571
1572 add_wait_queue(sk_sleep(sk), &wait);
1573 while (vsock_stream_has_space(vsk) == 0 &&
1574 sk->sk_err == 0 &&
1575 !(sk->sk_shutdown & SEND_SHUTDOWN) &&
1576 !(vsk->peer_shutdown & RCV_SHUTDOWN)) {
1577
1578 /* Don't wait for non-blocking sockets. */
1579 if (timeout == 0) {
1580 err = -EAGAIN;
1581 remove_wait_queue(sk_sleep(sk), &wait);
1582 goto out_err;
1583 }
1584
1585 err = transport->notify_send_pre_block(vsk, &send_data);
1586 if (err < 0) {
1587 remove_wait_queue(sk_sleep(sk), &wait);
1588 goto out_err;
1589 }
1590
1591 release_sock(sk);
1592 timeout = wait_woken(&wait, TASK_INTERRUPTIBLE, timeout);
1593 lock_sock(sk);
1594 if (signal_pending(current)) {
1595 err = sock_intr_errno(timeout);
1596 remove_wait_queue(sk_sleep(sk), &wait);
1597 goto out_err;
1598 } else if (timeout == 0) {
1599 err = -EAGAIN;
1600 remove_wait_queue(sk_sleep(sk), &wait);
1601 goto out_err;
1602 }
1603 }
1604 remove_wait_queue(sk_sleep(sk), &wait);
1605
1606 /* These checks occur both as part of and after the loop
1607 * conditional since we need to check before and after
1608 * sleeping.
1609 */
1610 if (sk->sk_err) {
1611 err = -sk->sk_err;
1612 goto out_err;
1613 } else if ((sk->sk_shutdown & SEND_SHUTDOWN) ||
1614 (vsk->peer_shutdown & RCV_SHUTDOWN)) {
1615 err = -EPIPE;
1616 goto out_err;
1617 }
1618
1619 err = transport->notify_send_pre_enqueue(vsk, &send_data);
1620 if (err < 0)
1621 goto out_err;
1622
1623 /* Note that enqueue will only write as many bytes as are free
1624 * in the produce queue, so we don't need to ensure len is
1625 * smaller than the queue size. It is the caller's
1626 * responsibility to check how many bytes we were able to send.
1627 */
1628
1629 written = transport->stream_enqueue(
1630 vsk, msg,
1631 len - total_written);
1632 if (written < 0) {
1633 err = -ENOMEM;
1634 goto out_err;
1635 }
1636
1637 total_written += written;
1638
1639 err = transport->notify_send_post_enqueue(
1640 vsk, written, &send_data);
1641 if (err < 0)
1642 goto out_err;
1643
1644 }
1645
1646 out_err:
1647 if (total_written > 0)
1648 err = total_written;
1649 out:
1650 release_sock(sk);
1651 return err;
1652 }
1653
1654
1655 static int
vsock_stream_recvmsg(struct socket * sock,struct msghdr * msg,size_t len,int flags)1656 vsock_stream_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
1657 int flags)
1658 {
1659 struct sock *sk;
1660 struct vsock_sock *vsk;
1661 int err;
1662 size_t target;
1663 ssize_t copied;
1664 long timeout;
1665 struct vsock_transport_recv_notify_data recv_data;
1666
1667 DEFINE_WAIT(wait);
1668
1669 sk = sock->sk;
1670 vsk = vsock_sk(sk);
1671 err = 0;
1672
1673 lock_sock(sk);
1674
1675 if (sk->sk_state != TCP_ESTABLISHED) {
1676 /* Recvmsg is supposed to return 0 if a peer performs an
1677 * orderly shutdown. Differentiate between that case and when a
1678 * peer has not connected or a local shutdown occured with the
1679 * SOCK_DONE flag.
1680 */
1681 if (sock_flag(sk, SOCK_DONE))
1682 err = 0;
1683 else
1684 err = -ENOTCONN;
1685
1686 goto out;
1687 }
1688
1689 if (flags & MSG_OOB) {
1690 err = -EOPNOTSUPP;
1691 goto out;
1692 }
1693
1694 /* We don't check peer_shutdown flag here since peer may actually shut
1695 * down, but there can be data in the queue that a local socket can
1696 * receive.
1697 */
1698 if (sk->sk_shutdown & RCV_SHUTDOWN) {
1699 err = 0;
1700 goto out;
1701 }
1702
1703 /* It is valid on Linux to pass in a zero-length receive buffer. This
1704 * is not an error. We may as well bail out now.
1705 */
1706 if (!len) {
1707 err = 0;
1708 goto out;
1709 }
1710
1711 /* We must not copy less than target bytes into the user's buffer
1712 * before returning successfully, so we wait for the consume queue to
1713 * have that much data to consume before dequeueing. Note that this
1714 * makes it impossible to handle cases where target is greater than the
1715 * queue size.
1716 */
1717 target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
1718 if (target >= transport->stream_rcvhiwat(vsk)) {
1719 err = -ENOMEM;
1720 goto out;
1721 }
1722 timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1723 copied = 0;
1724
1725 err = transport->notify_recv_init(vsk, target, &recv_data);
1726 if (err < 0)
1727 goto out;
1728
1729
1730 while (1) {
1731 s64 ready;
1732
1733 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1734 ready = vsock_stream_has_data(vsk);
1735
1736 if (ready == 0) {
1737 if (sk->sk_err != 0 ||
1738 (sk->sk_shutdown & RCV_SHUTDOWN) ||
1739 (vsk->peer_shutdown & SEND_SHUTDOWN)) {
1740 finish_wait(sk_sleep(sk), &wait);
1741 break;
1742 }
1743 /* Don't wait for non-blocking sockets. */
1744 if (timeout == 0) {
1745 err = -EAGAIN;
1746 finish_wait(sk_sleep(sk), &wait);
1747 break;
1748 }
1749
1750 err = transport->notify_recv_pre_block(
1751 vsk, target, &recv_data);
1752 if (err < 0) {
1753 finish_wait(sk_sleep(sk), &wait);
1754 break;
1755 }
1756 release_sock(sk);
1757 timeout = schedule_timeout(timeout);
1758 lock_sock(sk);
1759
1760 if (signal_pending(current)) {
1761 err = sock_intr_errno(timeout);
1762 finish_wait(sk_sleep(sk), &wait);
1763 break;
1764 } else if (timeout == 0) {
1765 err = -EAGAIN;
1766 finish_wait(sk_sleep(sk), &wait);
1767 break;
1768 }
1769 } else {
1770 ssize_t read;
1771
1772 finish_wait(sk_sleep(sk), &wait);
1773
1774 if (ready < 0) {
1775 /* Invalid queue pair content. XXX This should
1776 * be changed to a connection reset in a later
1777 * change.
1778 */
1779
1780 err = -ENOMEM;
1781 goto out;
1782 }
1783
1784 err = transport->notify_recv_pre_dequeue(
1785 vsk, target, &recv_data);
1786 if (err < 0)
1787 break;
1788
1789 read = transport->stream_dequeue(
1790 vsk, msg,
1791 len - copied, flags);
1792 if (read < 0) {
1793 err = -ENOMEM;
1794 break;
1795 }
1796
1797 copied += read;
1798
1799 err = transport->notify_recv_post_dequeue(
1800 vsk, target, read,
1801 !(flags & MSG_PEEK), &recv_data);
1802 if (err < 0)
1803 goto out;
1804
1805 if (read >= target || flags & MSG_PEEK)
1806 break;
1807
1808 target -= read;
1809 }
1810 }
1811
1812 if (sk->sk_err)
1813 err = -sk->sk_err;
1814 else if (sk->sk_shutdown & RCV_SHUTDOWN)
1815 err = 0;
1816
1817 if (copied > 0)
1818 err = copied;
1819
1820 out:
1821 release_sock(sk);
1822 return err;
1823 }
1824
1825 static const struct proto_ops vsock_stream_ops = {
1826 .family = PF_VSOCK,
1827 .owner = THIS_MODULE,
1828 .release = vsock_release,
1829 .bind = vsock_bind,
1830 .connect = vsock_stream_connect,
1831 .socketpair = sock_no_socketpair,
1832 .accept = vsock_accept,
1833 .getname = vsock_getname,
1834 .poll = vsock_poll,
1835 .ioctl = sock_no_ioctl,
1836 .listen = vsock_listen,
1837 .shutdown = vsock_shutdown,
1838 .setsockopt = vsock_stream_setsockopt,
1839 .getsockopt = vsock_stream_getsockopt,
1840 .sendmsg = vsock_stream_sendmsg,
1841 .recvmsg = vsock_stream_recvmsg,
1842 .mmap = sock_no_mmap,
1843 .sendpage = sock_no_sendpage,
1844 };
1845
vsock_create(struct net * net,struct socket * sock,int protocol,int kern)1846 static int vsock_create(struct net *net, struct socket *sock,
1847 int protocol, int kern)
1848 {
1849 if (!sock)
1850 return -EINVAL;
1851
1852 if (protocol && protocol != PF_VSOCK)
1853 return -EPROTONOSUPPORT;
1854
1855 switch (sock->type) {
1856 case SOCK_DGRAM:
1857 sock->ops = &vsock_dgram_ops;
1858 break;
1859 case SOCK_STREAM:
1860 sock->ops = &vsock_stream_ops;
1861 break;
1862 default:
1863 return -ESOCKTNOSUPPORT;
1864 }
1865
1866 sock->state = SS_UNCONNECTED;
1867
1868 return __vsock_create(net, sock, NULL, GFP_KERNEL, 0, kern) ? 0 : -ENOMEM;
1869 }
1870
1871 static const struct net_proto_family vsock_family_ops = {
1872 .family = AF_VSOCK,
1873 .create = vsock_create,
1874 .owner = THIS_MODULE,
1875 };
1876
vsock_dev_do_ioctl(struct file * filp,unsigned int cmd,void __user * ptr)1877 static long vsock_dev_do_ioctl(struct file *filp,
1878 unsigned int cmd, void __user *ptr)
1879 {
1880 u32 __user *p = ptr;
1881 int retval = 0;
1882
1883 switch (cmd) {
1884 case IOCTL_VM_SOCKETS_GET_LOCAL_CID:
1885 if (put_user(transport->get_local_cid(), p) != 0)
1886 retval = -EFAULT;
1887 break;
1888
1889 default:
1890 pr_err("Unknown ioctl %d\n", cmd);
1891 retval = -EINVAL;
1892 }
1893
1894 return retval;
1895 }
1896
vsock_dev_ioctl(struct file * filp,unsigned int cmd,unsigned long arg)1897 static long vsock_dev_ioctl(struct file *filp,
1898 unsigned int cmd, unsigned long arg)
1899 {
1900 return vsock_dev_do_ioctl(filp, cmd, (void __user *)arg);
1901 }
1902
1903 #ifdef CONFIG_COMPAT
vsock_dev_compat_ioctl(struct file * filp,unsigned int cmd,unsigned long arg)1904 static long vsock_dev_compat_ioctl(struct file *filp,
1905 unsigned int cmd, unsigned long arg)
1906 {
1907 return vsock_dev_do_ioctl(filp, cmd, compat_ptr(arg));
1908 }
1909 #endif
1910
1911 static const struct file_operations vsock_device_ops = {
1912 .owner = THIS_MODULE,
1913 .unlocked_ioctl = vsock_dev_ioctl,
1914 #ifdef CONFIG_COMPAT
1915 .compat_ioctl = vsock_dev_compat_ioctl,
1916 #endif
1917 .open = nonseekable_open,
1918 };
1919
1920 static struct miscdevice vsock_device = {
1921 .name = "vsock",
1922 .fops = &vsock_device_ops,
1923 };
1924
__vsock_core_init(const struct vsock_transport * t,struct module * owner)1925 int __vsock_core_init(const struct vsock_transport *t, struct module *owner)
1926 {
1927 int err = mutex_lock_interruptible(&vsock_register_mutex);
1928
1929 if (err)
1930 return err;
1931
1932 if (transport) {
1933 err = -EBUSY;
1934 goto err_busy;
1935 }
1936
1937 /* Transport must be the owner of the protocol so that it can't
1938 * unload while there are open sockets.
1939 */
1940 vsock_proto.owner = owner;
1941 transport = t;
1942
1943 vsock_device.minor = MISC_DYNAMIC_MINOR;
1944 err = misc_register(&vsock_device);
1945 if (err) {
1946 pr_err("Failed to register misc device\n");
1947 goto err_reset_transport;
1948 }
1949
1950 err = proto_register(&vsock_proto, 1); /* we want our slab */
1951 if (err) {
1952 pr_err("Cannot register vsock protocol\n");
1953 goto err_deregister_misc;
1954 }
1955
1956 err = sock_register(&vsock_family_ops);
1957 if (err) {
1958 pr_err("could not register af_vsock (%d) address family: %d\n",
1959 AF_VSOCK, err);
1960 goto err_unregister_proto;
1961 }
1962
1963 mutex_unlock(&vsock_register_mutex);
1964 return 0;
1965
1966 err_unregister_proto:
1967 proto_unregister(&vsock_proto);
1968 err_deregister_misc:
1969 misc_deregister(&vsock_device);
1970 err_reset_transport:
1971 transport = NULL;
1972 err_busy:
1973 mutex_unlock(&vsock_register_mutex);
1974 return err;
1975 }
1976 EXPORT_SYMBOL_GPL(__vsock_core_init);
1977
vsock_core_exit(void)1978 void vsock_core_exit(void)
1979 {
1980 mutex_lock(&vsock_register_mutex);
1981
1982 misc_deregister(&vsock_device);
1983 sock_unregister(AF_VSOCK);
1984 proto_unregister(&vsock_proto);
1985
1986 /* We do not want the assignment below re-ordered. */
1987 mb();
1988 transport = NULL;
1989
1990 mutex_unlock(&vsock_register_mutex);
1991 }
1992 EXPORT_SYMBOL_GPL(vsock_core_exit);
1993
vsock_core_get_transport(void)1994 const struct vsock_transport *vsock_core_get_transport(void)
1995 {
1996 /* vsock_register_mutex not taken since only the transport uses this
1997 * function and only while registered.
1998 */
1999 return transport;
2000 }
2001 EXPORT_SYMBOL_GPL(vsock_core_get_transport);
2002
vsock_exit(void)2003 static void __exit vsock_exit(void)
2004 {
2005 /* Do nothing. This function makes this module removable. */
2006 }
2007
2008 module_init(vsock_init_tables);
2009 module_exit(vsock_exit);
2010
2011 MODULE_AUTHOR("VMware, Inc.");
2012 MODULE_DESCRIPTION("VMware Virtual Socket Family");
2013 MODULE_VERSION("1.0.2.0-k");
2014 MODULE_LICENSE("GPL v2");
2015