xref: /linux/net/unix/af_unix.c (revision 0359338fd8cf1a2dc001d0cd69c331c17decee88)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * NET4:	Implementation of BSD Unix domain sockets.
4  *
5  * Authors:	Alan Cox, <alan@lxorguk.ukuu.org.uk>
6  *
7  * Fixes:
8  *		Linus Torvalds	:	Assorted bug cures.
9  *		Niibe Yutaka	:	async I/O support.
10  *		Carsten Paeth	:	PF_UNIX check, address fixes.
11  *		Alan Cox	:	Limit size of allocated blocks.
12  *		Alan Cox	:	Fixed the stupid socketpair bug.
13  *		Alan Cox	:	BSD compatibility fine tuning.
14  *		Alan Cox	:	Fixed a bug in connect when interrupted.
15  *		Alan Cox	:	Sorted out a proper draft version of
16  *					file descriptor passing hacked up from
17  *					Mike Shaver's work.
18  *		Marty Leisner	:	Fixes to fd passing
19  *		Nick Nevin	:	recvmsg bugfix.
20  *		Alan Cox	:	Started proper garbage collector
21  *		Heiko EiBfeldt	:	Missing verify_area check
22  *		Alan Cox	:	Started POSIXisms
23  *		Andreas Schwab	:	Replace inode by dentry for proper
24  *					reference counting
25  *		Kirk Petersen	:	Made this a module
26  *	    Christoph Rohland	:	Elegant non-blocking accept/connect algorithm.
27  *					Lots of bug fixes.
28  *	     Alexey Kuznetosv	:	Repaired (I hope) bugs introduces
29  *					by above two patches.
30  *	     Andrea Arcangeli	:	If possible we block in connect(2)
31  *					if the max backlog of the listen socket
32  *					is been reached. This won't break
33  *					old apps and it will avoid huge amount
34  *					of socks hashed (this for unix_gc()
35  *					performances reasons).
36  *					Security fix that limits the max
37  *					number of socks to 2*max_files and
38  *					the number of skb queueable in the
39  *					dgram receiver.
40  *		Artur Skawina   :	Hash function optimizations
41  *	     Alexey Kuznetsov   :	Full scale SMP. Lot of bugs are introduced 8)
42  *	      Malcolm Beattie   :	Set peercred for socketpair
43  *	     Michal Ostrowski   :       Module initialization cleanup.
44  *	     Arnaldo C. Melo	:	Remove MOD_{INC,DEC}_USE_COUNT,
45  *	     				the core infrastructure is doing that
46  *	     				for all net proto families now (2.5.69+)
47  *
48  * Known differences from reference BSD that was tested:
49  *
50  *	[TO FIX]
51  *	ECONNREFUSED is not returned from one end of a connected() socket to the
52  *		other the moment one end closes.
53  *	fstat() doesn't return st_dev=0, and give the blksize as high water mark
54  *		and a fake inode identifier (nor the BSD first socket fstat twice bug).
55  *	[NOT TO FIX]
56  *	accept() returns a path name even if the connecting socket has closed
57  *		in the meantime (BSD loses the path and gives up).
58  *	accept() returns 0 length path for an unbound connector. BSD returns 16
59  *		and a null first byte in the path (but not for gethost/peername - BSD bug ??)
60  *	socketpair(...SOCK_RAW..) doesn't panic the kernel.
61  *	BSD af_unix apparently has connect forgetting to block properly.
62  *		(need to check this with the POSIX spec in detail)
63  *
64  * Differences from 2.0.0-11-... (ANK)
65  *	Bug fixes and improvements.
66  *		- client shutdown killed server socket.
67  *		- removed all useless cli/sti pairs.
68  *
69  *	Semantic changes/extensions.
70  *		- generic control message passing.
71  *		- SCM_CREDENTIALS control message.
72  *		- "Abstract" (not FS based) socket bindings.
73  *		  Abstract names are sequences of bytes (not zero terminated)
74  *		  started by 0, so that this name space does not intersect
75  *		  with BSD names.
76  */
77 
78 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
79 
80 #include <linux/bpf-cgroup.h>
81 #include <linux/btf_ids.h>
82 #include <linux/dcache.h>
83 #include <linux/errno.h>
84 #include <linux/fcntl.h>
85 #include <linux/file.h>
86 #include <linux/filter.h>
87 #include <linux/fs.h>
88 #include <linux/fs_struct.h>
89 #include <linux/init.h>
90 #include <linux/kernel.h>
91 #include <linux/mount.h>
92 #include <linux/namei.h>
93 #include <linux/net.h>
94 #include <linux/pidfs.h>
95 #include <linux/poll.h>
96 #include <linux/proc_fs.h>
97 #include <linux/sched/signal.h>
98 #include <linux/security.h>
99 #include <linux/seq_file.h>
100 #include <linux/skbuff.h>
101 #include <linux/slab.h>
102 #include <linux/socket.h>
103 #include <linux/splice.h>
104 #include <linux/string.h>
105 #include <linux/uaccess.h>
106 #include <net/af_unix.h>
107 #include <net/net_namespace.h>
108 #include <net/scm.h>
109 #include <net/tcp_states.h>
110 #include <uapi/linux/sockios.h>
111 #include <uapi/linux/termios.h>
112 
113 #include "af_unix.h"
114 
115 static atomic_long_t unix_nr_socks;
116 static struct hlist_head bsd_socket_buckets[UNIX_HASH_SIZE / 2];
117 static spinlock_t bsd_socket_locks[UNIX_HASH_SIZE / 2];
118 
119 /* SMP locking strategy:
120  *    hash table is protected with spinlock.
121  *    each socket state is protected by separate spinlock.
122  */
123 #ifdef CONFIG_PROVE_LOCKING
124 #define cmp_ptr(l, r)	(((l) > (r)) - ((l) < (r)))
125 
126 static int unix_table_lock_cmp_fn(const struct lockdep_map *a,
127 				  const struct lockdep_map *b)
128 {
129 	return cmp_ptr(a, b);
130 }
131 
132 static int unix_state_lock_cmp_fn(const struct lockdep_map *_a,
133 				  const struct lockdep_map *_b)
134 {
135 	const struct unix_sock *a, *b;
136 
137 	a = container_of(_a, struct unix_sock, lock.dep_map);
138 	b = container_of(_b, struct unix_sock, lock.dep_map);
139 
140 	if (a->sk.sk_state == TCP_LISTEN) {
141 		/* unix_stream_connect(): Before the 2nd unix_state_lock(),
142 		 *
143 		 *   1. a is TCP_LISTEN.
144 		 *   2. b is not a.
145 		 *   3. concurrent connect(b -> a) must fail.
146 		 *
147 		 * Except for 2. & 3., the b's state can be any possible
148 		 * value due to concurrent connect() or listen().
149 		 *
150 		 * 2. is detected in debug_spin_lock_before(), and 3. cannot
151 		 * be expressed as lock_cmp_fn.
152 		 */
153 		switch (b->sk.sk_state) {
154 		case TCP_CLOSE:
155 		case TCP_ESTABLISHED:
156 		case TCP_LISTEN:
157 			return -1;
158 		default:
159 			/* Invalid case. */
160 			return 0;
161 		}
162 	}
163 
164 	/* Should never happen.  Just to be symmetric. */
165 	if (b->sk.sk_state == TCP_LISTEN) {
166 		switch (b->sk.sk_state) {
167 		case TCP_CLOSE:
168 		case TCP_ESTABLISHED:
169 			return 1;
170 		default:
171 			return 0;
172 		}
173 	}
174 
175 	/* unix_state_double_lock(): ascending address order. */
176 	return cmp_ptr(a, b);
177 }
178 
179 static int unix_recvq_lock_cmp_fn(const struct lockdep_map *_a,
180 				  const struct lockdep_map *_b)
181 {
182 	const struct sock *a, *b;
183 
184 	a = container_of(_a, struct sock, sk_receive_queue.lock.dep_map);
185 	b = container_of(_b, struct sock, sk_receive_queue.lock.dep_map);
186 
187 	/* unix_collect_skb(): listener -> embryo order. */
188 	if (a->sk_state == TCP_LISTEN && unix_sk(b)->listener == a)
189 		return -1;
190 
191 	/* Should never happen.  Just to be symmetric. */
192 	if (b->sk_state == TCP_LISTEN && unix_sk(a)->listener == b)
193 		return 1;
194 
195 	return 0;
196 }
197 #endif
198 
199 static unsigned int unix_unbound_hash(struct sock *sk)
200 {
201 	unsigned long hash = (unsigned long)sk;
202 
203 	hash ^= hash >> 16;
204 	hash ^= hash >> 8;
205 	hash ^= sk->sk_type;
206 
207 	return hash & UNIX_HASH_MOD;
208 }
209 
210 static unsigned int unix_bsd_hash(struct inode *i)
211 {
212 	return i->i_ino & UNIX_HASH_MOD;
213 }
214 
215 static unsigned int unix_abstract_hash(struct sockaddr_un *sunaddr,
216 				       int addr_len, int type)
217 {
218 	__wsum csum = csum_partial(sunaddr, addr_len, 0);
219 	unsigned int hash;
220 
221 	hash = (__force unsigned int)csum_fold(csum);
222 	hash ^= hash >> 8;
223 	hash ^= type;
224 
225 	return UNIX_HASH_MOD + 1 + (hash & UNIX_HASH_MOD);
226 }
227 
228 static void unix_table_double_lock(struct net *net,
229 				   unsigned int hash1, unsigned int hash2)
230 {
231 	if (hash1 == hash2) {
232 		spin_lock(&net->unx.table.locks[hash1]);
233 		return;
234 	}
235 
236 	if (hash1 > hash2)
237 		swap(hash1, hash2);
238 
239 	spin_lock(&net->unx.table.locks[hash1]);
240 	spin_lock(&net->unx.table.locks[hash2]);
241 }
242 
243 static void unix_table_double_unlock(struct net *net,
244 				     unsigned int hash1, unsigned int hash2)
245 {
246 	if (hash1 == hash2) {
247 		spin_unlock(&net->unx.table.locks[hash1]);
248 		return;
249 	}
250 
251 	spin_unlock(&net->unx.table.locks[hash1]);
252 	spin_unlock(&net->unx.table.locks[hash2]);
253 }
254 
255 #ifdef CONFIG_SECURITY_NETWORK
256 static void unix_get_secdata(struct scm_cookie *scm, struct sk_buff *skb)
257 {
258 	UNIXCB(skb).secid = scm->secid;
259 }
260 
261 static inline void unix_set_secdata(struct scm_cookie *scm, struct sk_buff *skb)
262 {
263 	scm->secid = UNIXCB(skb).secid;
264 }
265 
266 static inline bool unix_secdata_eq(struct scm_cookie *scm, struct sk_buff *skb)
267 {
268 	return (scm->secid == UNIXCB(skb).secid);
269 }
270 #else
271 static inline void unix_get_secdata(struct scm_cookie *scm, struct sk_buff *skb)
272 { }
273 
274 static inline void unix_set_secdata(struct scm_cookie *scm, struct sk_buff *skb)
275 { }
276 
277 static inline bool unix_secdata_eq(struct scm_cookie *scm, struct sk_buff *skb)
278 {
279 	return true;
280 }
281 #endif /* CONFIG_SECURITY_NETWORK */
282 
283 static inline int unix_may_send(struct sock *sk, struct sock *osk)
284 {
285 	return !unix_peer(osk) || unix_peer(osk) == sk;
286 }
287 
288 static inline int unix_recvq_full_lockless(const struct sock *sk)
289 {
290 	return skb_queue_len_lockless(&sk->sk_receive_queue) > sk->sk_max_ack_backlog;
291 }
292 
293 struct sock *unix_peer_get(struct sock *s)
294 {
295 	struct sock *peer;
296 
297 	unix_state_lock(s);
298 	peer = unix_peer(s);
299 	if (peer)
300 		sock_hold(peer);
301 	unix_state_unlock(s);
302 	return peer;
303 }
304 EXPORT_SYMBOL_GPL(unix_peer_get);
305 
306 static struct unix_address *unix_create_addr(struct sockaddr_un *sunaddr,
307 					     int addr_len)
308 {
309 	struct unix_address *addr;
310 
311 	addr = kmalloc(sizeof(*addr) + addr_len, GFP_KERNEL);
312 	if (!addr)
313 		return NULL;
314 
315 	refcount_set(&addr->refcnt, 1);
316 	addr->len = addr_len;
317 	memcpy(addr->name, sunaddr, addr_len);
318 
319 	return addr;
320 }
321 
322 static inline void unix_release_addr(struct unix_address *addr)
323 {
324 	if (refcount_dec_and_test(&addr->refcnt))
325 		kfree(addr);
326 }
327 
328 /*
329  *	Check unix socket name:
330  *		- should be not zero length.
331  *	        - if started by not zero, should be NULL terminated (FS object)
332  *		- if started by zero, it is abstract name.
333  */
334 
335 static int unix_validate_addr(struct sockaddr_un *sunaddr, int addr_len)
336 {
337 	if (addr_len <= offsetof(struct sockaddr_un, sun_path) ||
338 	    addr_len > sizeof(*sunaddr))
339 		return -EINVAL;
340 
341 	if (sunaddr->sun_family != AF_UNIX)
342 		return -EINVAL;
343 
344 	return 0;
345 }
346 
347 static int unix_mkname_bsd(struct sockaddr_un *sunaddr, int addr_len)
348 {
349 	struct sockaddr_storage *addr = (struct sockaddr_storage *)sunaddr;
350 	short offset = offsetof(struct sockaddr_storage, __data);
351 
352 	BUILD_BUG_ON(offset != offsetof(struct sockaddr_un, sun_path));
353 
354 	/* This may look like an off by one error but it is a bit more
355 	 * subtle.  108 is the longest valid AF_UNIX path for a binding.
356 	 * sun_path[108] doesn't as such exist.  However in kernel space
357 	 * we are guaranteed that it is a valid memory location in our
358 	 * kernel address buffer because syscall functions always pass
359 	 * a pointer of struct sockaddr_storage which has a bigger buffer
360 	 * than 108.  Also, we must terminate sun_path for strlen() in
361 	 * getname_kernel().
362 	 */
363 	addr->__data[addr_len - offset] = 0;
364 
365 	/* Don't pass sunaddr->sun_path to strlen().  Otherwise, 108 will
366 	 * cause panic if CONFIG_FORTIFY_SOURCE=y.  Let __fortify_strlen()
367 	 * know the actual buffer.
368 	 */
369 	return strlen(addr->__data) + offset + 1;
370 }
371 
372 static void __unix_remove_socket(struct sock *sk)
373 {
374 	sk_del_node_init(sk);
375 }
376 
377 static void __unix_insert_socket(struct net *net, struct sock *sk)
378 {
379 	DEBUG_NET_WARN_ON_ONCE(!sk_unhashed(sk));
380 	sk_add_node(sk, &net->unx.table.buckets[sk->sk_hash]);
381 }
382 
383 static void __unix_set_addr_hash(struct net *net, struct sock *sk,
384 				 struct unix_address *addr, unsigned int hash)
385 {
386 	__unix_remove_socket(sk);
387 	smp_store_release(&unix_sk(sk)->addr, addr);
388 
389 	sk->sk_hash = hash;
390 	__unix_insert_socket(net, sk);
391 }
392 
393 static void unix_remove_socket(struct net *net, struct sock *sk)
394 {
395 	spin_lock(&net->unx.table.locks[sk->sk_hash]);
396 	__unix_remove_socket(sk);
397 	spin_unlock(&net->unx.table.locks[sk->sk_hash]);
398 }
399 
400 static void unix_insert_unbound_socket(struct net *net, struct sock *sk)
401 {
402 	spin_lock(&net->unx.table.locks[sk->sk_hash]);
403 	__unix_insert_socket(net, sk);
404 	spin_unlock(&net->unx.table.locks[sk->sk_hash]);
405 }
406 
407 static void unix_insert_bsd_socket(struct sock *sk)
408 {
409 	spin_lock(&bsd_socket_locks[sk->sk_hash]);
410 	sk_add_bind_node(sk, &bsd_socket_buckets[sk->sk_hash]);
411 	spin_unlock(&bsd_socket_locks[sk->sk_hash]);
412 }
413 
414 static void unix_remove_bsd_socket(struct sock *sk)
415 {
416 	if (!hlist_unhashed(&sk->sk_bind_node)) {
417 		spin_lock(&bsd_socket_locks[sk->sk_hash]);
418 		__sk_del_bind_node(sk);
419 		spin_unlock(&bsd_socket_locks[sk->sk_hash]);
420 
421 		sk_node_init(&sk->sk_bind_node);
422 	}
423 }
424 
425 static struct sock *__unix_find_socket_byname(struct net *net,
426 					      struct sockaddr_un *sunname,
427 					      int len, unsigned int hash)
428 {
429 	struct sock *s;
430 
431 	sk_for_each(s, &net->unx.table.buckets[hash]) {
432 		struct unix_sock *u = unix_sk(s);
433 
434 		if (u->addr->len == len &&
435 		    !memcmp(u->addr->name, sunname, len))
436 			return s;
437 	}
438 	return NULL;
439 }
440 
441 static inline struct sock *unix_find_socket_byname(struct net *net,
442 						   struct sockaddr_un *sunname,
443 						   int len, unsigned int hash)
444 {
445 	struct sock *s;
446 
447 	spin_lock(&net->unx.table.locks[hash]);
448 	s = __unix_find_socket_byname(net, sunname, len, hash);
449 	if (s)
450 		sock_hold(s);
451 	spin_unlock(&net->unx.table.locks[hash]);
452 	return s;
453 }
454 
455 static struct sock *unix_find_socket_byinode(struct inode *i)
456 {
457 	unsigned int hash = unix_bsd_hash(i);
458 	struct sock *s;
459 
460 	spin_lock(&bsd_socket_locks[hash]);
461 	sk_for_each_bound(s, &bsd_socket_buckets[hash]) {
462 		struct dentry *dentry = unix_sk(s)->path.dentry;
463 
464 		if (dentry && d_backing_inode(dentry) == i) {
465 			sock_hold(s);
466 			spin_unlock(&bsd_socket_locks[hash]);
467 			return s;
468 		}
469 	}
470 	spin_unlock(&bsd_socket_locks[hash]);
471 	return NULL;
472 }
473 
474 /* Support code for asymmetrically connected dgram sockets
475  *
476  * If a datagram socket is connected to a socket not itself connected
477  * to the first socket (eg, /dev/log), clients may only enqueue more
478  * messages if the present receive queue of the server socket is not
479  * "too large". This means there's a second writeability condition
480  * poll and sendmsg need to test. The dgram recv code will do a wake
481  * up on the peer_wait wait queue of a socket upon reception of a
482  * datagram which needs to be propagated to sleeping would-be writers
483  * since these might not have sent anything so far. This can't be
484  * accomplished via poll_wait because the lifetime of the server
485  * socket might be less than that of its clients if these break their
486  * association with it or if the server socket is closed while clients
487  * are still connected to it and there's no way to inform "a polling
488  * implementation" that it should let go of a certain wait queue
489  *
490  * In order to propagate a wake up, a wait_queue_entry_t of the client
491  * socket is enqueued on the peer_wait queue of the server socket
492  * whose wake function does a wake_up on the ordinary client socket
493  * wait queue. This connection is established whenever a write (or
494  * poll for write) hit the flow control condition and broken when the
495  * association to the server socket is dissolved or after a wake up
496  * was relayed.
497  */
498 
499 static int unix_dgram_peer_wake_relay(wait_queue_entry_t *q, unsigned mode, int flags,
500 				      void *key)
501 {
502 	struct unix_sock *u;
503 	wait_queue_head_t *u_sleep;
504 
505 	u = container_of(q, struct unix_sock, peer_wake);
506 
507 	__remove_wait_queue(&unix_sk(u->peer_wake.private)->peer_wait,
508 			    q);
509 	u->peer_wake.private = NULL;
510 
511 	/* relaying can only happen while the wq still exists */
512 	u_sleep = sk_sleep(&u->sk);
513 	if (u_sleep)
514 		wake_up_interruptible_poll(u_sleep, key_to_poll(key));
515 
516 	return 0;
517 }
518 
519 static int unix_dgram_peer_wake_connect(struct sock *sk, struct sock *other)
520 {
521 	struct unix_sock *u, *u_other;
522 	int rc;
523 
524 	u = unix_sk(sk);
525 	u_other = unix_sk(other);
526 	rc = 0;
527 	spin_lock(&u_other->peer_wait.lock);
528 
529 	if (!u->peer_wake.private) {
530 		u->peer_wake.private = other;
531 		__add_wait_queue(&u_other->peer_wait, &u->peer_wake);
532 
533 		rc = 1;
534 	}
535 
536 	spin_unlock(&u_other->peer_wait.lock);
537 	return rc;
538 }
539 
540 static void unix_dgram_peer_wake_disconnect(struct sock *sk,
541 					    struct sock *other)
542 {
543 	struct unix_sock *u, *u_other;
544 
545 	u = unix_sk(sk);
546 	u_other = unix_sk(other);
547 	spin_lock(&u_other->peer_wait.lock);
548 
549 	if (u->peer_wake.private == other) {
550 		__remove_wait_queue(&u_other->peer_wait, &u->peer_wake);
551 		u->peer_wake.private = NULL;
552 	}
553 
554 	spin_unlock(&u_other->peer_wait.lock);
555 }
556 
557 static void unix_dgram_peer_wake_disconnect_wakeup(struct sock *sk,
558 						   struct sock *other)
559 {
560 	unix_dgram_peer_wake_disconnect(sk, other);
561 	wake_up_interruptible_poll(sk_sleep(sk),
562 				   EPOLLOUT |
563 				   EPOLLWRNORM |
564 				   EPOLLWRBAND);
565 }
566 
567 /* preconditions:
568  *	- unix_peer(sk) == other
569  *	- association is stable
570  */
571 static int unix_dgram_peer_wake_me(struct sock *sk, struct sock *other)
572 {
573 	int connected;
574 
575 	connected = unix_dgram_peer_wake_connect(sk, other);
576 
577 	/* If other is SOCK_DEAD, we want to make sure we signal
578 	 * POLLOUT, such that a subsequent write() can get a
579 	 * -ECONNREFUSED. Otherwise, if we haven't queued any skbs
580 	 * to other and its full, we will hang waiting for POLLOUT.
581 	 */
582 	if (unix_recvq_full_lockless(other) && !sock_flag(other, SOCK_DEAD))
583 		return 1;
584 
585 	if (connected)
586 		unix_dgram_peer_wake_disconnect(sk, other);
587 
588 	return 0;
589 }
590 
591 static int unix_writable(const struct sock *sk, unsigned char state)
592 {
593 	return state != TCP_LISTEN &&
594 		(refcount_read(&sk->sk_wmem_alloc) << 2) <= READ_ONCE(sk->sk_sndbuf);
595 }
596 
597 static void unix_write_space(struct sock *sk)
598 {
599 	struct socket_wq *wq;
600 
601 	rcu_read_lock();
602 	if (unix_writable(sk, READ_ONCE(sk->sk_state))) {
603 		wq = rcu_dereference(sk->sk_wq);
604 		if (skwq_has_sleeper(wq))
605 			wake_up_interruptible_sync_poll(&wq->wait,
606 				EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND);
607 		sk_wake_async_rcu(sk, SOCK_WAKE_SPACE, POLL_OUT);
608 	}
609 	rcu_read_unlock();
610 }
611 
612 /* When dgram socket disconnects (or changes its peer), we clear its receive
613  * queue of packets arrived from previous peer. First, it allows to do
614  * flow control based only on wmem_alloc; second, sk connected to peer
615  * may receive messages only from that peer. */
616 static void unix_dgram_disconnected(struct sock *sk, struct sock *other)
617 {
618 	if (!skb_queue_empty(&sk->sk_receive_queue)) {
619 		skb_queue_purge_reason(&sk->sk_receive_queue,
620 				       SKB_DROP_REASON_UNIX_DISCONNECT);
621 
622 		wake_up_interruptible_all(&unix_sk(sk)->peer_wait);
623 
624 		/* If one link of bidirectional dgram pipe is disconnected,
625 		 * we signal error. Messages are lost. Do not make this,
626 		 * when peer was not connected to us.
627 		 */
628 		if (!sock_flag(other, SOCK_DEAD) && unix_peer(other) == sk) {
629 			WRITE_ONCE(other->sk_err, ECONNRESET);
630 			sk_error_report(other);
631 		}
632 	}
633 }
634 
635 static void unix_sock_destructor(struct sock *sk)
636 {
637 	struct unix_sock *u = unix_sk(sk);
638 
639 	skb_queue_purge_reason(&sk->sk_receive_queue, SKB_DROP_REASON_SOCKET_CLOSE);
640 
641 	DEBUG_NET_WARN_ON_ONCE(refcount_read(&sk->sk_wmem_alloc));
642 	DEBUG_NET_WARN_ON_ONCE(!sk_unhashed(sk));
643 	DEBUG_NET_WARN_ON_ONCE(sk->sk_socket);
644 	if (!sock_flag(sk, SOCK_DEAD)) {
645 		pr_info("Attempt to release alive unix socket: %p\n", sk);
646 		return;
647 	}
648 
649 	if (u->addr)
650 		unix_release_addr(u->addr);
651 
652 	atomic_long_dec(&unix_nr_socks);
653 	sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
654 #ifdef UNIX_REFCNT_DEBUG
655 	pr_debug("UNIX %p is destroyed, %ld are still alive.\n", sk,
656 		atomic_long_read(&unix_nr_socks));
657 #endif
658 }
659 
660 static unsigned int unix_skb_len(const struct sk_buff *skb)
661 {
662 	return skb->len - UNIXCB(skb).consumed;
663 }
664 
665 static void unix_release_sock(struct sock *sk, int embrion)
666 {
667 	struct unix_sock *u = unix_sk(sk);
668 	struct sock *skpair;
669 	struct sk_buff *skb;
670 	struct path path;
671 	int state;
672 
673 	unix_remove_socket(sock_net(sk), sk);
674 	unix_remove_bsd_socket(sk);
675 
676 	/* Clear state */
677 	unix_state_lock(sk);
678 	sock_orphan(sk);
679 	WRITE_ONCE(sk->sk_shutdown, SHUTDOWN_MASK);
680 	path	     = u->path;
681 	u->path.dentry = NULL;
682 	u->path.mnt = NULL;
683 	state = sk->sk_state;
684 	WRITE_ONCE(sk->sk_state, TCP_CLOSE);
685 
686 	skpair = unix_peer(sk);
687 	unix_peer(sk) = NULL;
688 
689 	unix_state_unlock(sk);
690 
691 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
692 	u->oob_skb = NULL;
693 #endif
694 
695 	wake_up_interruptible_all(&u->peer_wait);
696 
697 	if (skpair != NULL) {
698 		if (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET) {
699 			struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
700 
701 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
702 			if (skb && !unix_skb_len(skb))
703 				skb = skb_peek_next(skb, &sk->sk_receive_queue);
704 #endif
705 			unix_state_lock(skpair);
706 			/* No more writes */
707 			WRITE_ONCE(skpair->sk_shutdown, SHUTDOWN_MASK);
708 			if (skb || embrion)
709 				WRITE_ONCE(skpair->sk_err, ECONNRESET);
710 			unix_state_unlock(skpair);
711 			skpair->sk_state_change(skpair);
712 			sk_wake_async(skpair, SOCK_WAKE_WAITD, POLL_HUP);
713 		}
714 
715 		unix_dgram_peer_wake_disconnect(sk, skpair);
716 		sock_put(skpair); /* It may now die */
717 	}
718 
719 	/* Try to flush out this socket. Throw out buffers at least */
720 
721 	while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) {
722 		if (state == TCP_LISTEN)
723 			unix_release_sock(skb->sk, 1);
724 
725 		/* passed fds are erased in the kfree_skb hook */
726 		kfree_skb_reason(skb, SKB_DROP_REASON_SOCKET_CLOSE);
727 	}
728 
729 	if (path.dentry)
730 		path_put(&path);
731 
732 	sock_put(sk);
733 
734 	/* ---- Socket is dead now and most probably destroyed ---- */
735 
736 	unix_schedule_gc(NULL);
737 }
738 
739 struct unix_peercred {
740 	DECLARE_PIDS(peer_pid, PIDTYPE_TGID);
741 	const struct cred *peer_cred;
742 };
743 
744 static inline int prepare_peercred(struct unix_peercred *peercred)
745 {
746 	int err;
747 
748 	get_task_pids(peercred->peer_pid, current);
749 	err = pidfs_register_pids(peercred->peer_pid);
750 	if (unlikely(err)) {
751 		put_pids(peercred->peer_pid);
752 		return err;
753 	}
754 
755 	peercred->peer_cred = get_current_cred();
756 	return 0;
757 }
758 
759 static void drop_peercred(struct unix_peercred *peercred)
760 {
761 	const struct cred *cred = NULL;
762 
763 	might_sleep();
764 
765 	put_pids(peercred->peer_pid);
766 	swap(peercred->peer_cred, cred);
767 	put_cred(cred);
768 }
769 
770 static inline void init_peercred(struct sock *sk,
771 				 const struct unix_peercred *peercred)
772 {
773 	memcpy(sk->sk_peer_pid, peercred->peer_pid, sizeof(sk->sk_peer_pid));
774 	sk->sk_peer_cred = peercred->peer_cred;
775 }
776 
777 static void update_peercred(struct sock *sk, struct unix_peercred *peercred)
778 {
779 	const struct cred *old_cred;
780 
781 	spin_lock(&sk->sk_peer_lock);
782 	swap_pids(sk->sk_peer_pid, peercred->peer_pid);
783 	old_cred = sk->sk_peer_cred;
784 	sk->sk_peer_cred = peercred->peer_cred;
785 	spin_unlock(&sk->sk_peer_lock);
786 
787 	peercred->peer_cred = old_cred;
788 }
789 
790 static void copy_peercred(struct sock *sk, struct sock *peersk)
791 {
792 	lockdep_assert_held(&unix_sk(peersk)->lock);
793 
794 	spin_lock(&sk->sk_peer_lock);
795 	get_pids(sk->sk_peer_pid, peersk->sk_peer_pid);
796 	sk->sk_peer_cred = get_cred(peersk->sk_peer_cred);
797 	spin_unlock(&sk->sk_peer_lock);
798 }
799 
800 static bool unix_may_passcred(const struct sock *sk)
801 {
802 	return sk->sk_scm_credentials || sk->sk_scm_pidfd ||
803 		sk->sk_scm_pidfd_thread;
804 }
805 
806 static int unix_listen(struct socket *sock, int backlog)
807 {
808 	int err;
809 	struct sock *sk = sock->sk;
810 	struct unix_sock *u = unix_sk(sk);
811 	struct unix_peercred peercred = {};
812 
813 	err = -EOPNOTSUPP;
814 	if (sock->type != SOCK_STREAM && sock->type != SOCK_SEQPACKET)
815 		goto out;	/* Only stream/seqpacket sockets accept */
816 	err = -EINVAL;
817 	if (!READ_ONCE(u->addr))
818 		goto out;	/* No listens on an unbound socket */
819 	err = prepare_peercred(&peercred);
820 	if (err)
821 		goto out;
822 	unix_state_lock(sk);
823 	err = -EINVAL;
824 	if (sk->sk_state != TCP_CLOSE && sk->sk_state != TCP_LISTEN)
825 		goto out_unlock;
826 	if (backlog > sk->sk_max_ack_backlog)
827 		wake_up_interruptible_all(&u->peer_wait);
828 	sk->sk_max_ack_backlog	= backlog;
829 	WRITE_ONCE(sk->sk_state, TCP_LISTEN);
830 
831 	/* set credentials so connect can copy them */
832 	update_peercred(sk, &peercred);
833 	err = 0;
834 
835 out_unlock:
836 	unix_state_unlock(sk);
837 	drop_peercred(&peercred);
838 out:
839 	return err;
840 }
841 
842 static int unix_release(struct socket *);
843 static int unix_bind(struct socket *, struct sockaddr_unsized *, int);
844 static int unix_stream_connect(struct socket *, struct sockaddr_unsized *,
845 			       int addr_len, int flags);
846 static int unix_socketpair(struct socket *, struct socket *);
847 static int unix_accept(struct socket *, struct socket *, struct proto_accept_arg *arg);
848 static int unix_getname(struct socket *, struct sockaddr *, int);
849 static __poll_t unix_poll(struct file *, struct socket *, poll_table *);
850 static __poll_t unix_dgram_poll(struct file *, struct socket *,
851 				    poll_table *);
852 static int unix_ioctl(struct socket *, unsigned int, unsigned long);
853 #ifdef CONFIG_COMPAT
854 static int unix_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg);
855 #endif
856 static int unix_shutdown(struct socket *, int);
857 static int unix_stream_sendmsg(struct socket *, struct msghdr *, size_t);
858 static int unix_stream_recvmsg(struct socket *, struct msghdr *, size_t, int);
859 static ssize_t unix_stream_splice_read(struct socket *,  loff_t *ppos,
860 				       struct pipe_inode_info *, size_t size,
861 				       unsigned int flags);
862 static int unix_dgram_sendmsg(struct socket *, struct msghdr *, size_t);
863 static int unix_dgram_recvmsg(struct socket *, struct msghdr *, size_t, int);
864 static int unix_read_skb(struct sock *sk, skb_read_actor_t recv_actor);
865 static int unix_stream_read_skb(struct sock *sk, skb_read_actor_t recv_actor);
866 static int unix_dgram_connect(struct socket *, struct sockaddr_unsized *,
867 			      int, int);
868 static int unix_seqpacket_sendmsg(struct socket *, struct msghdr *, size_t);
869 static int unix_seqpacket_recvmsg(struct socket *, struct msghdr *, size_t,
870 				  int);
871 
872 #ifdef CONFIG_PROC_FS
873 static int unix_count_nr_fds(struct sock *sk)
874 {
875 	struct sk_buff *skb;
876 	struct unix_sock *u;
877 	int nr_fds = 0;
878 
879 	spin_lock(&sk->sk_receive_queue.lock);
880 	skb = skb_peek(&sk->sk_receive_queue);
881 	while (skb) {
882 		u = unix_sk(skb->sk);
883 		nr_fds += atomic_read(&u->scm_stat.nr_fds);
884 		skb = skb_peek_next(skb, &sk->sk_receive_queue);
885 	}
886 	spin_unlock(&sk->sk_receive_queue.lock);
887 
888 	return nr_fds;
889 }
890 
891 static void unix_show_fdinfo(struct seq_file *m, struct socket *sock)
892 {
893 	struct sock *sk = sock->sk;
894 	unsigned char s_state;
895 	struct unix_sock *u;
896 	int nr_fds = 0;
897 
898 	if (sk) {
899 		s_state = READ_ONCE(sk->sk_state);
900 		u = unix_sk(sk);
901 
902 		/* SOCK_STREAM and SOCK_SEQPACKET sockets never change their
903 		 * sk_state after switching to TCP_ESTABLISHED or TCP_LISTEN.
904 		 * SOCK_DGRAM is ordinary. So, no lock is needed.
905 		 */
906 		if (sock->type == SOCK_DGRAM || s_state == TCP_ESTABLISHED)
907 			nr_fds = atomic_read(&u->scm_stat.nr_fds);
908 		else if (s_state == TCP_LISTEN)
909 			nr_fds = unix_count_nr_fds(sk);
910 
911 		seq_printf(m, "scm_fds: %u\n", nr_fds);
912 	}
913 }
914 #else
915 #define unix_show_fdinfo NULL
916 #endif
917 
918 static bool unix_custom_sockopt(int optname)
919 {
920 	switch (optname) {
921 	case SO_INQ:
922 	case SO_RIGHTS_NOTRUNC:
923 		return true;
924 	default:
925 		return false;
926 	}
927 }
928 
929 static int unix_setsockopt(struct socket *sock, int level, int optname,
930 			   sockptr_t optval, unsigned int optlen)
931 {
932 	struct unix_sock *u = unix_sk(sock->sk);
933 	struct sock *sk = sock->sk;
934 	int val;
935 
936 	if (level != SOL_SOCKET)
937 		return -EOPNOTSUPP;
938 
939 	if (!unix_custom_sockopt(optname))
940 		return sock_setsockopt(sock, level, optname, optval, optlen);
941 
942 	if (optlen != sizeof(int))
943 		return -EINVAL;
944 
945 	if (copy_from_sockptr(&val, optval, sizeof(val)))
946 		return -EFAULT;
947 
948 	switch (optname) {
949 	case SO_INQ:
950 		if (sk->sk_type != SOCK_STREAM)
951 			return -ENOPROTOOPT;
952 
953 		if (val > 1 || val < 0)
954 			return -EINVAL;
955 
956 		WRITE_ONCE(u->recvmsg_inq, val);
957 		break;
958 
959 	case SO_RIGHTS_NOTRUNC:
960 		if (val > 1 || val < 0)
961 			return -EINVAL;
962 
963 		WRITE_ONCE(u->scm_rights_notrunc, val);
964 		break;
965 
966 	default:
967 		return -ENOPROTOOPT;
968 	}
969 
970 	return 0;
971 }
972 
973 static const struct proto_ops unix_stream_ops = {
974 	.family =	PF_UNIX,
975 	.owner =	THIS_MODULE,
976 	.release =	unix_release,
977 	.bind =		unix_bind,
978 	.connect =	unix_stream_connect,
979 	.socketpair =	unix_socketpair,
980 	.accept =	unix_accept,
981 	.getname =	unix_getname,
982 	.poll =		unix_poll,
983 	.ioctl =	unix_ioctl,
984 #ifdef CONFIG_COMPAT
985 	.compat_ioctl =	unix_compat_ioctl,
986 #endif
987 	.listen =	unix_listen,
988 	.shutdown =	unix_shutdown,
989 	.setsockopt =	unix_setsockopt,
990 	.sendmsg =	unix_stream_sendmsg,
991 	.recvmsg =	unix_stream_recvmsg,
992 	.read_skb =	unix_stream_read_skb,
993 	.mmap =		sock_no_mmap,
994 	.splice_read =	unix_stream_splice_read,
995 	.set_peek_off =	sk_set_peek_off,
996 	.show_fdinfo =	unix_show_fdinfo,
997 };
998 
999 static const struct proto_ops unix_dgram_ops = {
1000 	.family =	PF_UNIX,
1001 	.owner =	THIS_MODULE,
1002 	.release =	unix_release,
1003 	.bind =		unix_bind,
1004 	.connect =	unix_dgram_connect,
1005 	.socketpair =	unix_socketpair,
1006 	.accept =	sock_no_accept,
1007 	.getname =	unix_getname,
1008 	.poll =		unix_dgram_poll,
1009 	.ioctl =	unix_ioctl,
1010 #ifdef CONFIG_COMPAT
1011 	.compat_ioctl =	unix_compat_ioctl,
1012 #endif
1013 	.listen =	sock_no_listen,
1014 	.shutdown =	unix_shutdown,
1015 	.setsockopt =	unix_setsockopt,
1016 	.sendmsg =	unix_dgram_sendmsg,
1017 	.read_skb =	unix_read_skb,
1018 	.recvmsg =	unix_dgram_recvmsg,
1019 	.mmap =		sock_no_mmap,
1020 	.set_peek_off =	sk_set_peek_off,
1021 	.show_fdinfo =	unix_show_fdinfo,
1022 };
1023 
1024 static const struct proto_ops unix_seqpacket_ops = {
1025 	.family =	PF_UNIX,
1026 	.owner =	THIS_MODULE,
1027 	.release =	unix_release,
1028 	.bind =		unix_bind,
1029 	.connect =	unix_stream_connect,
1030 	.socketpair =	unix_socketpair,
1031 	.accept =	unix_accept,
1032 	.getname =	unix_getname,
1033 	.poll =		unix_dgram_poll,
1034 	.ioctl =	unix_ioctl,
1035 #ifdef CONFIG_COMPAT
1036 	.compat_ioctl =	unix_compat_ioctl,
1037 #endif
1038 	.listen =	unix_listen,
1039 	.shutdown =	unix_shutdown,
1040 	.setsockopt =	unix_setsockopt,
1041 	.sendmsg =	unix_seqpacket_sendmsg,
1042 	.recvmsg =	unix_seqpacket_recvmsg,
1043 	.mmap =		sock_no_mmap,
1044 	.set_peek_off =	sk_set_peek_off,
1045 	.show_fdinfo =	unix_show_fdinfo,
1046 };
1047 
1048 static void unix_close(struct sock *sk, long timeout)
1049 {
1050 	/* Nothing to do here, unix socket does not need a ->close().
1051 	 * This is merely for sockmap.
1052 	 */
1053 }
1054 
1055 static bool unix_bpf_bypass_getsockopt(int level, int optname)
1056 {
1057 	if (level == SOL_SOCKET) {
1058 		switch (optname) {
1059 		case SO_PEERPIDFD:
1060 		case SO_PEERPIDFD_THREAD:
1061 			return true;
1062 		default:
1063 			return false;
1064 		}
1065 	}
1066 
1067 	return false;
1068 }
1069 
1070 struct proto unix_dgram_proto = {
1071 	.name			= "UNIX",
1072 	.owner			= THIS_MODULE,
1073 	.obj_size		= sizeof(struct unix_sock),
1074 	.close			= unix_close,
1075 	.bpf_bypass_getsockopt	= unix_bpf_bypass_getsockopt,
1076 #ifdef CONFIG_BPF_SYSCALL
1077 	.psock_update_sk_prot	= unix_dgram_bpf_update_proto,
1078 #endif
1079 };
1080 
1081 struct proto unix_stream_proto = {
1082 	.name			= "UNIX-STREAM",
1083 	.owner			= THIS_MODULE,
1084 	.obj_size		= sizeof(struct unix_sock),
1085 	.close			= unix_close,
1086 	.bpf_bypass_getsockopt	= unix_bpf_bypass_getsockopt,
1087 #ifdef CONFIG_BPF_SYSCALL
1088 	.psock_update_sk_prot	= unix_stream_bpf_update_proto,
1089 #endif
1090 };
1091 
1092 static struct sock *unix_create1(struct net *net, struct socket *sock, int kern, int type)
1093 {
1094 	struct unix_sock *u;
1095 	struct sock *sk;
1096 	int err;
1097 
1098 	atomic_long_inc(&unix_nr_socks);
1099 	if (atomic_long_read(&unix_nr_socks) > 2 * get_max_files()) {
1100 		err = -ENFILE;
1101 		goto err;
1102 	}
1103 
1104 	if (type == SOCK_STREAM)
1105 		sk = sk_alloc(net, PF_UNIX, GFP_KERNEL, &unix_stream_proto, kern);
1106 	else /*dgram and  seqpacket */
1107 		sk = sk_alloc(net, PF_UNIX, GFP_KERNEL, &unix_dgram_proto, kern);
1108 
1109 	if (!sk) {
1110 		err = -ENOMEM;
1111 		goto err;
1112 	}
1113 
1114 	sock_init_data(sock, sk);
1115 
1116 	sk->sk_scm_rights	= 1;
1117 	sk->sk_hash		= unix_unbound_hash(sk);
1118 	sk->sk_allocation	= GFP_KERNEL_ACCOUNT;
1119 	sk->sk_write_space	= unix_write_space;
1120 	sk->sk_max_ack_backlog	= READ_ONCE(net->unx.sysctl_max_dgram_qlen);
1121 	sk->sk_destruct		= unix_sock_destructor;
1122 	lock_set_cmp_fn(&sk->sk_receive_queue.lock, unix_recvq_lock_cmp_fn, NULL);
1123 
1124 	u = unix_sk(sk);
1125 	u->listener = NULL;
1126 	u->vertex = NULL;
1127 	u->path.dentry = NULL;
1128 	u->path.mnt = NULL;
1129 	spin_lock_init(&u->lock);
1130 	lock_set_cmp_fn(&u->lock, unix_state_lock_cmp_fn, NULL);
1131 	mutex_init(&u->iolock); /* single task reading lock */
1132 	mutex_init(&u->bindlock); /* single task binding lock */
1133 	init_waitqueue_head(&u->peer_wait);
1134 	init_waitqueue_func_entry(&u->peer_wake, unix_dgram_peer_wake_relay);
1135 	memset(&u->scm_stat, 0, sizeof(struct scm_stat));
1136 	unix_insert_unbound_socket(net, sk);
1137 
1138 	sock_prot_inuse_add(net, sk->sk_prot, 1);
1139 
1140 	return sk;
1141 
1142 err:
1143 	atomic_long_dec(&unix_nr_socks);
1144 	return ERR_PTR(err);
1145 }
1146 
1147 static int unix_create(struct net *net, struct socket *sock, int protocol,
1148 		       int kern)
1149 {
1150 	struct sock *sk;
1151 
1152 	if (protocol && protocol != PF_UNIX)
1153 		return -EPROTONOSUPPORT;
1154 
1155 	set_bit(SOCK_CUSTOM_SOCKOPT, &sock->flags);
1156 
1157 	switch (sock->type) {
1158 	case SOCK_STREAM:
1159 		sock->ops = &unix_stream_ops;
1160 		break;
1161 		/*
1162 		 *	Believe it or not BSD has AF_UNIX, SOCK_RAW though
1163 		 *	nothing uses it.
1164 		 */
1165 	case SOCK_RAW:
1166 		sock->type = SOCK_DGRAM;
1167 		fallthrough;
1168 	case SOCK_DGRAM:
1169 		sock->ops = &unix_dgram_ops;
1170 		break;
1171 	case SOCK_SEQPACKET:
1172 		sock->ops = &unix_seqpacket_ops;
1173 		break;
1174 	default:
1175 		return -ESOCKTNOSUPPORT;
1176 	}
1177 
1178 	sk = unix_create1(net, sock, kern, sock->type);
1179 	if (IS_ERR(sk))
1180 		return PTR_ERR(sk);
1181 
1182 	return 0;
1183 }
1184 
1185 static int unix_release(struct socket *sock)
1186 {
1187 	struct sock *sk = sock->sk;
1188 
1189 	if (!sk)
1190 		return 0;
1191 
1192 	sk->sk_prot->close(sk, 0);
1193 	unix_release_sock(sk, 0);
1194 	sock->sk = NULL;
1195 
1196 	return 0;
1197 }
1198 
1199 static struct sock *unix_find_bsd(struct sockaddr_un *sunaddr, int addr_len,
1200 				  int type, int flags)
1201 {
1202 	struct inode *inode;
1203 	struct path path;
1204 	struct sock *sk;
1205 	int err;
1206 
1207 	unix_mkname_bsd(sunaddr, addr_len);
1208 
1209 	if (flags & SOCK_COREDUMP) {
1210 		scoped_with_init_fs() {
1211 			scoped_with_kernel_creds()
1212 				err = kern_path(sunaddr->sun_path,
1213 						LOOKUP_NO_SYMLINKS |
1214 						LOOKUP_NO_MAGICLINKS, &path);
1215 		}
1216 		if (err)
1217 			goto fail;
1218 	} else {
1219 		err = kern_path(sunaddr->sun_path, LOOKUP_FOLLOW, &path);
1220 		if (err)
1221 			goto fail;
1222 
1223 		err = path_permission(&path, MAY_WRITE);
1224 		if (err)
1225 			goto path_put;
1226 	}
1227 
1228 	err = -ECONNREFUSED;
1229 	inode = d_backing_inode(path.dentry);
1230 	if (!S_ISSOCK(inode->i_mode))
1231 		goto path_put;
1232 
1233 	sk = unix_find_socket_byinode(inode);
1234 	if (!sk)
1235 		goto path_put;
1236 
1237 	err = -EPROTOTYPE;
1238 	if (sk->sk_type != type)
1239 		goto sock_put;
1240 
1241 	err = security_unix_find(&path, sk, flags);
1242 	if (err)
1243 		goto sock_put;
1244 
1245 	touch_atime(&path);
1246 
1247 	path_put(&path);
1248 
1249 	return sk;
1250 
1251 sock_put:
1252 	sock_put(sk);
1253 path_put:
1254 	path_put(&path);
1255 fail:
1256 	return ERR_PTR(err);
1257 }
1258 
1259 static struct sock *unix_find_abstract(struct net *net,
1260 				       struct sockaddr_un *sunaddr,
1261 				       int addr_len, int type)
1262 {
1263 	unsigned int hash = unix_abstract_hash(sunaddr, addr_len, type);
1264 	struct dentry *dentry;
1265 	struct sock *sk;
1266 
1267 	sk = unix_find_socket_byname(net, sunaddr, addr_len, hash);
1268 	if (!sk)
1269 		return ERR_PTR(-ECONNREFUSED);
1270 
1271 	dentry = unix_sk(sk)->path.dentry;
1272 	if (dentry)
1273 		touch_atime(&unix_sk(sk)->path);
1274 
1275 	return sk;
1276 }
1277 
1278 static struct sock *unix_find_other(struct net *net,
1279 				    struct sockaddr_un *sunaddr,
1280 				    int addr_len, int type, int flags)
1281 {
1282 	struct sock *sk;
1283 
1284 	if (sunaddr->sun_path[0])
1285 		sk = unix_find_bsd(sunaddr, addr_len, type, flags);
1286 	else
1287 		sk = unix_find_abstract(net, sunaddr, addr_len, type);
1288 
1289 	return sk;
1290 }
1291 
1292 static int unix_autobind(struct sock *sk)
1293 {
1294 	struct unix_sock *u = unix_sk(sk);
1295 	unsigned int new_hash, old_hash;
1296 	struct net *net = sock_net(sk);
1297 	struct unix_address *addr;
1298 	u32 lastnum, ordernum;
1299 	int err;
1300 
1301 	err = mutex_lock_interruptible(&u->bindlock);
1302 	if (err)
1303 		return err;
1304 
1305 	if (u->addr)
1306 		goto out;
1307 
1308 	err = -ENOMEM;
1309 	addr = kzalloc(sizeof(*addr) +
1310 		       offsetof(struct sockaddr_un, sun_path) + 16, GFP_KERNEL);
1311 	if (!addr)
1312 		goto out;
1313 
1314 	addr->len = offsetof(struct sockaddr_un, sun_path) + 6;
1315 	addr->name->sun_family = AF_UNIX;
1316 	refcount_set(&addr->refcnt, 1);
1317 
1318 	old_hash = sk->sk_hash;
1319 	ordernum = get_random_u32();
1320 	lastnum = ordernum & 0xFFFFF;
1321 retry:
1322 	ordernum = (ordernum + 1) & 0xFFFFF;
1323 	sprintf(addr->name->sun_path + 1, "%05x", ordernum);
1324 
1325 	new_hash = unix_abstract_hash(addr->name, addr->len, sk->sk_type);
1326 	unix_table_double_lock(net, old_hash, new_hash);
1327 
1328 	if (__unix_find_socket_byname(net, addr->name, addr->len, new_hash)) {
1329 		unix_table_double_unlock(net, old_hash, new_hash);
1330 
1331 		/* __unix_find_socket_byname() may take long time if many names
1332 		 * are already in use.
1333 		 */
1334 		cond_resched();
1335 
1336 		if (ordernum == lastnum) {
1337 			/* Give up if all names seems to be in use. */
1338 			err = -ENOSPC;
1339 			unix_release_addr(addr);
1340 			goto out;
1341 		}
1342 
1343 		goto retry;
1344 	}
1345 
1346 	__unix_set_addr_hash(net, sk, addr, new_hash);
1347 	unix_table_double_unlock(net, old_hash, new_hash);
1348 	err = 0;
1349 
1350 out:	mutex_unlock(&u->bindlock);
1351 	return err;
1352 }
1353 
1354 static int unix_bind_bsd(struct sock *sk, struct sockaddr_un *sunaddr,
1355 			 int addr_len)
1356 {
1357 	umode_t mode = S_IFSOCK |
1358 	       (SOCK_INODE(sk->sk_socket)->i_mode & ~current_umask());
1359 	struct unix_sock *u = unix_sk(sk);
1360 	unsigned int new_hash, old_hash;
1361 	struct net *net = sock_net(sk);
1362 	const struct mnt_idmap *idmap;
1363 	struct unix_address *addr;
1364 	struct dentry *dentry;
1365 	struct path parent;
1366 	int err;
1367 
1368 	addr_len = unix_mkname_bsd(sunaddr, addr_len);
1369 	addr = unix_create_addr(sunaddr, addr_len);
1370 	if (!addr)
1371 		return -ENOMEM;
1372 
1373 	/*
1374 	 * Get the parent directory, calculate the hash for last
1375 	 * component.
1376 	 */
1377 	dentry = start_creating_path(AT_FDCWD, addr->name->sun_path, &parent, 0);
1378 	if (IS_ERR(dentry)) {
1379 		err = PTR_ERR(dentry);
1380 		goto out;
1381 	}
1382 
1383 	/*
1384 	 * All right, let's create it.
1385 	 */
1386 	idmap = mnt_idmap(parent.mnt);
1387 	err = security_path_mknod(&parent, dentry, mode, 0);
1388 	if (!err)
1389 		err = vfs_mknod(idmap, d_inode(parent.dentry), dentry, mode, 0, NULL);
1390 	if (err)
1391 		goto out_path;
1392 	err = mutex_lock_interruptible(&u->bindlock);
1393 	if (err)
1394 		goto out_unlink;
1395 	if (u->addr)
1396 		goto out_unlock;
1397 
1398 	old_hash = sk->sk_hash;
1399 	new_hash = unix_bsd_hash(d_backing_inode(dentry));
1400 	unix_table_double_lock(net, old_hash, new_hash);
1401 	u->path.mnt = mntget(parent.mnt);
1402 	u->path.dentry = dget(dentry);
1403 	__unix_set_addr_hash(net, sk, addr, new_hash);
1404 	unix_table_double_unlock(net, old_hash, new_hash);
1405 	unix_insert_bsd_socket(sk);
1406 	mutex_unlock(&u->bindlock);
1407 	end_creating_path(&parent, dentry);
1408 	return 0;
1409 
1410 out_unlock:
1411 	mutex_unlock(&u->bindlock);
1412 	err = -EINVAL;
1413 out_unlink:
1414 	/* failed after successful mknod?  unlink what we'd created... */
1415 	vfs_unlink(idmap, d_inode(parent.dentry), dentry, NULL);
1416 out_path:
1417 	end_creating_path(&parent, dentry);
1418 out:
1419 	unix_release_addr(addr);
1420 	return err == -EEXIST ? -EADDRINUSE : err;
1421 }
1422 
1423 static int unix_bind_abstract(struct sock *sk, struct sockaddr_un *sunaddr,
1424 			      int addr_len)
1425 {
1426 	struct unix_sock *u = unix_sk(sk);
1427 	unsigned int new_hash, old_hash;
1428 	struct net *net = sock_net(sk);
1429 	struct unix_address *addr;
1430 	int err;
1431 
1432 	addr = unix_create_addr(sunaddr, addr_len);
1433 	if (!addr)
1434 		return -ENOMEM;
1435 
1436 	err = mutex_lock_interruptible(&u->bindlock);
1437 	if (err)
1438 		goto out;
1439 
1440 	if (u->addr) {
1441 		err = -EINVAL;
1442 		goto out_mutex;
1443 	}
1444 
1445 	old_hash = sk->sk_hash;
1446 	new_hash = unix_abstract_hash(addr->name, addr->len, sk->sk_type);
1447 	unix_table_double_lock(net, old_hash, new_hash);
1448 
1449 	if (__unix_find_socket_byname(net, addr->name, addr->len, new_hash))
1450 		goto out_spin;
1451 
1452 	__unix_set_addr_hash(net, sk, addr, new_hash);
1453 	unix_table_double_unlock(net, old_hash, new_hash);
1454 	mutex_unlock(&u->bindlock);
1455 	return 0;
1456 
1457 out_spin:
1458 	unix_table_double_unlock(net, old_hash, new_hash);
1459 	err = -EADDRINUSE;
1460 out_mutex:
1461 	mutex_unlock(&u->bindlock);
1462 out:
1463 	unix_release_addr(addr);
1464 	return err;
1465 }
1466 
1467 static int unix_bind(struct socket *sock, struct sockaddr_unsized *uaddr, int addr_len)
1468 {
1469 	struct sockaddr_un *sunaddr = (struct sockaddr_un *)uaddr;
1470 	struct sock *sk = sock->sk;
1471 	int err;
1472 
1473 	if (addr_len == offsetof(struct sockaddr_un, sun_path) &&
1474 	    sunaddr->sun_family == AF_UNIX)
1475 		return unix_autobind(sk);
1476 
1477 	err = unix_validate_addr(sunaddr, addr_len);
1478 	if (err)
1479 		return err;
1480 
1481 	if (sunaddr->sun_path[0])
1482 		err = unix_bind_bsd(sk, sunaddr, addr_len);
1483 	else
1484 		err = unix_bind_abstract(sk, sunaddr, addr_len);
1485 
1486 	return err;
1487 }
1488 
1489 static void unix_state_double_lock(struct sock *sk1, struct sock *sk2)
1490 {
1491 	if (unlikely(sk1 == sk2) || !sk2) {
1492 		unix_state_lock(sk1);
1493 		return;
1494 	}
1495 
1496 	if (sk1 > sk2)
1497 		swap(sk1, sk2);
1498 
1499 	unix_state_lock(sk1);
1500 	unix_state_lock(sk2);
1501 }
1502 
1503 static void unix_state_double_unlock(struct sock *sk1, struct sock *sk2)
1504 {
1505 	if (unlikely(sk1 == sk2) || !sk2) {
1506 		unix_state_unlock(sk1);
1507 		return;
1508 	}
1509 	unix_state_unlock(sk1);
1510 	unix_state_unlock(sk2);
1511 }
1512 
1513 static int unix_dgram_connect(struct socket *sock, struct sockaddr_unsized *addr,
1514 			      int alen, int flags)
1515 {
1516 	struct sockaddr_un *sunaddr = (struct sockaddr_un *)addr;
1517 	struct sock *sk = sock->sk;
1518 	struct sock *other;
1519 	int err;
1520 
1521 	err = -EINVAL;
1522 	if (alen < offsetofend(struct sockaddr, sa_family))
1523 		goto out;
1524 
1525 	if (addr->sa_family != AF_UNSPEC) {
1526 		err = unix_validate_addr(sunaddr, alen);
1527 		if (err)
1528 			goto out;
1529 
1530 		err = BPF_CGROUP_RUN_PROG_UNIX_CONNECT_LOCK(sk, addr, &alen);
1531 		if (err)
1532 			goto out;
1533 
1534 		if (unix_may_passcred(sk) && !READ_ONCE(unix_sk(sk)->addr)) {
1535 			err = unix_autobind(sk);
1536 			if (err)
1537 				goto out;
1538 		}
1539 
1540 restart:
1541 		other = unix_find_other(sock_net(sk), sunaddr, alen, sock->type, 0);
1542 		if (IS_ERR(other)) {
1543 			err = PTR_ERR(other);
1544 			goto out;
1545 		}
1546 
1547 		unix_state_double_lock(sk, other);
1548 
1549 		/* Apparently VFS overslept socket death. Retry. */
1550 		if (sock_flag(other, SOCK_DEAD)) {
1551 			unix_state_double_unlock(sk, other);
1552 			sock_put(other);
1553 			goto restart;
1554 		}
1555 
1556 		err = -EPERM;
1557 		if (!unix_may_send(sk, other))
1558 			goto out_unlock;
1559 
1560 		err = security_unix_may_send(sk->sk_socket, other->sk_socket);
1561 		if (err)
1562 			goto out_unlock;
1563 
1564 		WRITE_ONCE(sk->sk_state, TCP_ESTABLISHED);
1565 		WRITE_ONCE(other->sk_state, TCP_ESTABLISHED);
1566 	} else {
1567 		/*
1568 		 *	1003.1g breaking connected state with AF_UNSPEC
1569 		 */
1570 		other = NULL;
1571 		unix_state_double_lock(sk, other);
1572 	}
1573 
1574 	/*
1575 	 * If it was connected, reconnect.
1576 	 */
1577 	if (unix_peer(sk)) {
1578 		struct sock *old_peer = unix_peer(sk);
1579 
1580 		unix_peer(sk) = other;
1581 		if (!other)
1582 			WRITE_ONCE(sk->sk_state, TCP_CLOSE);
1583 		unix_dgram_peer_wake_disconnect_wakeup(sk, old_peer);
1584 
1585 		unix_state_double_unlock(sk, other);
1586 
1587 		if (other != old_peer) {
1588 			unix_dgram_disconnected(sk, old_peer);
1589 
1590 			unix_state_lock(old_peer);
1591 			if (!unix_peer(old_peer))
1592 				WRITE_ONCE(old_peer->sk_state, TCP_CLOSE);
1593 			unix_state_unlock(old_peer);
1594 		}
1595 
1596 		sock_put(old_peer);
1597 	} else {
1598 		unix_peer(sk) = other;
1599 		unix_state_double_unlock(sk, other);
1600 	}
1601 
1602 	return 0;
1603 
1604 out_unlock:
1605 	unix_state_double_unlock(sk, other);
1606 	sock_put(other);
1607 out:
1608 	return err;
1609 }
1610 
1611 static long unix_wait_for_peer(struct sock *other, long timeo)
1612 {
1613 	struct unix_sock *u = unix_sk(other);
1614 	int sched;
1615 	DEFINE_WAIT(wait);
1616 
1617 	prepare_to_wait_exclusive(&u->peer_wait, &wait, TASK_INTERRUPTIBLE);
1618 
1619 	sched = !sock_flag(other, SOCK_DEAD) &&
1620 		!(other->sk_shutdown & RCV_SHUTDOWN) &&
1621 		unix_recvq_full_lockless(other);
1622 
1623 	unix_state_unlock(other);
1624 
1625 	if (sched)
1626 		timeo = schedule_timeout(timeo);
1627 
1628 	finish_wait(&u->peer_wait, &wait);
1629 	return timeo;
1630 }
1631 
1632 static int unix_stream_connect(struct socket *sock, struct sockaddr_unsized *uaddr,
1633 			       int addr_len, int flags)
1634 {
1635 	struct sockaddr_un *sunaddr = (struct sockaddr_un *)uaddr;
1636 	struct sock *sk = sock->sk, *newsk = NULL, *other = NULL;
1637 	struct unix_sock *u = unix_sk(sk), *newu, *otheru;
1638 	struct unix_peercred peercred = {};
1639 	struct net *net = sock_net(sk);
1640 	struct sk_buff *skb = NULL;
1641 	unsigned char state;
1642 	long timeo;
1643 	int err;
1644 
1645 	err = unix_validate_addr(sunaddr, addr_len);
1646 	if (err)
1647 		goto out;
1648 
1649 	err = BPF_CGROUP_RUN_PROG_UNIX_CONNECT_LOCK(sk, uaddr, &addr_len);
1650 	if (err)
1651 		goto out;
1652 
1653 	if (unix_may_passcred(sk) && !READ_ONCE(u->addr)) {
1654 		err = unix_autobind(sk);
1655 		if (err)
1656 			goto out;
1657 	}
1658 
1659 	timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
1660 
1661 	err = prepare_peercred(&peercred);
1662 	if (err)
1663 		goto out;
1664 
1665 	/* create new sock for complete connection */
1666 	newsk = unix_create1(net, NULL, 0, sock->type);
1667 	if (IS_ERR(newsk)) {
1668 		err = PTR_ERR(newsk);
1669 		goto out;
1670 	}
1671 
1672 	/* Allocate skb for sending to listening sock */
1673 	skb = sock_wmalloc(newsk, 1, 0, GFP_KERNEL);
1674 	if (!skb) {
1675 		err = -ENOMEM;
1676 		goto out_free_sk;
1677 	}
1678 
1679 restart:
1680 	/*  Find listening sock. */
1681 	other = unix_find_other(net, sunaddr, addr_len, sk->sk_type, flags);
1682 	if (IS_ERR(other)) {
1683 		err = PTR_ERR(other);
1684 		goto out_free_skb;
1685 	}
1686 
1687 	unix_state_lock(other);
1688 
1689 	/* Apparently VFS overslept socket death. Retry. */
1690 	if (sock_flag(other, SOCK_DEAD)) {
1691 		unix_state_unlock(other);
1692 		sock_put(other);
1693 		goto restart;
1694 	}
1695 
1696 	if (other->sk_state != TCP_LISTEN ||
1697 	    other->sk_shutdown & RCV_SHUTDOWN) {
1698 		err = -ECONNREFUSED;
1699 		goto out_unlock;
1700 	}
1701 
1702 	if (unix_recvq_full_lockless(other)) {
1703 		if (!timeo) {
1704 			err = -EAGAIN;
1705 			goto out_unlock;
1706 		}
1707 
1708 		timeo = unix_wait_for_peer(other, timeo);
1709 		sock_put(other);
1710 
1711 		err = sock_intr_errno(timeo);
1712 		if (signal_pending(current))
1713 			goto out_free_skb;
1714 
1715 		goto restart;
1716 	}
1717 
1718 	/* self connect and simultaneous connect are eliminated
1719 	 * by rejecting TCP_LISTEN socket to avoid deadlock.
1720 	 */
1721 	state = READ_ONCE(sk->sk_state);
1722 	if (unlikely(state != TCP_CLOSE)) {
1723 		err = state == TCP_ESTABLISHED ? -EISCONN : -EINVAL;
1724 		goto out_unlock;
1725 	}
1726 
1727 	unix_state_lock(sk);
1728 
1729 	if (unlikely(sk->sk_state != TCP_CLOSE)) {
1730 		err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EINVAL;
1731 		unix_state_unlock(sk);
1732 		goto out_unlock;
1733 	}
1734 
1735 	err = security_unix_stream_connect(sk, other, newsk);
1736 	if (err) {
1737 		unix_state_unlock(sk);
1738 		goto out_unlock;
1739 	}
1740 
1741 	/* The way is open! Fastly set all the necessary fields... */
1742 
1743 	sock_hold(sk);
1744 	unix_peer(newsk) = sk;
1745 	newsk->sk_state = TCP_ESTABLISHED;
1746 	newsk->sk_type = sk->sk_type;
1747 	newsk->sk_scm_recv_flags = other->sk_scm_recv_flags;
1748 	init_peercred(newsk, &peercred);
1749 
1750 	newu = unix_sk(newsk);
1751 	otheru = unix_sk(other);
1752 	newu->listener = other;
1753 	newu->recvmsg_inq = READ_ONCE(otheru->recvmsg_inq);
1754 	newu->scm_rights_notrunc = READ_ONCE(otheru->scm_rights_notrunc);
1755 	RCU_INIT_POINTER(newsk->sk_wq, &newu->peer_wq);
1756 
1757 	/* copy address information from listening to new sock
1758 	 *
1759 	 * The contents of *(otheru->addr) and otheru->path
1760 	 * are seen fully set up here, since we have found
1761 	 * otheru in hash under its lock.  Insertion into the
1762 	 * hash chain we'd found it in had been done in an
1763 	 * earlier critical area protected by the chain's lock,
1764 	 * the same one where we'd set *(otheru->addr) contents,
1765 	 * as well as otheru->path and otheru->addr itself.
1766 	 *
1767 	 * Using smp_store_release() here to set newu->addr
1768 	 * is enough to make those stores, as well as stores
1769 	 * to newu->path visible to anyone who gets newu->addr
1770 	 * by smp_load_acquire().  IOW, the same warranties
1771 	 * as for unix_sock instances bound in unix_bind() or
1772 	 * in unix_autobind().
1773 	 */
1774 	if (otheru->path.dentry) {
1775 		path_get(&otheru->path);
1776 		newu->path = otheru->path;
1777 	}
1778 	refcount_inc(&otheru->addr->refcnt);
1779 	smp_store_release(&newu->addr, otheru->addr);
1780 
1781 	/* Set credentials */
1782 	copy_peercred(sk, other);
1783 
1784 	WRITE_ONCE(sk->sk_state, TCP_ESTABLISHED);
1785 	sock_hold(newsk);
1786 
1787 	smp_mb__after_atomic();	/* sock_hold() does an atomic_inc() */
1788 	unix_peer(sk)	= newsk;
1789 
1790 	unix_state_unlock(sk);
1791 
1792 	/* take ten and send info to listening sock */
1793 	spin_lock(&other->sk_receive_queue.lock);
1794 	__skb_queue_tail(&other->sk_receive_queue, skb);
1795 	spin_unlock(&other->sk_receive_queue.lock);
1796 	unix_state_unlock(other);
1797 	READ_ONCE(other->sk_data_ready)(other);
1798 	sock_put(other);
1799 	return 0;
1800 
1801 out_unlock:
1802 	unix_state_unlock(other);
1803 	sock_put(other);
1804 out_free_skb:
1805 	consume_skb(skb);
1806 out_free_sk:
1807 	unix_release_sock(newsk, 0);
1808 out:
1809 	drop_peercred(&peercred);
1810 	return err;
1811 }
1812 
1813 static int unix_socketpair(struct socket *socka, struct socket *sockb)
1814 {
1815 	struct unix_peercred ska_peercred = {}, skb_peercred = {};
1816 	struct sock *ska = socka->sk, *skb = sockb->sk;
1817 	int err;
1818 
1819 	err = prepare_peercred(&ska_peercred);
1820 	if (err)
1821 		return err;
1822 
1823 	err = prepare_peercred(&skb_peercred);
1824 	if (err) {
1825 		drop_peercred(&ska_peercred);
1826 		return err;
1827 	}
1828 
1829 	/* Join our sockets back to back */
1830 	sock_hold(ska);
1831 	sock_hold(skb);
1832 	unix_peer(ska) = skb;
1833 	unix_peer(skb) = ska;
1834 	init_peercred(ska, &ska_peercred);
1835 	init_peercred(skb, &skb_peercred);
1836 
1837 	ska->sk_state = TCP_ESTABLISHED;
1838 	skb->sk_state = TCP_ESTABLISHED;
1839 
1840 	return 0;
1841 }
1842 
1843 static int unix_accept(struct socket *sock, struct socket *newsock,
1844 		       struct proto_accept_arg *arg)
1845 {
1846 	struct sock *sk = sock->sk;
1847 	struct sk_buff *skb;
1848 	struct sock *tsk;
1849 
1850 	arg->err = -EOPNOTSUPP;
1851 	if (sock->type != SOCK_STREAM && sock->type != SOCK_SEQPACKET)
1852 		goto out;
1853 
1854 	arg->err = -EINVAL;
1855 	if (READ_ONCE(sk->sk_state) != TCP_LISTEN)
1856 		goto out;
1857 
1858 	/* If socket state is TCP_LISTEN it cannot change (for now...),
1859 	 * so that no locks are necessary.
1860 	 */
1861 
1862 	skb = skb_recv_datagram(sk, (arg->flags & O_NONBLOCK) ? MSG_DONTWAIT : 0,
1863 				&arg->err);
1864 	if (!skb) {
1865 		/* This means receive shutdown. */
1866 		if (arg->err == 0)
1867 			arg->err = -EINVAL;
1868 		goto out;
1869 	}
1870 
1871 	tsk = skb->sk;
1872 	skb_free_datagram(sk, skb);
1873 	wake_up_interruptible(&unix_sk(sk)->peer_wait);
1874 
1875 	set_bit(SOCK_CUSTOM_SOCKOPT, &newsock->flags);
1876 
1877 	/* attach accepted sock to socket */
1878 	unix_state_lock(tsk);
1879 	unix_update_edges(unix_sk(tsk));
1880 	sock_graft(tsk, newsock);
1881 	unix_state_unlock(tsk);
1882 	return 0;
1883 
1884 out:
1885 	return arg->err;
1886 }
1887 
1888 
1889 static int unix_getname(struct socket *sock, struct sockaddr *uaddr, int peer)
1890 {
1891 	struct sock *sk = sock->sk;
1892 	struct unix_address *addr;
1893 	DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr, uaddr);
1894 	int err = 0;
1895 
1896 	if (peer) {
1897 		sk = unix_peer_get(sk);
1898 
1899 		err = -ENOTCONN;
1900 		if (!sk)
1901 			goto out;
1902 		err = 0;
1903 	} else {
1904 		sock_hold(sk);
1905 	}
1906 
1907 	addr = smp_load_acquire(&unix_sk(sk)->addr);
1908 	if (!addr) {
1909 		sunaddr->sun_family = AF_UNIX;
1910 		sunaddr->sun_path[0] = 0;
1911 		err = offsetof(struct sockaddr_un, sun_path);
1912 	} else {
1913 		err = addr->len;
1914 		memcpy(sunaddr, addr->name, addr->len);
1915 
1916 		if (peer)
1917 			BPF_CGROUP_RUN_SA_PROG(sk, uaddr, &err,
1918 					       CGROUP_UNIX_GETPEERNAME);
1919 		else
1920 			BPF_CGROUP_RUN_SA_PROG(sk, uaddr, &err,
1921 					       CGROUP_UNIX_GETSOCKNAME);
1922 	}
1923 	sock_put(sk);
1924 out:
1925 	return err;
1926 }
1927 
1928 /* The "user->unix_inflight" variable is protected by the garbage
1929  * collection lock, and we just read it locklessly here. If you go
1930  * over the limit, there might be a tiny race in actually noticing
1931  * it across threads. Tough.
1932  */
1933 static inline bool too_many_unix_fds(struct task_struct *p)
1934 {
1935 	struct user_struct *user = current_user();
1936 
1937 	if (unlikely(READ_ONCE(user->unix_inflight) > task_rlimit(p, RLIMIT_NOFILE)))
1938 		return !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN);
1939 	return false;
1940 }
1941 
1942 static int unix_attach_fds(struct scm_cookie *scm, struct sk_buff *skb)
1943 {
1944 	if (too_many_unix_fds(current))
1945 		return -ETOOMANYREFS;
1946 
1947 	UNIXCB(skb).fp = scm->fp;
1948 	scm->fp = NULL;
1949 
1950 	if (unix_prepare_fpl(UNIXCB(skb).fp))
1951 		return -ENOMEM;
1952 
1953 	return 0;
1954 }
1955 
1956 static void unix_detach_fds(struct scm_cookie *scm, struct sk_buff *skb)
1957 {
1958 	scm->fp = UNIXCB(skb).fp;
1959 	UNIXCB(skb).fp = NULL;
1960 
1961 	unix_destroy_fpl(scm->fp);
1962 }
1963 
1964 static void unix_peek_fds(struct scm_cookie *scm, struct sk_buff *skb)
1965 {
1966 	scm->fp = scm_fp_dup(UNIXCB(skb).fp);
1967 
1968 	unix_peek_fpl(scm->fp);
1969 }
1970 
1971 static void unix_destruct_scm(struct sk_buff *skb)
1972 {
1973 	struct scm_cookie scm = {};
1974 
1975 	swap_pids(scm.pid, UNIXCB(skb).pid);
1976 
1977 	if (UNIXCB(skb).fp)
1978 		unix_detach_fds(&scm, skb);
1979 
1980 	scm_destroy(&scm);
1981 }
1982 
1983 static void unix_wfree(struct sk_buff *skb)
1984 {
1985 	unix_destruct_scm(skb);
1986 	sock_wfree(skb);
1987 }
1988 
1989 static int unix_scm_to_skb(struct scm_cookie *scm, struct sk_buff *skb, bool send_fds)
1990 {
1991 	int err = 0;
1992 
1993 	get_pids(UNIXCB(skb).pid, scm->pid);
1994 	UNIXCB(skb).uid = scm->creds.uid;
1995 	UNIXCB(skb).gid = scm->creds.gid;
1996 	UNIXCB(skb).fp = NULL;
1997 	unix_get_secdata(scm, skb);
1998 	if (scm->fp && send_fds)
1999 		err = unix_attach_fds(scm, skb);
2000 
2001 	skb->destructor = unix_wfree;
2002 	return err;
2003 }
2004 
2005 static void unix_skb_to_scm(struct sk_buff *skb, struct scm_cookie *scm)
2006 {
2007 	get_pids(scm->pid, UNIXCB(skb).pid);
2008 	scm_set_cred(scm, UNIXCB(skb).pid[PIDTYPE_TGID], UNIXCB(skb).uid, UNIXCB(skb).gid);
2009 	unix_set_secdata(scm, skb);
2010 }
2011 
2012 /**
2013  * unix_maybe_add_creds() - Adds current task uid/gid and struct pid to skb if needed.
2014  * @skb: skb to attach creds to.
2015  * @sk: Sender sock.
2016  * @other: Receiver sock.
2017  *
2018  * Some apps rely on write() giving SCM_CREDENTIALS
2019  * We include credentials if source or destination socket
2020  * asserted SOCK_PASSCRED.
2021  *
2022  * Context: May sleep.
2023  * Return: On success zero, on error a negative error code is returned.
2024  */
2025 static int unix_maybe_add_creds(struct sk_buff *skb, const struct sock *sk,
2026 				const struct sock *other)
2027 {
2028 	if (UNIXCB(skb).pid[PIDTYPE_TGID])
2029 		return 0;
2030 
2031 	if (unix_may_passcred(sk) || unix_may_passcred(other) ||
2032 	    !other->sk_socket) {
2033 		int err;
2034 
2035 		get_task_pids(UNIXCB(skb).pid, current);
2036 		err = pidfs_register_pids(UNIXCB(skb).pid);
2037 		if (unlikely(err)) {
2038 			put_pids(UNIXCB(skb).pid);
2039 			return err;
2040 		}
2041 
2042 		current_uid_gid(&UNIXCB(skb).uid, &UNIXCB(skb).gid);
2043 	}
2044 
2045 	return 0;
2046 }
2047 
2048 static bool unix_skb_scm_eq(const struct sock *sk, struct sk_buff *skb,
2049 			    struct scm_cookie *scm)
2050 {
2051 	/* Only a thread pidfd receiver can tell threads of one process apart. */
2052 	if (sk->sk_scm_pidfd_thread &&
2053 	    UNIXCB(skb).pid[PIDTYPE_PID] != scm->pid[PIDTYPE_PID])
2054 		return false;
2055 
2056 	return UNIXCB(skb).pid[PIDTYPE_TGID] == scm->pid[PIDTYPE_TGID] &&
2057 	       uid_eq(UNIXCB(skb).uid, scm->creds.uid) &&
2058 	       gid_eq(UNIXCB(skb).gid, scm->creds.gid) &&
2059 	       unix_secdata_eq(scm, skb);
2060 }
2061 
2062 static void scm_stat_add(struct sock *sk, struct sk_buff *skb)
2063 {
2064 	struct scm_fp_list *fp = UNIXCB(skb).fp;
2065 	struct unix_sock *u = unix_sk(sk);
2066 
2067 	if (unlikely(fp && fp->count)) {
2068 		atomic_add(fp->count, &u->scm_stat.nr_fds);
2069 		unix_add_edges(fp, u);
2070 	}
2071 }
2072 
2073 static void scm_stat_del(struct sock *sk, struct sk_buff *skb)
2074 {
2075 	struct scm_fp_list *fp = UNIXCB(skb).fp;
2076 	struct unix_sock *u = unix_sk(sk);
2077 
2078 	if (unlikely(fp && fp->count)) {
2079 		atomic_sub(fp->count, &u->scm_stat.nr_fds);
2080 		unix_del_edges(fp);
2081 	}
2082 }
2083 
2084 static void unix_orphan_scm(struct sock *sk, struct sk_buff *skb)
2085 {
2086 	scm_stat_del(sk, skb);
2087 	unix_destruct_scm(skb);
2088 	skb->destructor = sock_wfree;
2089 }
2090 
2091 /*
2092  *	Send AF_UNIX data.
2093  */
2094 
2095 static int unix_dgram_sendmsg(struct socket *sock, struct msghdr *msg,
2096 			      size_t len)
2097 {
2098 	struct sock *sk = sock->sk, *other = NULL;
2099 	struct unix_sock *u = unix_sk(sk);
2100 	struct scm_cookie scm;
2101 	struct sk_buff *skb;
2102 	int data_len = 0;
2103 	int sk_locked;
2104 	long timeo;
2105 	int err;
2106 
2107 	err = scm_send(sock, msg, &scm, false);
2108 	if (err < 0)
2109 		return err;
2110 
2111 	if (msg->msg_flags & MSG_OOB) {
2112 		err = -EOPNOTSUPP;
2113 		goto out;
2114 	}
2115 
2116 	if (msg->msg_namelen) {
2117 		err = unix_validate_addr(msg->msg_name, msg->msg_namelen);
2118 		if (err)
2119 			goto out;
2120 
2121 		err = BPF_CGROUP_RUN_PROG_UNIX_SENDMSG_LOCK(sk,
2122 							    msg->msg_name,
2123 							    &msg->msg_namelen,
2124 							    NULL);
2125 		if (err)
2126 			goto out;
2127 	}
2128 
2129 	if (unix_may_passcred(sk) && !READ_ONCE(u->addr)) {
2130 		err = unix_autobind(sk);
2131 		if (err)
2132 			goto out;
2133 	}
2134 
2135 	if (len > READ_ONCE(sk->sk_sndbuf) - 32) {
2136 		err = -EMSGSIZE;
2137 		goto out;
2138 	}
2139 
2140 	if (len > SKB_MAX_ALLOC) {
2141 		data_len = min_t(size_t,
2142 				 len - SKB_MAX_ALLOC,
2143 				 MAX_SKB_FRAGS * PAGE_SIZE);
2144 		data_len = PAGE_ALIGN(data_len);
2145 
2146 		BUILD_BUG_ON(SKB_MAX_ALLOC < PAGE_SIZE);
2147 	}
2148 
2149 	skb = sock_alloc_send_pskb(sk, len - data_len, data_len,
2150 				   msg->msg_flags & MSG_DONTWAIT, &err,
2151 				   PAGE_ALLOC_COSTLY_ORDER);
2152 	if (!skb)
2153 		goto out;
2154 
2155 	err = unix_scm_to_skb(&scm, skb, true);
2156 	if (err < 0)
2157 		goto out_free;
2158 
2159 	skb_put(skb, len - data_len);
2160 	skb->data_len = data_len;
2161 	skb->len = len;
2162 	err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, len);
2163 	if (err)
2164 		goto out_free;
2165 
2166 	timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
2167 
2168 	if (msg->msg_namelen) {
2169 lookup:
2170 		other = unix_find_other(sock_net(sk), msg->msg_name,
2171 					msg->msg_namelen, sk->sk_type, 0);
2172 		if (IS_ERR(other)) {
2173 			err = PTR_ERR(other);
2174 			goto out_free;
2175 		}
2176 	} else {
2177 		other = unix_peer_get(sk);
2178 		if (!other) {
2179 			err = -ENOTCONN;
2180 			goto out_free;
2181 		}
2182 	}
2183 
2184 	if (sk_filter(other, skb) < 0) {
2185 		/* Toss the packet but do not return any error to the sender */
2186 		err = len;
2187 		goto out_sock_put;
2188 	}
2189 
2190 	err = unix_maybe_add_creds(skb, sk, other);
2191 	if (err)
2192 		goto out_sock_put;
2193 
2194 restart:
2195 	sk_locked = 0;
2196 	unix_state_lock(other);
2197 restart_locked:
2198 
2199 	if (!unix_may_send(sk, other)) {
2200 		err = -EPERM;
2201 		goto out_unlock;
2202 	}
2203 
2204 	if (unlikely(sock_flag(other, SOCK_DEAD))) {
2205 		/* Check with 1003.1g - what should datagram error */
2206 
2207 		unix_state_unlock(other);
2208 
2209 		if (sk->sk_type == SOCK_SEQPACKET) {
2210 			/* We are here only when racing with unix_release_sock()
2211 			 * is clearing @other. Never change state to TCP_CLOSE
2212 			 * unlike SOCK_DGRAM wants.
2213 			 */
2214 			err = -EPIPE;
2215 			goto out_sock_put;
2216 		}
2217 
2218 		if (!sk_locked)
2219 			unix_state_lock(sk);
2220 
2221 		if (unix_peer(sk) == other) {
2222 			unix_peer(sk) = NULL;
2223 			unix_dgram_peer_wake_disconnect_wakeup(sk, other);
2224 
2225 			WRITE_ONCE(sk->sk_state, TCP_CLOSE);
2226 			unix_state_unlock(sk);
2227 
2228 			unix_dgram_disconnected(sk, other);
2229 			sock_put(other);
2230 			err = -ECONNREFUSED;
2231 			goto out_sock_put;
2232 		}
2233 
2234 		unix_state_unlock(sk);
2235 
2236 		if (!msg->msg_namelen) {
2237 			err = -ECONNRESET;
2238 			goto out_sock_put;
2239 		}
2240 
2241 		sock_put(other);
2242 		goto lookup;
2243 	}
2244 
2245 	if (other->sk_shutdown & RCV_SHUTDOWN) {
2246 		err = -EPIPE;
2247 		goto out_unlock;
2248 	}
2249 
2250 	if (UNIXCB(skb).fp && !other->sk_scm_rights) {
2251 		err = -EPERM;
2252 		goto out_unlock;
2253 	}
2254 
2255 	if (sk->sk_type != SOCK_SEQPACKET) {
2256 		err = security_unix_may_send(sk->sk_socket, other->sk_socket);
2257 		if (err)
2258 			goto out_unlock;
2259 	}
2260 
2261 	/* other == sk && unix_peer(other) != sk if
2262 	 * - unix_peer(sk) == NULL, destination address bound to sk
2263 	 * - unix_peer(sk) == sk by time of get but disconnected before lock
2264 	 */
2265 	if (other != sk &&
2266 	    unlikely(unix_peer(other) != sk &&
2267 	    unix_recvq_full_lockless(other))) {
2268 		if (timeo) {
2269 			timeo = unix_wait_for_peer(other, timeo);
2270 
2271 			err = sock_intr_errno(timeo);
2272 			if (signal_pending(current))
2273 				goto out_sock_put;
2274 
2275 			goto restart;
2276 		}
2277 
2278 		if (!sk_locked) {
2279 			unix_state_unlock(other);
2280 			unix_state_double_lock(sk, other);
2281 		}
2282 
2283 		if (unix_peer(sk) != other ||
2284 		    unix_dgram_peer_wake_me(sk, other)) {
2285 			err = -EAGAIN;
2286 			sk_locked = 1;
2287 			goto out_unlock;
2288 		}
2289 
2290 		if (!sk_locked) {
2291 			sk_locked = 1;
2292 			goto restart_locked;
2293 		}
2294 	}
2295 
2296 	if (unlikely(sk_locked))
2297 		unix_state_unlock(sk);
2298 
2299 	if (sock_flag(other, SOCK_RCVTSTAMP))
2300 		__net_timestamp(skb);
2301 
2302 	scm_stat_add(other, skb);
2303 	skb_queue_tail(&other->sk_receive_queue, skb);
2304 	unix_state_unlock(other);
2305 	READ_ONCE(other->sk_data_ready)(other);
2306 	sock_put(other);
2307 	scm_destroy(&scm);
2308 	return len;
2309 
2310 out_unlock:
2311 	if (sk_locked)
2312 		unix_state_unlock(sk);
2313 	unix_state_unlock(other);
2314 out_sock_put:
2315 	sock_put(other);
2316 out_free:
2317 	consume_skb(skb);
2318 out:
2319 	scm_destroy(&scm);
2320 	return err;
2321 }
2322 
2323 /* We use paged skbs for stream sockets, and limit occupancy to 32768
2324  * bytes, and a minimum of a full page.
2325  */
2326 #define UNIX_SKB_FRAGS_SZ (PAGE_SIZE << get_order(32768))
2327 
2328 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
2329 static int queue_oob(struct sock *sk, struct msghdr *msg, struct sock *other,
2330 		     struct scm_cookie *scm, bool fds_sent)
2331 {
2332 	struct unix_sock *ousk = unix_sk(other);
2333 	struct sk_buff *skb;
2334 	int err;
2335 
2336 	skb = sock_alloc_send_skb(sk, 1, msg->msg_flags & MSG_DONTWAIT, &err);
2337 
2338 	if (!skb)
2339 		return err;
2340 
2341 	err = unix_scm_to_skb(scm, skb, !fds_sent);
2342 	if (err < 0)
2343 		goto out;
2344 
2345 	err = unix_maybe_add_creds(skb, sk, other);
2346 	if (err)
2347 		goto out;
2348 
2349 	skb_put(skb, 1);
2350 	err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, 1);
2351 
2352 	if (err)
2353 		goto out;
2354 
2355 	unix_state_lock(other);
2356 
2357 	if (sock_flag(other, SOCK_DEAD) ||
2358 	    (other->sk_shutdown & RCV_SHUTDOWN)) {
2359 		err = -EPIPE;
2360 		goto out_unlock;
2361 	}
2362 
2363 	if (UNIXCB(skb).fp && !other->sk_scm_rights) {
2364 		err = -EPERM;
2365 		goto out_unlock;
2366 	}
2367 
2368 	scm_stat_add(other, skb);
2369 
2370 	spin_lock(&other->sk_receive_queue.lock);
2371 	WRITE_ONCE(ousk->oob_skb, skb);
2372 	WRITE_ONCE(ousk->inq_len, ousk->inq_len + 1);
2373 	__skb_queue_tail(&other->sk_receive_queue, skb);
2374 	spin_unlock(&other->sk_receive_queue.lock);
2375 
2376 	sk_send_sigurg(other);
2377 	unix_state_unlock(other);
2378 	READ_ONCE(other->sk_data_ready)(other);
2379 
2380 	return 0;
2381 out_unlock:
2382 	unix_state_unlock(other);
2383 out:
2384 	consume_skb(skb);
2385 	return err;
2386 }
2387 #endif
2388 
2389 static int unix_stream_sendmsg(struct socket *sock, struct msghdr *msg,
2390 			       size_t len)
2391 {
2392 	struct sock *sk = sock->sk;
2393 	struct sk_buff *skb = NULL;
2394 	struct sock *other = NULL;
2395 	struct unix_sock *otheru;
2396 	struct scm_cookie scm;
2397 	bool fds_sent = false;
2398 	int err, sent = 0;
2399 
2400 	err = scm_send(sock, msg, &scm, false);
2401 	if (err < 0)
2402 		return err;
2403 
2404 	if (msg->msg_flags & MSG_OOB) {
2405 		err = -EOPNOTSUPP;
2406 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
2407 		if (len)
2408 			len--;
2409 		else
2410 #endif
2411 			goto out_err;
2412 	}
2413 
2414 	if (msg->msg_namelen) {
2415 		err = READ_ONCE(sk->sk_state) == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
2416 		goto out_err;
2417 	}
2418 
2419 	other = unix_peer(sk);
2420 	if (!other) {
2421 		err = -ENOTCONN;
2422 		goto out_err;
2423 	}
2424 
2425 	otheru = unix_sk(other);
2426 
2427 	if (READ_ONCE(sk->sk_shutdown) & SEND_SHUTDOWN)
2428 		goto out_pipe;
2429 
2430 	while (sent < len) {
2431 		int size = len - sent;
2432 		int data_len;
2433 
2434 		if (unlikely(msg->msg_flags & MSG_SPLICE_PAGES)) {
2435 			skb = sock_alloc_send_pskb(sk, 0, 0,
2436 						   msg->msg_flags & MSG_DONTWAIT,
2437 						   &err, 0);
2438 		} else {
2439 			/* Keep two messages in the pipe so it schedules better */
2440 			size = min_t(int, size, (READ_ONCE(sk->sk_sndbuf) >> 1) - 64);
2441 
2442 			/* allow fallback to order-0 allocations */
2443 			size = min_t(int, size, SKB_MAX_HEAD(0) + UNIX_SKB_FRAGS_SZ);
2444 
2445 			data_len = max_t(int, 0, size - SKB_MAX_HEAD(0));
2446 
2447 			data_len = min_t(size_t, size, PAGE_ALIGN(data_len));
2448 
2449 			skb = sock_alloc_send_pskb(sk, size - data_len, data_len,
2450 						   msg->msg_flags & MSG_DONTWAIT, &err,
2451 						   get_order(UNIX_SKB_FRAGS_SZ));
2452 		}
2453 		if (!skb)
2454 			goto out_err;
2455 
2456 		/* Only send the fds in the first buffer */
2457 		err = unix_scm_to_skb(&scm, skb, !fds_sent);
2458 		if (err < 0)
2459 			goto out_free;
2460 
2461 		fds_sent = true;
2462 
2463 		err = unix_maybe_add_creds(skb, sk, other);
2464 		if (err)
2465 			goto out_free;
2466 
2467 		if (unlikely(msg->msg_flags & MSG_SPLICE_PAGES)) {
2468 			skb->ip_summed = CHECKSUM_UNNECESSARY;
2469 			err = skb_splice_from_iter(skb, &msg->msg_iter, size);
2470 			if (err < 0)
2471 				goto out_free;
2472 
2473 			size = err;
2474 			refcount_add(size, &sk->sk_wmem_alloc);
2475 		} else {
2476 			skb_put(skb, size - data_len);
2477 			skb->data_len = data_len;
2478 			skb->len = size;
2479 			err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, size);
2480 			if (err)
2481 				goto out_free;
2482 		}
2483 
2484 		unix_state_lock(other);
2485 
2486 		if (sock_flag(other, SOCK_DEAD) ||
2487 		    (other->sk_shutdown & RCV_SHUTDOWN))
2488 			goto out_pipe_unlock;
2489 
2490 		if (UNIXCB(skb).fp && !other->sk_scm_rights) {
2491 			unix_state_unlock(other);
2492 			err = -EPERM;
2493 			goto out_free;
2494 		}
2495 
2496 		scm_stat_add(other, skb);
2497 
2498 		spin_lock(&other->sk_receive_queue.lock);
2499 		WRITE_ONCE(otheru->inq_len, otheru->inq_len + skb->len);
2500 		__skb_queue_tail(&other->sk_receive_queue, skb);
2501 		spin_unlock(&other->sk_receive_queue.lock);
2502 
2503 		unix_state_unlock(other);
2504 		READ_ONCE(other->sk_data_ready)(other);
2505 		sent += size;
2506 	}
2507 
2508 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
2509 	if (msg->msg_flags & MSG_OOB) {
2510 		err = queue_oob(sk, msg, other, &scm, fds_sent);
2511 		if (err)
2512 			goto out_err;
2513 		sent++;
2514 	}
2515 #endif
2516 
2517 	scm_destroy(&scm);
2518 
2519 	return sent;
2520 
2521 out_pipe_unlock:
2522 	unix_state_unlock(other);
2523 out_pipe:
2524 	if (!sent && !(msg->msg_flags & MSG_NOSIGNAL))
2525 		send_sig(SIGPIPE, current, 0);
2526 	err = -EPIPE;
2527 out_free:
2528 	consume_skb(skb);
2529 out_err:
2530 	scm_destroy(&scm);
2531 	return sent ? : err;
2532 }
2533 
2534 static int unix_seqpacket_sendmsg(struct socket *sock, struct msghdr *msg,
2535 				  size_t len)
2536 {
2537 	int err;
2538 	struct sock *sk = sock->sk;
2539 
2540 	err = sock_error(sk);
2541 	if (err)
2542 		return err;
2543 
2544 	if (READ_ONCE(sk->sk_state) != TCP_ESTABLISHED)
2545 		return -ENOTCONN;
2546 
2547 	if (msg->msg_namelen)
2548 		msg->msg_namelen = 0;
2549 
2550 	return unix_dgram_sendmsg(sock, msg, len);
2551 }
2552 
2553 static int unix_seqpacket_recvmsg(struct socket *sock, struct msghdr *msg,
2554 				  size_t size, int flags)
2555 {
2556 	struct sock *sk = sock->sk;
2557 
2558 	if (READ_ONCE(sk->sk_state) != TCP_ESTABLISHED)
2559 		return -ENOTCONN;
2560 
2561 	return unix_dgram_recvmsg(sock, msg, size, flags);
2562 }
2563 
2564 static void unix_copy_addr(struct msghdr *msg, struct sock *sk)
2565 {
2566 	struct unix_address *addr = smp_load_acquire(&unix_sk(sk)->addr);
2567 
2568 	if (addr) {
2569 		msg->msg_namelen = addr->len;
2570 		memcpy(msg->msg_name, addr->name, addr->len);
2571 	}
2572 }
2573 
2574 int __unix_dgram_recvmsg(struct sock *sk, struct msghdr *msg, size_t size,
2575 			 int flags)
2576 {
2577 	struct scm_cookie scm;
2578 	struct socket *sock = sk->sk_socket;
2579 	struct unix_sock *u = unix_sk(sk);
2580 	struct sk_buff *skb, *last;
2581 	long timeo;
2582 	int skip;
2583 	int err;
2584 
2585 	err = -EOPNOTSUPP;
2586 	if (flags&MSG_OOB)
2587 		goto out;
2588 
2589 	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2590 
2591 	do {
2592 		mutex_lock(&u->iolock);
2593 
2594 		skip = sk_peek_offset(sk, flags);
2595 		skb = __skb_try_recv_datagram(sk, &sk->sk_receive_queue, flags,
2596 					      &skip, &err, &last);
2597 		if (skb) {
2598 			if (!(flags & MSG_PEEK))
2599 				scm_stat_del(sk, skb);
2600 			break;
2601 		}
2602 
2603 		mutex_unlock(&u->iolock);
2604 
2605 		if (err != -EAGAIN)
2606 			break;
2607 	} while (timeo &&
2608 		 !__skb_wait_for_more_packets(sk, &sk->sk_receive_queue,
2609 					      &err, &timeo, last));
2610 
2611 	if (!skb) { /* implies iolock unlocked */
2612 		/* Signal EOF on disconnected non-blocking SEQPACKET socket. */
2613 		if (sk->sk_type == SOCK_SEQPACKET && err == -EAGAIN &&
2614 		    (READ_ONCE(sk->sk_shutdown) & RCV_SHUTDOWN))
2615 			err = 0;
2616 		goto out;
2617 	}
2618 
2619 	if (wq_has_sleeper(&u->peer_wait))
2620 		wake_up_interruptible_sync_poll(&u->peer_wait,
2621 						EPOLLOUT | EPOLLWRNORM |
2622 						EPOLLWRBAND);
2623 
2624 	if (msg->msg_name) {
2625 		unix_copy_addr(msg, skb->sk);
2626 
2627 		BPF_CGROUP_RUN_PROG_UNIX_RECVMSG_LOCK(sk,
2628 						      msg->msg_name,
2629 						      &msg->msg_namelen);
2630 	}
2631 
2632 	if (size > skb->len - skip)
2633 		size = skb->len - skip;
2634 	else if (size < skb->len - skip)
2635 		msg->msg_flags |= MSG_TRUNC;
2636 
2637 	err = skb_copy_datagram_msg(skb, skip, msg, size);
2638 	if (err)
2639 		goto out_free;
2640 
2641 	if (sock_flag(sk, SOCK_RCVTSTAMP))
2642 		__sock_recv_timestamp(msg, sk, skb);
2643 
2644 	memset(&scm, 0, sizeof(scm));
2645 
2646 	unix_skb_to_scm(skb, &scm);
2647 
2648 	if (!(flags & MSG_PEEK)) {
2649 		if (UNIXCB(skb).fp)
2650 			unix_detach_fds(&scm, skb);
2651 
2652 		sk_peek_offset_bwd(sk, skb->len);
2653 	} else {
2654 		/* It is questionable: on PEEK we could:
2655 		   - do not return fds - good, but too simple 8)
2656 		   - return fds, and do not return them on read (old strategy,
2657 		     apparently wrong)
2658 		   - clone fds (I chose it for now, it is the most universal
2659 		     solution)
2660 
2661 		   POSIX 1003.1g does not actually define this clearly
2662 		   at all. POSIX 1003.1g doesn't define a lot of things
2663 		   clearly however!
2664 
2665 		*/
2666 
2667 		sk_peek_offset_fwd(sk, size);
2668 
2669 		if (UNIXCB(skb).fp)
2670 			unix_peek_fds(&scm, skb);
2671 	}
2672 	err = (flags & MSG_TRUNC) ? skb->len - skip : size;
2673 
2674 	scm_recv_unix(sock, msg, &scm, flags);
2675 
2676 out_free:
2677 	skb_free_datagram(sk, skb);
2678 	mutex_unlock(&u->iolock);
2679 out:
2680 	return err;
2681 }
2682 
2683 static int unix_dgram_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
2684 			      int flags)
2685 {
2686 	struct sock *sk = sock->sk;
2687 
2688 #ifdef CONFIG_BPF_SYSCALL
2689 	const struct proto *prot = READ_ONCE(sk->sk_prot);
2690 
2691 	if (prot != &unix_dgram_proto)
2692 		return prot->recvmsg(sk, msg, size, flags);
2693 #endif
2694 	return __unix_dgram_recvmsg(sk, msg, size, flags);
2695 }
2696 
2697 static int unix_read_skb(struct sock *sk, skb_read_actor_t recv_actor)
2698 {
2699 	struct unix_sock *u = unix_sk(sk);
2700 	struct sk_buff *skb;
2701 	int err;
2702 
2703 	mutex_lock(&u->iolock);
2704 
2705 	skb = skb_recv_datagram(sk, MSG_DONTWAIT, &err);
2706 	if (!skb) {
2707 		mutex_unlock(&u->iolock);
2708 		return err;
2709 	}
2710 
2711 	unix_orphan_scm(sk, skb);
2712 
2713 	mutex_unlock(&u->iolock);
2714 
2715 	return recv_actor(sk, skb);
2716 }
2717 
2718 /*
2719  *	Sleep until more data has arrived. But check for races..
2720  */
2721 static long unix_stream_data_wait(struct sock *sk, long timeo,
2722 				  struct sk_buff *last, bool freezable)
2723 {
2724 	unsigned int state = TASK_INTERRUPTIBLE | freezable * TASK_FREEZABLE;
2725 	struct sk_buff *tail;
2726 	DEFINE_WAIT(wait);
2727 
2728 	unix_state_lock(sk);
2729 
2730 	for (;;) {
2731 		prepare_to_wait(sk_sleep(sk), &wait, state);
2732 
2733 		tail = skb_peek_tail(&sk->sk_receive_queue);
2734 		if (tail != last ||
2735 		    sk->sk_err ||
2736 		    (sk->sk_shutdown & RCV_SHUTDOWN) ||
2737 		    signal_pending(current) ||
2738 		    !timeo)
2739 			break;
2740 
2741 		sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
2742 		unix_state_unlock(sk);
2743 		timeo = schedule_timeout(timeo);
2744 		unix_state_lock(sk);
2745 
2746 		if (sock_flag(sk, SOCK_DEAD))
2747 			break;
2748 
2749 		sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
2750 	}
2751 
2752 	finish_wait(sk_sleep(sk), &wait);
2753 	unix_state_unlock(sk);
2754 	return timeo;
2755 }
2756 
2757 struct unix_stream_read_state {
2758 	int (*recv_actor)(struct sk_buff *, int, int,
2759 			  struct unix_stream_read_state *);
2760 	struct socket *socket;
2761 	struct msghdr *msg;
2762 	struct pipe_inode_info *pipe;
2763 	size_t size;
2764 	int flags;
2765 	unsigned int splice_flags;
2766 };
2767 
2768 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
2769 static int unix_stream_recv_urg(struct unix_stream_read_state *state)
2770 {
2771 	struct sk_buff *oob_skb, *read_skb = NULL;
2772 	struct socket *sock = state->socket;
2773 	struct sock *sk = sock->sk;
2774 	struct unix_sock *u = unix_sk(sk);
2775 	int chunk = 1;
2776 
2777 	mutex_lock(&u->iolock);
2778 	unix_state_lock(sk);
2779 	spin_lock(&sk->sk_receive_queue.lock);
2780 
2781 	if (sock_flag(sk, SOCK_URGINLINE) || !u->oob_skb) {
2782 		spin_unlock(&sk->sk_receive_queue.lock);
2783 		unix_state_unlock(sk);
2784 		mutex_unlock(&u->iolock);
2785 		return -EINVAL;
2786 	}
2787 
2788 	oob_skb = u->oob_skb;
2789 
2790 	if (!(state->flags & MSG_PEEK)) {
2791 		WRITE_ONCE(u->oob_skb, NULL);
2792 		WRITE_ONCE(u->inq_len, u->inq_len - 1);
2793 
2794 		if (oob_skb->prev != (struct sk_buff *)&sk->sk_receive_queue &&
2795 		    !unix_skb_len(oob_skb->prev)) {
2796 			read_skb = oob_skb->prev;
2797 			__skb_unlink(read_skb, &sk->sk_receive_queue);
2798 		}
2799 	}
2800 
2801 	spin_unlock(&sk->sk_receive_queue.lock);
2802 	unix_state_unlock(sk);
2803 
2804 	chunk = state->recv_actor(oob_skb, 0, chunk, state);
2805 
2806 	if (!(state->flags & MSG_PEEK))
2807 		UNIXCB(oob_skb).consumed += 1;
2808 
2809 	mutex_unlock(&u->iolock);
2810 
2811 	consume_skb(read_skb);
2812 
2813 	if (chunk < 0)
2814 		return -EFAULT;
2815 
2816 	state->msg->msg_flags |= MSG_OOB;
2817 	return 1;
2818 }
2819 
2820 static struct sk_buff *manage_oob(struct sk_buff *skb, struct sk_buff **last,
2821 				  struct sock *sk, int flags, int copied)
2822 {
2823 	struct sk_buff *read_skb = NULL, *unread_skb = NULL;
2824 	struct unix_sock *u = unix_sk(sk);
2825 
2826 	if (likely(unix_skb_len(skb) && skb != READ_ONCE(u->oob_skb)))
2827 		return skb;
2828 
2829 	spin_lock(&sk->sk_receive_queue.lock);
2830 
2831 	if (!unix_skb_len(skb)) {
2832 		if (copied && (!u->oob_skb || skb == u->oob_skb)) {
2833 			skb = NULL;
2834 		} else if (flags & MSG_PEEK) {
2835 			*last = skb;
2836 			skb = skb_peek_next(skb, &sk->sk_receive_queue);
2837 		} else {
2838 			read_skb = skb;
2839 			skb = skb_peek_next(skb, &sk->sk_receive_queue);
2840 			__skb_unlink(read_skb, &sk->sk_receive_queue);
2841 			*last = skb;
2842 		}
2843 
2844 		if (!skb)
2845 			goto unlock;
2846 	}
2847 
2848 	if (skb != u->oob_skb)
2849 		goto unlock;
2850 
2851 	if (copied) {
2852 		skb = NULL;
2853 	} else if (!(flags & MSG_PEEK)) {
2854 		WRITE_ONCE(u->oob_skb, NULL);
2855 
2856 		if (!sock_flag(sk, SOCK_URGINLINE)) {
2857 			__skb_unlink(skb, &sk->sk_receive_queue);
2858 			unread_skb = skb;
2859 			skb = skb_peek(&sk->sk_receive_queue);
2860 			*last = skb;
2861 		}
2862 	} else if (!sock_flag(sk, SOCK_URGINLINE)) {
2863 		*last = skb;
2864 		skb = skb_peek_next(skb, &sk->sk_receive_queue);
2865 	}
2866 
2867 unlock:
2868 	spin_unlock(&sk->sk_receive_queue.lock);
2869 
2870 	consume_skb(read_skb);
2871 	kfree_skb_reason(unread_skb, SKB_DROP_REASON_UNIX_SKIP_OOB);
2872 
2873 	return skb;
2874 }
2875 #endif
2876 
2877 static int unix_stream_read_skb(struct sock *sk, skb_read_actor_t recv_actor)
2878 {
2879 	struct sk_buff_head *queue = &sk->sk_receive_queue;
2880 	struct unix_sock *u = unix_sk(sk);
2881 	struct sk_buff *skb;
2882 	int err;
2883 
2884 	if (unlikely(READ_ONCE(sk->sk_state) != TCP_ESTABLISHED))
2885 		return -ENOTCONN;
2886 
2887 	err = sock_error(sk);
2888 	if (err)
2889 		return err;
2890 
2891 	mutex_lock(&u->iolock);
2892 	spin_lock(&queue->lock);
2893 
2894 	skb = __skb_dequeue(queue);
2895 	if (!skb) {
2896 		spin_unlock(&queue->lock);
2897 		mutex_unlock(&u->iolock);
2898 		return -EAGAIN;
2899 	}
2900 
2901 	WRITE_ONCE(u->inq_len, u->inq_len - unix_skb_len(skb));
2902 
2903 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
2904 	if (skb == u->oob_skb) {
2905 		WRITE_ONCE(u->oob_skb, NULL);
2906 		spin_unlock(&queue->lock);
2907 		mutex_unlock(&u->iolock);
2908 
2909 		kfree_skb_reason(skb, SKB_DROP_REASON_UNIX_SKIP_OOB);
2910 		return -EAGAIN;
2911 	}
2912 #endif
2913 
2914 	spin_unlock(&queue->lock);
2915 
2916 	unix_orphan_scm(sk, skb);
2917 
2918 	mutex_unlock(&u->iolock);
2919 
2920 	return recv_actor(sk, skb);
2921 }
2922 
2923 static int unix_stream_read_generic(struct unix_stream_read_state *state,
2924 				    bool freezable)
2925 {
2926 	int noblock = state->flags & MSG_DONTWAIT;
2927 	struct socket *sock = state->socket;
2928 	struct msghdr *msg = state->msg;
2929 	struct sock *sk = sock->sk;
2930 	size_t size = state->size;
2931 	int flags = state->flags;
2932 	bool check_creds = false;
2933 	struct scm_cookie scm;
2934 	struct unix_sock *u;
2935 	int copied = 0;
2936 	int err = 0;
2937 	long timeo;
2938 	int target;
2939 	int skip;
2940 
2941 	if (unlikely(READ_ONCE(sk->sk_state) != TCP_ESTABLISHED)) {
2942 		err = -EINVAL;
2943 		goto out;
2944 	}
2945 
2946 	if (unlikely(flags & MSG_OOB)) {
2947 		err = -EOPNOTSUPP;
2948 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
2949 		err = unix_stream_recv_urg(state);
2950 #endif
2951 		goto out;
2952 	}
2953 
2954 	target = sock_rcvlowat(sk, flags & MSG_WAITALL, size);
2955 	timeo = sock_rcvtimeo(sk, noblock);
2956 
2957 	memset(&scm, 0, sizeof(scm));
2958 
2959 	u = unix_sk(sk);
2960 
2961 redo:
2962 	/* Lock the socket to prevent queue disordering
2963 	 * while sleeps in memcpy_tomsg
2964 	 */
2965 	mutex_lock(&u->iolock);
2966 
2967 	skip = max(sk_peek_offset(sk, flags), 0);
2968 
2969 	do {
2970 		struct sk_buff *skb, *last;
2971 		int chunk;
2972 
2973 		unix_state_lock(sk);
2974 		if (sock_flag(sk, SOCK_DEAD)) {
2975 			err = -ECONNRESET;
2976 			goto unlock;
2977 		}
2978 		last = skb = skb_peek(&sk->sk_receive_queue);
2979 
2980 again:
2981 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
2982 		if (skb) {
2983 			skb = manage_oob(skb, &last, sk, flags, copied);
2984 			if (!skb && (copied || !state->size)) {
2985 				unix_state_unlock(sk);
2986 				break;
2987 			}
2988 		}
2989 #endif
2990 		if (skb == NULL) {
2991 			if (copied >= target)
2992 				goto unlock;
2993 
2994 			/*
2995 			 *	POSIX 1003.1g mandates this order.
2996 			 */
2997 
2998 			err = sock_error(sk);
2999 			if (err)
3000 				goto unlock;
3001 			if (sk->sk_shutdown & RCV_SHUTDOWN)
3002 				goto unlock;
3003 
3004 			unix_state_unlock(sk);
3005 			if (!timeo) {
3006 				err = -EAGAIN;
3007 				break;
3008 			}
3009 
3010 			mutex_unlock(&u->iolock);
3011 
3012 			timeo = unix_stream_data_wait(sk, timeo, last, freezable);
3013 
3014 			if (signal_pending(current)) {
3015 				err = sock_intr_errno(timeo);
3016 				scm_destroy(&scm);
3017 				goto out;
3018 			}
3019 
3020 			goto redo;
3021 unlock:
3022 			unix_state_unlock(sk);
3023 			break;
3024 		}
3025 
3026 		while (skip >= unix_skb_len(skb)) {
3027 			skip -= unix_skb_len(skb);
3028 			last = skb;
3029 			skb = skb_peek_next(skb, &sk->sk_receive_queue);
3030 			if (!skb)
3031 				goto again;
3032 		}
3033 
3034 		unix_state_unlock(sk);
3035 
3036 		if (check_creds) {
3037 			/* Never glue messages from different writers */
3038 			if (!unix_skb_scm_eq(sk, skb, &scm))
3039 				break;
3040 		} else if (unix_may_passcred(sk)) {
3041 			/* Copy credentials */
3042 			unix_skb_to_scm(skb, &scm);
3043 			check_creds = true;
3044 		}
3045 
3046 		/* Copy address just once */
3047 		if (msg && msg->msg_name) {
3048 			DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr, msg->msg_name);
3049 
3050 			unix_copy_addr(msg, skb->sk);
3051 			BPF_CGROUP_RUN_PROG_UNIX_RECVMSG_LOCK(sk, msg->msg_name,
3052 							      &msg->msg_namelen);
3053 
3054 			sunaddr = NULL;
3055 		}
3056 
3057 		chunk = min_t(unsigned int, unix_skb_len(skb) - skip, size);
3058 		chunk = state->recv_actor(skb, skip, chunk, state);
3059 		if (chunk < 0) {
3060 			if (copied == 0)
3061 				copied = -EFAULT;
3062 			break;
3063 		}
3064 		copied += chunk;
3065 		size -= chunk;
3066 
3067 		/* Mark read part of skb as used */
3068 		if (!(flags & MSG_PEEK)) {
3069 			UNIXCB(skb).consumed += chunk;
3070 
3071 			sk_peek_offset_bwd(sk, chunk);
3072 
3073 			if (UNIXCB(skb).fp) {
3074 				scm_stat_del(sk, skb);
3075 				unix_detach_fds(&scm, skb);
3076 			}
3077 
3078 			spin_lock(&sk->sk_receive_queue.lock);
3079 			WRITE_ONCE(u->inq_len, u->inq_len - chunk);
3080 			if (unix_skb_len(skb)) {
3081 				spin_unlock(&sk->sk_receive_queue.lock);
3082 				break;
3083 			}
3084 			__skb_unlink(skb, &sk->sk_receive_queue);
3085 			spin_unlock(&sk->sk_receive_queue.lock);
3086 
3087 			consume_skb(skb);
3088 
3089 			if (scm.fp)
3090 				break;
3091 		} else {
3092 			/* It is questionable, see note in unix_dgram_recvmsg.
3093 			 */
3094 			if (UNIXCB(skb).fp)
3095 				unix_peek_fds(&scm, skb);
3096 
3097 			sk_peek_offset_fwd(sk, chunk);
3098 
3099 			if (UNIXCB(skb).fp)
3100 				break;
3101 
3102 			skip = 0;
3103 			last = skb;
3104 			unix_state_lock(sk);
3105 			skb = skb_peek_next(skb, &sk->sk_receive_queue);
3106 			if (skb)
3107 				goto again;
3108 			unix_state_unlock(sk);
3109 			break;
3110 		}
3111 	} while (size);
3112 
3113 	mutex_unlock(&u->iolock);
3114 	if (msg) {
3115 		bool do_cmsg = READ_ONCE(u->recvmsg_inq);
3116 
3117 		scm_recv_unix(sock, msg, &scm, flags);
3118 
3119 		if ((do_cmsg | msg->msg_get_inq) && (copied ?: err) >= 0) {
3120 			msg->msg_inq = READ_ONCE(u->inq_len);
3121 			if (do_cmsg)
3122 				put_cmsg(msg, SOL_SOCKET, SCM_INQ,
3123 					 sizeof(msg->msg_inq), &msg->msg_inq);
3124 		}
3125 	} else {
3126 		scm_destroy(&scm);
3127 	}
3128 out:
3129 	return copied ? : err;
3130 }
3131 
3132 static int unix_stream_read_actor(struct sk_buff *skb,
3133 				  int skip, int chunk,
3134 				  struct unix_stream_read_state *state)
3135 {
3136 	int ret;
3137 
3138 	ret = skb_copy_datagram_msg(skb, UNIXCB(skb).consumed + skip,
3139 				    state->msg, chunk);
3140 	return ret ?: chunk;
3141 }
3142 
3143 int __unix_stream_recvmsg(struct sock *sk, struct msghdr *msg,
3144 			  size_t size, int flags)
3145 {
3146 	struct unix_stream_read_state state = {
3147 		.recv_actor = unix_stream_read_actor,
3148 		.socket = sk->sk_socket,
3149 		.msg = msg,
3150 		.size = size,
3151 		.flags = flags
3152 	};
3153 
3154 	return unix_stream_read_generic(&state, true);
3155 }
3156 
3157 static int unix_stream_recvmsg(struct socket *sock, struct msghdr *msg,
3158 			       size_t size, int flags)
3159 {
3160 	struct unix_stream_read_state state = {
3161 		.recv_actor = unix_stream_read_actor,
3162 		.socket = sock,
3163 		.msg = msg,
3164 		.size = size,
3165 		.flags = flags
3166 	};
3167 
3168 #ifdef CONFIG_BPF_SYSCALL
3169 	struct sock *sk = sock->sk;
3170 	const struct proto *prot = READ_ONCE(sk->sk_prot);
3171 
3172 	if (prot != &unix_stream_proto)
3173 		return prot->recvmsg(sk, msg, size, flags);
3174 #endif
3175 	return unix_stream_read_generic(&state, true);
3176 }
3177 
3178 static int unix_stream_splice_actor(struct sk_buff *skb,
3179 				    int skip, int chunk,
3180 				    struct unix_stream_read_state *state)
3181 {
3182 	return skb_splice_bits(skb, state->socket->sk,
3183 			       UNIXCB(skb).consumed + skip,
3184 			       state->pipe, chunk, state->splice_flags);
3185 }
3186 
3187 static ssize_t unix_stream_splice_read(struct socket *sock,  loff_t *ppos,
3188 				       struct pipe_inode_info *pipe,
3189 				       size_t size, unsigned int flags)
3190 {
3191 	struct unix_stream_read_state state = {
3192 		.recv_actor = unix_stream_splice_actor,
3193 		.socket = sock,
3194 		.pipe = pipe,
3195 		.size = size,
3196 		.splice_flags = flags,
3197 	};
3198 
3199 	if (unlikely(*ppos))
3200 		return -ESPIPE;
3201 
3202 	if (sock->file->f_flags & O_NONBLOCK ||
3203 	    flags & SPLICE_F_NONBLOCK)
3204 		state.flags = MSG_DONTWAIT;
3205 
3206 	return unix_stream_read_generic(&state, false);
3207 }
3208 
3209 static int unix_shutdown(struct socket *sock, int mode)
3210 {
3211 	struct sock *sk = sock->sk;
3212 	struct sock *other;
3213 
3214 	if (mode < SHUT_RD || mode > SHUT_RDWR)
3215 		return -EINVAL;
3216 	/* This maps:
3217 	 * SHUT_RD   (0) -> RCV_SHUTDOWN  (1)
3218 	 * SHUT_WR   (1) -> SEND_SHUTDOWN (2)
3219 	 * SHUT_RDWR (2) -> SHUTDOWN_MASK (3)
3220 	 */
3221 	++mode;
3222 
3223 	unix_state_lock(sk);
3224 	WRITE_ONCE(sk->sk_shutdown, sk->sk_shutdown | mode);
3225 	other = unix_peer(sk);
3226 	if (other)
3227 		sock_hold(other);
3228 	unix_state_unlock(sk);
3229 	sk->sk_state_change(sk);
3230 
3231 	if (other &&
3232 		(sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET)) {
3233 
3234 		int peer_mode = 0;
3235 		const struct proto *prot = READ_ONCE(other->sk_prot);
3236 
3237 		if (prot->unhash)
3238 			prot->unhash(other);
3239 		if (mode&RCV_SHUTDOWN)
3240 			peer_mode |= SEND_SHUTDOWN;
3241 		if (mode&SEND_SHUTDOWN)
3242 			peer_mode |= RCV_SHUTDOWN;
3243 		unix_state_lock(other);
3244 		WRITE_ONCE(other->sk_shutdown, other->sk_shutdown | peer_mode);
3245 		unix_state_unlock(other);
3246 		other->sk_state_change(other);
3247 		if (peer_mode == SHUTDOWN_MASK)
3248 			sk_wake_async(other, SOCK_WAKE_WAITD, POLL_HUP);
3249 		else if (peer_mode & RCV_SHUTDOWN)
3250 			sk_wake_async(other, SOCK_WAKE_WAITD, POLL_IN);
3251 	}
3252 	if (other)
3253 		sock_put(other);
3254 
3255 	return 0;
3256 }
3257 
3258 long unix_inq_len(struct sock *sk)
3259 {
3260 	struct sk_buff *skb;
3261 	long amount = 0;
3262 
3263 	if (READ_ONCE(sk->sk_state) == TCP_LISTEN)
3264 		return -EINVAL;
3265 
3266 	if (sk->sk_type == SOCK_STREAM)
3267 		return READ_ONCE(unix_sk(sk)->inq_len);
3268 
3269 	spin_lock(&sk->sk_receive_queue.lock);
3270 	if (sk->sk_type == SOCK_SEQPACKET) {
3271 		skb_queue_walk(&sk->sk_receive_queue, skb)
3272 			amount += unix_skb_len(skb);
3273 	} else {
3274 		skb = skb_peek(&sk->sk_receive_queue);
3275 		if (skb)
3276 			amount = skb->len;
3277 	}
3278 	spin_unlock(&sk->sk_receive_queue.lock);
3279 
3280 	return amount;
3281 }
3282 EXPORT_SYMBOL_GPL(unix_inq_len);
3283 
3284 long unix_outq_len(struct sock *sk)
3285 {
3286 	return sk_wmem_alloc_get(sk);
3287 }
3288 EXPORT_SYMBOL_GPL(unix_outq_len);
3289 
3290 static int unix_open_file(struct sock *sk)
3291 {
3292 	if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
3293 		return -EPERM;
3294 
3295 	if (!smp_load_acquire(&unix_sk(sk)->addr))
3296 		return -ENOENT;
3297 
3298 	if (!unix_sk(sk)->path.dentry)
3299 		return -ENOENT;
3300 
3301 	return FD_ADD(O_CLOEXEC, dentry_open(&unix_sk(sk)->path, O_PATH, current_cred()));
3302 }
3303 
3304 static int unix_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
3305 {
3306 	struct sock *sk = sock->sk;
3307 	long amount = 0;
3308 	int err;
3309 
3310 	switch (cmd) {
3311 	case SIOCOUTQ:
3312 		amount = unix_outq_len(sk);
3313 		err = put_user(amount, (int __user *)arg);
3314 		break;
3315 	case SIOCINQ:
3316 		amount = unix_inq_len(sk);
3317 		if (amount < 0)
3318 			err = amount;
3319 		else
3320 			err = put_user(amount, (int __user *)arg);
3321 		break;
3322 	case SIOCUNIXFILE:
3323 		err = unix_open_file(sk);
3324 		break;
3325 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
3326 	case SIOCATMARK:
3327 		{
3328 			struct unix_sock *u = unix_sk(sk);
3329 			struct sk_buff *skb;
3330 			int answ = 0;
3331 
3332 			if (sk->sk_type != SOCK_STREAM)
3333 				return -EOPNOTSUPP;
3334 
3335 			mutex_lock(&u->iolock);
3336 
3337 			skb = skb_peek(&sk->sk_receive_queue);
3338 			if (skb) {
3339 				struct sk_buff *oob_skb = READ_ONCE(u->oob_skb);
3340 				struct sk_buff *next_skb;
3341 
3342 				next_skb = skb_peek_next(skb, &sk->sk_receive_queue);
3343 
3344 				if (skb == oob_skb ||
3345 				    (!unix_skb_len(skb) &&
3346 				     (!oob_skb || next_skb == oob_skb)))
3347 					answ = 1;
3348 			}
3349 
3350 			mutex_unlock(&u->iolock);
3351 
3352 			err = put_user(answ, (int __user *)arg);
3353 		}
3354 		break;
3355 #endif
3356 	default:
3357 		err = -ENOIOCTLCMD;
3358 		break;
3359 	}
3360 	return err;
3361 }
3362 
3363 #ifdef CONFIG_COMPAT
3364 static int unix_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
3365 {
3366 	return unix_ioctl(sock, cmd, (unsigned long)compat_ptr(arg));
3367 }
3368 #endif
3369 
3370 static __poll_t unix_poll(struct file *file, struct socket *sock, poll_table *wait)
3371 {
3372 	struct sock *sk = sock->sk;
3373 	unsigned char state;
3374 	__poll_t mask;
3375 	u8 shutdown;
3376 
3377 	sock_poll_wait(file, sock, wait);
3378 	mask = 0;
3379 	shutdown = READ_ONCE(sk->sk_shutdown);
3380 	state = READ_ONCE(sk->sk_state);
3381 
3382 	/* exceptional events? */
3383 	if (READ_ONCE(sk->sk_err))
3384 		mask |= EPOLLERR;
3385 	if (shutdown == SHUTDOWN_MASK)
3386 		mask |= EPOLLHUP;
3387 	if (shutdown & RCV_SHUTDOWN)
3388 		mask |= EPOLLRDHUP | EPOLLIN | EPOLLRDNORM;
3389 
3390 	/* readable? */
3391 	if (!skb_queue_empty_lockless(&sk->sk_receive_queue))
3392 		mask |= EPOLLIN | EPOLLRDNORM;
3393 	if (sk_is_readable(sk))
3394 		mask |= EPOLLIN | EPOLLRDNORM;
3395 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
3396 	if (READ_ONCE(unix_sk(sk)->oob_skb))
3397 		mask |= EPOLLPRI;
3398 #endif
3399 
3400 	/* Connection-based need to check for termination and startup */
3401 	if ((sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET) &&
3402 	    state == TCP_CLOSE)
3403 		mask |= EPOLLHUP;
3404 
3405 	/*
3406 	 * we set writable also when the other side has shut down the
3407 	 * connection. This prevents stuck sockets.
3408 	 */
3409 	if (unix_writable(sk, state))
3410 		mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
3411 
3412 	return mask;
3413 }
3414 
3415 static __poll_t unix_dgram_poll(struct file *file, struct socket *sock,
3416 				    poll_table *wait)
3417 {
3418 	struct sock *sk = sock->sk, *other;
3419 	unsigned int writable;
3420 	unsigned char state;
3421 	__poll_t mask;
3422 	u8 shutdown;
3423 
3424 	sock_poll_wait(file, sock, wait);
3425 	mask = 0;
3426 	shutdown = READ_ONCE(sk->sk_shutdown);
3427 	state = READ_ONCE(sk->sk_state);
3428 
3429 	/* exceptional events? */
3430 	if (READ_ONCE(sk->sk_err) ||
3431 	    !skb_queue_empty_lockless(&sk->sk_error_queue))
3432 		mask |= EPOLLERR |
3433 			(sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? EPOLLPRI : 0);
3434 
3435 	if (shutdown & RCV_SHUTDOWN)
3436 		mask |= EPOLLRDHUP | EPOLLIN | EPOLLRDNORM;
3437 	if (shutdown == SHUTDOWN_MASK)
3438 		mask |= EPOLLHUP;
3439 
3440 	/* readable? */
3441 	if (!skb_queue_empty_lockless(&sk->sk_receive_queue))
3442 		mask |= EPOLLIN | EPOLLRDNORM;
3443 	if (sk_is_readable(sk))
3444 		mask |= EPOLLIN | EPOLLRDNORM;
3445 
3446 	/* Connection-based need to check for termination and startup */
3447 	if (sk->sk_type == SOCK_SEQPACKET && state == TCP_CLOSE)
3448 		mask |= EPOLLHUP;
3449 
3450 	/* No write status requested, avoid expensive OUT tests. */
3451 	if (!(poll_requested_events(wait) & (EPOLLWRBAND|EPOLLWRNORM|EPOLLOUT)))
3452 		return mask;
3453 
3454 	writable = unix_writable(sk, state);
3455 	if (writable) {
3456 		unix_state_lock(sk);
3457 
3458 		other = unix_peer(sk);
3459 		if (other && unix_peer(other) != sk &&
3460 		    unix_recvq_full_lockless(other) &&
3461 		    unix_dgram_peer_wake_me(sk, other))
3462 			writable = 0;
3463 
3464 		unix_state_unlock(sk);
3465 	}
3466 
3467 	if (writable)
3468 		mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
3469 	else
3470 		sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
3471 
3472 	return mask;
3473 }
3474 
3475 #ifdef CONFIG_PROC_FS
3476 
3477 #define BUCKET_SPACE (BITS_PER_LONG - (UNIX_HASH_BITS + 1) - 1)
3478 
3479 #define get_bucket(x) ((x) >> BUCKET_SPACE)
3480 #define get_offset(x) ((x) & ((1UL << BUCKET_SPACE) - 1))
3481 #define set_bucket_offset(b, o) ((b) << BUCKET_SPACE | (o))
3482 
3483 static struct sock *unix_from_bucket(struct seq_file *seq, loff_t *pos)
3484 {
3485 	unsigned long offset = get_offset(*pos);
3486 	unsigned long bucket = get_bucket(*pos);
3487 	unsigned long count = 0;
3488 	struct sock *sk;
3489 
3490 	for (sk = sk_head(&seq_file_net(seq)->unx.table.buckets[bucket]);
3491 	     sk; sk = sk_next(sk)) {
3492 		if (++count == offset)
3493 			break;
3494 	}
3495 
3496 	return sk;
3497 }
3498 
3499 static struct sock *unix_get_first(struct seq_file *seq, loff_t *pos)
3500 {
3501 	unsigned long bucket = get_bucket(*pos);
3502 	struct net *net = seq_file_net(seq);
3503 	struct sock *sk;
3504 
3505 	while (bucket < UNIX_HASH_SIZE) {
3506 		spin_lock(&net->unx.table.locks[bucket]);
3507 
3508 		sk = unix_from_bucket(seq, pos);
3509 		if (sk)
3510 			return sk;
3511 
3512 		spin_unlock(&net->unx.table.locks[bucket]);
3513 
3514 		*pos = set_bucket_offset(++bucket, 1);
3515 	}
3516 
3517 	return NULL;
3518 }
3519 
3520 static struct sock *unix_get_next(struct seq_file *seq, struct sock *sk,
3521 				  loff_t *pos)
3522 {
3523 	unsigned long bucket = get_bucket(*pos);
3524 
3525 	sk = sk_next(sk);
3526 	if (sk)
3527 		return sk;
3528 
3529 
3530 	spin_unlock(&seq_file_net(seq)->unx.table.locks[bucket]);
3531 
3532 	*pos = set_bucket_offset(++bucket, 1);
3533 
3534 	return unix_get_first(seq, pos);
3535 }
3536 
3537 static void *unix_seq_start(struct seq_file *seq, loff_t *pos)
3538 {
3539 	if (!*pos)
3540 		return SEQ_START_TOKEN;
3541 
3542 	return unix_get_first(seq, pos);
3543 }
3544 
3545 static void *unix_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3546 {
3547 	++*pos;
3548 
3549 	if (v == SEQ_START_TOKEN)
3550 		return unix_get_first(seq, pos);
3551 
3552 	return unix_get_next(seq, v, pos);
3553 }
3554 
3555 static void unix_seq_stop(struct seq_file *seq, void *v)
3556 {
3557 	struct sock *sk = v;
3558 
3559 	if (sk)
3560 		spin_unlock(&seq_file_net(seq)->unx.table.locks[sk->sk_hash]);
3561 }
3562 
3563 static int unix_seq_show(struct seq_file *seq, void *v)
3564 {
3565 
3566 	if (v == SEQ_START_TOKEN)
3567 		seq_puts(seq, "Num       RefCount Protocol Flags    Type St "
3568 			 "Inode Path\n");
3569 	else {
3570 		struct sock *s = v;
3571 		struct unix_sock *u = unix_sk(s);
3572 		unix_state_lock(s);
3573 
3574 		seq_printf(seq, "%08u: %08X %08X %08X %04X %02X %5llu", 0,
3575 			refcount_read(&s->sk_refcnt),
3576 			0,
3577 			s->sk_state == TCP_LISTEN ? __SO_ACCEPTCON : 0,
3578 			s->sk_type,
3579 			s->sk_socket ?
3580 			(s->sk_state == TCP_ESTABLISHED ? SS_CONNECTED : SS_UNCONNECTED) :
3581 			(s->sk_state == TCP_ESTABLISHED ? SS_CONNECTING : SS_DISCONNECTING),
3582 			sock_i_ino(s));
3583 
3584 		if (u->addr) {	// under a hash table lock here
3585 			int i, len;
3586 			seq_putc(seq, ' ');
3587 
3588 			i = 0;
3589 			len = u->addr->len -
3590 				offsetof(struct sockaddr_un, sun_path);
3591 			if (u->addr->name->sun_path[0]) {
3592 				len--;
3593 			} else {
3594 				seq_putc(seq, '@');
3595 				i++;
3596 			}
3597 			for ( ; i < len; i++)
3598 				seq_putc(seq, u->addr->name->sun_path[i] ?:
3599 					 '@');
3600 		}
3601 		unix_state_unlock(s);
3602 		seq_putc(seq, '\n');
3603 	}
3604 
3605 	return 0;
3606 }
3607 
3608 static const struct seq_operations unix_seq_ops = {
3609 	.start  = unix_seq_start,
3610 	.next   = unix_seq_next,
3611 	.stop   = unix_seq_stop,
3612 	.show   = unix_seq_show,
3613 };
3614 
3615 #ifdef CONFIG_BPF_SYSCALL
3616 struct bpf_unix_iter_state {
3617 	struct seq_net_private p;
3618 	unsigned int cur_sk;
3619 	unsigned int end_sk;
3620 	unsigned int max_sk;
3621 	struct sock **batch;
3622 	bool st_bucket_done;
3623 };
3624 
3625 struct bpf_iter__unix {
3626 	__bpf_md_ptr(struct bpf_iter_meta *, meta);
3627 	__bpf_md_ptr(struct unix_sock *, unix_sk);
3628 	uid_t uid __aligned(8);
3629 };
3630 
3631 static int unix_prog_seq_show(struct bpf_prog *prog, struct bpf_iter_meta *meta,
3632 			      struct unix_sock *unix_sk, uid_t uid)
3633 {
3634 	struct bpf_iter__unix ctx;
3635 
3636 	meta->seq_num--;  /* skip SEQ_START_TOKEN */
3637 	ctx.meta = meta;
3638 	ctx.unix_sk = unix_sk;
3639 	ctx.uid = uid;
3640 	return bpf_iter_run_prog(prog, &ctx);
3641 }
3642 
3643 static int bpf_iter_unix_hold_batch(struct seq_file *seq, struct sock *start_sk)
3644 
3645 {
3646 	struct bpf_unix_iter_state *iter = seq->private;
3647 	unsigned int expected = 1;
3648 	struct sock *sk;
3649 
3650 	sock_hold(start_sk);
3651 	iter->batch[iter->end_sk++] = start_sk;
3652 
3653 	for (sk = sk_next(start_sk); sk; sk = sk_next(sk)) {
3654 		if (iter->end_sk < iter->max_sk) {
3655 			sock_hold(sk);
3656 			iter->batch[iter->end_sk++] = sk;
3657 		}
3658 
3659 		expected++;
3660 	}
3661 
3662 	spin_unlock(&seq_file_net(seq)->unx.table.locks[start_sk->sk_hash]);
3663 
3664 	return expected;
3665 }
3666 
3667 static void bpf_iter_unix_put_batch(struct bpf_unix_iter_state *iter)
3668 {
3669 	while (iter->cur_sk < iter->end_sk)
3670 		sock_put(iter->batch[iter->cur_sk++]);
3671 }
3672 
3673 static int bpf_iter_unix_realloc_batch(struct bpf_unix_iter_state *iter,
3674 				       unsigned int new_batch_sz)
3675 {
3676 	struct sock **new_batch;
3677 
3678 	new_batch = kvmalloc_objs(*new_batch, new_batch_sz,
3679 				  GFP_USER | __GFP_NOWARN);
3680 	if (!new_batch)
3681 		return -ENOMEM;
3682 
3683 	bpf_iter_unix_put_batch(iter);
3684 	kvfree(iter->batch);
3685 	iter->batch = new_batch;
3686 	iter->max_sk = new_batch_sz;
3687 
3688 	return 0;
3689 }
3690 
3691 static struct sock *bpf_iter_unix_batch(struct seq_file *seq,
3692 					loff_t *pos)
3693 {
3694 	struct bpf_unix_iter_state *iter = seq->private;
3695 	unsigned int expected;
3696 	bool resized = false;
3697 	struct sock *sk;
3698 
3699 	if (iter->st_bucket_done)
3700 		*pos = set_bucket_offset(get_bucket(*pos) + 1, 1);
3701 
3702 again:
3703 	/* Get a new batch */
3704 	iter->cur_sk = 0;
3705 	iter->end_sk = 0;
3706 
3707 	sk = unix_get_first(seq, pos);
3708 	if (!sk)
3709 		return NULL; /* Done */
3710 
3711 	expected = bpf_iter_unix_hold_batch(seq, sk);
3712 
3713 	if (iter->end_sk == expected) {
3714 		iter->st_bucket_done = true;
3715 		return sk;
3716 	}
3717 
3718 	if (!resized && !bpf_iter_unix_realloc_batch(iter, expected * 3 / 2)) {
3719 		resized = true;
3720 		goto again;
3721 	}
3722 
3723 	return sk;
3724 }
3725 
3726 static void *bpf_iter_unix_seq_start(struct seq_file *seq, loff_t *pos)
3727 {
3728 	if (!*pos)
3729 		return SEQ_START_TOKEN;
3730 
3731 	/* bpf iter does not support lseek, so it always
3732 	 * continue from where it was stop()-ped.
3733 	 */
3734 	return bpf_iter_unix_batch(seq, pos);
3735 }
3736 
3737 static void *bpf_iter_unix_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3738 {
3739 	struct bpf_unix_iter_state *iter = seq->private;
3740 	struct sock *sk;
3741 
3742 	/* Whenever seq_next() is called, the iter->cur_sk is
3743 	 * done with seq_show(), so advance to the next sk in
3744 	 * the batch.
3745 	 */
3746 	if (iter->cur_sk < iter->end_sk)
3747 		sock_put(iter->batch[iter->cur_sk++]);
3748 
3749 	++*pos;
3750 
3751 	if (iter->cur_sk < iter->end_sk)
3752 		sk = iter->batch[iter->cur_sk];
3753 	else
3754 		sk = bpf_iter_unix_batch(seq, pos);
3755 
3756 	return sk;
3757 }
3758 
3759 static int bpf_iter_unix_seq_show(struct seq_file *seq, void *v)
3760 {
3761 	struct bpf_iter_meta meta;
3762 	struct bpf_prog *prog;
3763 	struct sock *sk = v;
3764 	uid_t uid;
3765 	int ret;
3766 
3767 	if (v == SEQ_START_TOKEN)
3768 		return 0;
3769 
3770 	lock_sock(sk);
3771 	unix_state_lock(sk);
3772 
3773 	if (unlikely(sock_flag(sk, SOCK_DEAD))) {
3774 		ret = SEQ_SKIP;
3775 		goto unlock;
3776 	}
3777 
3778 	uid = from_kuid_munged(seq_user_ns(seq), sk_uid(sk));
3779 	meta.seq = seq;
3780 	prog = bpf_iter_get_info(&meta, false);
3781 	ret = unix_prog_seq_show(prog, &meta, v, uid);
3782 unlock:
3783 	unix_state_unlock(sk);
3784 	release_sock(sk);
3785 	return ret;
3786 }
3787 
3788 static void bpf_iter_unix_seq_stop(struct seq_file *seq, void *v)
3789 {
3790 	struct bpf_unix_iter_state *iter = seq->private;
3791 	struct bpf_iter_meta meta;
3792 	struct bpf_prog *prog;
3793 
3794 	if (!v) {
3795 		meta.seq = seq;
3796 		prog = bpf_iter_get_info(&meta, true);
3797 		if (prog)
3798 			(void)unix_prog_seq_show(prog, &meta, v, 0);
3799 	}
3800 
3801 	if (iter->cur_sk < iter->end_sk)
3802 		bpf_iter_unix_put_batch(iter);
3803 }
3804 
3805 static const struct seq_operations bpf_iter_unix_seq_ops = {
3806 	.start	= bpf_iter_unix_seq_start,
3807 	.next	= bpf_iter_unix_seq_next,
3808 	.stop	= bpf_iter_unix_seq_stop,
3809 	.show	= bpf_iter_unix_seq_show,
3810 };
3811 #endif
3812 #endif
3813 
3814 static const struct net_proto_family unix_family_ops = {
3815 	.family = PF_UNIX,
3816 	.create = unix_create,
3817 	.owner	= THIS_MODULE,
3818 };
3819 
3820 
3821 static int __net_init unix_net_init(struct net *net)
3822 {
3823 	int i;
3824 
3825 	net->unx.sysctl_max_dgram_qlen = 10;
3826 	if (unix_sysctl_register(net))
3827 		goto out;
3828 
3829 #ifdef CONFIG_PROC_FS
3830 	if (!proc_create_net("unix", 0, net->proc_net, &unix_seq_ops,
3831 			     sizeof(struct seq_net_private)))
3832 		goto err_sysctl;
3833 #endif
3834 
3835 	net->unx.table.locks = kvmalloc_objs(spinlock_t, UNIX_HASH_SIZE);
3836 	if (!net->unx.table.locks)
3837 		goto err_proc;
3838 
3839 	net->unx.table.buckets = kvmalloc_objs(struct hlist_head,
3840 					       UNIX_HASH_SIZE);
3841 	if (!net->unx.table.buckets)
3842 		goto free_locks;
3843 
3844 	for (i = 0; i < UNIX_HASH_SIZE; i++) {
3845 		spin_lock_init(&net->unx.table.locks[i]);
3846 		lock_set_cmp_fn(&net->unx.table.locks[i], unix_table_lock_cmp_fn, NULL);
3847 		INIT_HLIST_HEAD(&net->unx.table.buckets[i]);
3848 	}
3849 
3850 	return 0;
3851 
3852 free_locks:
3853 	kvfree(net->unx.table.locks);
3854 err_proc:
3855 #ifdef CONFIG_PROC_FS
3856 	remove_proc_entry("unix", net->proc_net);
3857 err_sysctl:
3858 #endif
3859 	unix_sysctl_unregister(net);
3860 out:
3861 	return -ENOMEM;
3862 }
3863 
3864 static void __net_exit unix_net_exit(struct net *net)
3865 {
3866 	kvfree(net->unx.table.buckets);
3867 	kvfree(net->unx.table.locks);
3868 	unix_sysctl_unregister(net);
3869 	remove_proc_entry("unix", net->proc_net);
3870 }
3871 
3872 static struct pernet_operations unix_net_ops = {
3873 	.init = unix_net_init,
3874 	.exit = unix_net_exit,
3875 };
3876 
3877 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
3878 DEFINE_BPF_ITER_FUNC(unix, struct bpf_iter_meta *meta,
3879 		     struct unix_sock *unix_sk, uid_t uid)
3880 
3881 #define INIT_BATCH_SZ 16
3882 
3883 static int bpf_iter_init_unix(void *priv_data, struct bpf_iter_aux_info *aux)
3884 {
3885 	struct bpf_unix_iter_state *iter = priv_data;
3886 	int err;
3887 
3888 	err = bpf_iter_init_seq_net(priv_data, aux);
3889 	if (err)
3890 		return err;
3891 
3892 	err = bpf_iter_unix_realloc_batch(iter, INIT_BATCH_SZ);
3893 	if (err) {
3894 		bpf_iter_fini_seq_net(priv_data);
3895 		return err;
3896 	}
3897 
3898 	return 0;
3899 }
3900 
3901 static void bpf_iter_fini_unix(void *priv_data)
3902 {
3903 	struct bpf_unix_iter_state *iter = priv_data;
3904 
3905 	bpf_iter_fini_seq_net(priv_data);
3906 	kvfree(iter->batch);
3907 }
3908 
3909 static const struct bpf_iter_seq_info unix_seq_info = {
3910 	.seq_ops		= &bpf_iter_unix_seq_ops,
3911 	.init_seq_private	= bpf_iter_init_unix,
3912 	.fini_seq_private	= bpf_iter_fini_unix,
3913 	.seq_priv_size		= sizeof(struct bpf_unix_iter_state),
3914 };
3915 
3916 static const struct bpf_func_proto *
3917 bpf_iter_unix_get_func_proto(enum bpf_func_id func_id,
3918 			     const struct bpf_prog *prog)
3919 {
3920 	switch (func_id) {
3921 	case BPF_FUNC_setsockopt:
3922 		return &bpf_sk_setsockopt_proto;
3923 	case BPF_FUNC_getsockopt:
3924 		return &bpf_sk_getsockopt_proto;
3925 	default:
3926 		return NULL;
3927 	}
3928 }
3929 
3930 static struct bpf_iter_reg unix_reg_info = {
3931 	.target			= "unix",
3932 	.ctx_arg_info_size	= 1,
3933 	.ctx_arg_info		= {
3934 		{ offsetof(struct bpf_iter__unix, unix_sk),
3935 		  PTR_TO_BTF_ID_OR_NULL },
3936 	},
3937 	.get_func_proto         = bpf_iter_unix_get_func_proto,
3938 	.seq_info		= &unix_seq_info,
3939 };
3940 
3941 static void __init bpf_iter_register(void)
3942 {
3943 	unix_reg_info.ctx_arg_info[0].btf_id = btf_sock_ids[BTF_SOCK_TYPE_UNIX];
3944 	if (bpf_iter_reg_target(&unix_reg_info))
3945 		pr_warn("Warning: could not register bpf iterator unix\n");
3946 }
3947 #endif
3948 
3949 static int __init af_unix_init(void)
3950 {
3951 	int i, rc = -1;
3952 
3953 	BUILD_BUG_ON(sizeof(struct unix_skb_parms) > sizeof_field(struct sk_buff, cb));
3954 
3955 	for (i = 0; i < UNIX_HASH_SIZE / 2; i++) {
3956 		spin_lock_init(&bsd_socket_locks[i]);
3957 		INIT_HLIST_HEAD(&bsd_socket_buckets[i]);
3958 	}
3959 
3960 	rc = proto_register(&unix_dgram_proto, 1);
3961 	if (rc != 0) {
3962 		pr_crit("%s: Cannot create unix_sock SLAB cache!\n", __func__);
3963 		goto out;
3964 	}
3965 
3966 	rc = proto_register(&unix_stream_proto, 1);
3967 	if (rc != 0) {
3968 		pr_crit("%s: Cannot create unix_sock SLAB cache!\n", __func__);
3969 		proto_unregister(&unix_dgram_proto);
3970 		goto out;
3971 	}
3972 
3973 	sock_register(&unix_family_ops);
3974 	register_pernet_subsys(&unix_net_ops);
3975 	unix_bpf_build_proto();
3976 
3977 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
3978 	bpf_iter_register();
3979 #endif
3980 
3981 out:
3982 	return rc;
3983 }
3984 
3985 /* Later than subsys_initcall() because we depend on stuff initialised there */
3986 fs_initcall(af_unix_init);
3987