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