xref: /linux/net/kcm/kcmsock.c (revision 9ee0034b8f49aaaa7e7c2da8db1038915db99c19)
1 /*
2  * Kernel Connection Multiplexor
3  *
4  * Copyright (c) 2016 Tom Herbert <tom@herbertland.com>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2
8  * as published by the Free Software Foundation.
9  */
10 
11 #include <linux/bpf.h>
12 #include <linux/errno.h>
13 #include <linux/errqueue.h>
14 #include <linux/file.h>
15 #include <linux/in.h>
16 #include <linux/kernel.h>
17 #include <linux/module.h>
18 #include <linux/net.h>
19 #include <linux/netdevice.h>
20 #include <linux/poll.h>
21 #include <linux/rculist.h>
22 #include <linux/skbuff.h>
23 #include <linux/socket.h>
24 #include <linux/uaccess.h>
25 #include <linux/workqueue.h>
26 #include <net/kcm.h>
27 #include <net/netns/generic.h>
28 #include <net/sock.h>
29 #include <uapi/linux/kcm.h>
30 
31 unsigned int kcm_net_id;
32 
33 static struct kmem_cache *kcm_psockp __read_mostly;
34 static struct kmem_cache *kcm_muxp __read_mostly;
35 static struct workqueue_struct *kcm_wq;
36 
37 static inline struct kcm_sock *kcm_sk(const struct sock *sk)
38 {
39 	return (struct kcm_sock *)sk;
40 }
41 
42 static inline struct kcm_tx_msg *kcm_tx_msg(struct sk_buff *skb)
43 {
44 	return (struct kcm_tx_msg *)skb->cb;
45 }
46 
47 static void report_csk_error(struct sock *csk, int err)
48 {
49 	csk->sk_err = EPIPE;
50 	csk->sk_error_report(csk);
51 }
52 
53 static void kcm_abort_tx_psock(struct kcm_psock *psock, int err,
54 			       bool wakeup_kcm)
55 {
56 	struct sock *csk = psock->sk;
57 	struct kcm_mux *mux = psock->mux;
58 
59 	/* Unrecoverable error in transmit */
60 
61 	spin_lock_bh(&mux->lock);
62 
63 	if (psock->tx_stopped) {
64 		spin_unlock_bh(&mux->lock);
65 		return;
66 	}
67 
68 	psock->tx_stopped = 1;
69 	KCM_STATS_INCR(psock->stats.tx_aborts);
70 
71 	if (!psock->tx_kcm) {
72 		/* Take off psocks_avail list */
73 		list_del(&psock->psock_avail_list);
74 	} else if (wakeup_kcm) {
75 		/* In this case psock is being aborted while outside of
76 		 * write_msgs and psock is reserved. Schedule tx_work
77 		 * to handle the failure there. Need to commit tx_stopped
78 		 * before queuing work.
79 		 */
80 		smp_mb();
81 
82 		queue_work(kcm_wq, &psock->tx_kcm->tx_work);
83 	}
84 
85 	spin_unlock_bh(&mux->lock);
86 
87 	/* Report error on lower socket */
88 	report_csk_error(csk, err);
89 }
90 
91 /* RX mux lock held. */
92 static void kcm_update_rx_mux_stats(struct kcm_mux *mux,
93 				    struct kcm_psock *psock)
94 {
95 	STRP_STATS_ADD(mux->stats.rx_bytes,
96 		       psock->strp.stats.rx_bytes -
97 		       psock->saved_rx_bytes);
98 	mux->stats.rx_msgs +=
99 		psock->strp.stats.rx_msgs - psock->saved_rx_msgs;
100 	psock->saved_rx_msgs = psock->strp.stats.rx_msgs;
101 	psock->saved_rx_bytes = psock->strp.stats.rx_bytes;
102 }
103 
104 static void kcm_update_tx_mux_stats(struct kcm_mux *mux,
105 				    struct kcm_psock *psock)
106 {
107 	KCM_STATS_ADD(mux->stats.tx_bytes,
108 		      psock->stats.tx_bytes - psock->saved_tx_bytes);
109 	mux->stats.tx_msgs +=
110 		psock->stats.tx_msgs - psock->saved_tx_msgs;
111 	psock->saved_tx_msgs = psock->stats.tx_msgs;
112 	psock->saved_tx_bytes = psock->stats.tx_bytes;
113 }
114 
115 static int kcm_queue_rcv_skb(struct sock *sk, struct sk_buff *skb);
116 
117 /* KCM is ready to receive messages on its queue-- either the KCM is new or
118  * has become unblocked after being blocked on full socket buffer. Queue any
119  * pending ready messages on a psock. RX mux lock held.
120  */
121 static void kcm_rcv_ready(struct kcm_sock *kcm)
122 {
123 	struct kcm_mux *mux = kcm->mux;
124 	struct kcm_psock *psock;
125 	struct sk_buff *skb;
126 
127 	if (unlikely(kcm->rx_wait || kcm->rx_psock || kcm->rx_disabled))
128 		return;
129 
130 	while (unlikely((skb = __skb_dequeue(&mux->rx_hold_queue)))) {
131 		if (kcm_queue_rcv_skb(&kcm->sk, skb)) {
132 			/* Assuming buffer limit has been reached */
133 			skb_queue_head(&mux->rx_hold_queue, skb);
134 			WARN_ON(!sk_rmem_alloc_get(&kcm->sk));
135 			return;
136 		}
137 	}
138 
139 	while (!list_empty(&mux->psocks_ready)) {
140 		psock = list_first_entry(&mux->psocks_ready, struct kcm_psock,
141 					 psock_ready_list);
142 
143 		if (kcm_queue_rcv_skb(&kcm->sk, psock->ready_rx_msg)) {
144 			/* Assuming buffer limit has been reached */
145 			WARN_ON(!sk_rmem_alloc_get(&kcm->sk));
146 			return;
147 		}
148 
149 		/* Consumed the ready message on the psock. Schedule rx_work to
150 		 * get more messages.
151 		 */
152 		list_del(&psock->psock_ready_list);
153 		psock->ready_rx_msg = NULL;
154 		/* Commit clearing of ready_rx_msg for queuing work */
155 		smp_mb();
156 
157 		strp_unpause(&psock->strp);
158 		strp_check_rcv(&psock->strp);
159 	}
160 
161 	/* Buffer limit is okay now, add to ready list */
162 	list_add_tail(&kcm->wait_rx_list,
163 		      &kcm->mux->kcm_rx_waiters);
164 	kcm->rx_wait = true;
165 }
166 
167 static void kcm_rfree(struct sk_buff *skb)
168 {
169 	struct sock *sk = skb->sk;
170 	struct kcm_sock *kcm = kcm_sk(sk);
171 	struct kcm_mux *mux = kcm->mux;
172 	unsigned int len = skb->truesize;
173 
174 	sk_mem_uncharge(sk, len);
175 	atomic_sub(len, &sk->sk_rmem_alloc);
176 
177 	/* For reading rx_wait and rx_psock without holding lock */
178 	smp_mb__after_atomic();
179 
180 	if (!kcm->rx_wait && !kcm->rx_psock &&
181 	    sk_rmem_alloc_get(sk) < sk->sk_rcvlowat) {
182 		spin_lock_bh(&mux->rx_lock);
183 		kcm_rcv_ready(kcm);
184 		spin_unlock_bh(&mux->rx_lock);
185 	}
186 }
187 
188 static int kcm_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
189 {
190 	struct sk_buff_head *list = &sk->sk_receive_queue;
191 
192 	if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
193 		return -ENOMEM;
194 
195 	if (!sk_rmem_schedule(sk, skb, skb->truesize))
196 		return -ENOBUFS;
197 
198 	skb->dev = NULL;
199 
200 	skb_orphan(skb);
201 	skb->sk = sk;
202 	skb->destructor = kcm_rfree;
203 	atomic_add(skb->truesize, &sk->sk_rmem_alloc);
204 	sk_mem_charge(sk, skb->truesize);
205 
206 	skb_queue_tail(list, skb);
207 
208 	if (!sock_flag(sk, SOCK_DEAD))
209 		sk->sk_data_ready(sk);
210 
211 	return 0;
212 }
213 
214 /* Requeue received messages for a kcm socket to other kcm sockets. This is
215  * called with a kcm socket is receive disabled.
216  * RX mux lock held.
217  */
218 static void requeue_rx_msgs(struct kcm_mux *mux, struct sk_buff_head *head)
219 {
220 	struct sk_buff *skb;
221 	struct kcm_sock *kcm;
222 
223 	while ((skb = __skb_dequeue(head))) {
224 		/* Reset destructor to avoid calling kcm_rcv_ready */
225 		skb->destructor = sock_rfree;
226 		skb_orphan(skb);
227 try_again:
228 		if (list_empty(&mux->kcm_rx_waiters)) {
229 			skb_queue_tail(&mux->rx_hold_queue, skb);
230 			continue;
231 		}
232 
233 		kcm = list_first_entry(&mux->kcm_rx_waiters,
234 				       struct kcm_sock, wait_rx_list);
235 
236 		if (kcm_queue_rcv_skb(&kcm->sk, skb)) {
237 			/* Should mean socket buffer full */
238 			list_del(&kcm->wait_rx_list);
239 			kcm->rx_wait = false;
240 
241 			/* Commit rx_wait to read in kcm_free */
242 			smp_wmb();
243 
244 			goto try_again;
245 		}
246 	}
247 }
248 
249 /* Lower sock lock held */
250 static struct kcm_sock *reserve_rx_kcm(struct kcm_psock *psock,
251 				       struct sk_buff *head)
252 {
253 	struct kcm_mux *mux = psock->mux;
254 	struct kcm_sock *kcm;
255 
256 	WARN_ON(psock->ready_rx_msg);
257 
258 	if (psock->rx_kcm)
259 		return psock->rx_kcm;
260 
261 	spin_lock_bh(&mux->rx_lock);
262 
263 	if (psock->rx_kcm) {
264 		spin_unlock_bh(&mux->rx_lock);
265 		return psock->rx_kcm;
266 	}
267 
268 	kcm_update_rx_mux_stats(mux, psock);
269 
270 	if (list_empty(&mux->kcm_rx_waiters)) {
271 		psock->ready_rx_msg = head;
272 		strp_pause(&psock->strp);
273 		list_add_tail(&psock->psock_ready_list,
274 			      &mux->psocks_ready);
275 		spin_unlock_bh(&mux->rx_lock);
276 		return NULL;
277 	}
278 
279 	kcm = list_first_entry(&mux->kcm_rx_waiters,
280 			       struct kcm_sock, wait_rx_list);
281 	list_del(&kcm->wait_rx_list);
282 	kcm->rx_wait = false;
283 
284 	psock->rx_kcm = kcm;
285 	kcm->rx_psock = psock;
286 
287 	spin_unlock_bh(&mux->rx_lock);
288 
289 	return kcm;
290 }
291 
292 static void kcm_done(struct kcm_sock *kcm);
293 
294 static void kcm_done_work(struct work_struct *w)
295 {
296 	kcm_done(container_of(w, struct kcm_sock, done_work));
297 }
298 
299 /* Lower sock held */
300 static void unreserve_rx_kcm(struct kcm_psock *psock,
301 			     bool rcv_ready)
302 {
303 	struct kcm_sock *kcm = psock->rx_kcm;
304 	struct kcm_mux *mux = psock->mux;
305 
306 	if (!kcm)
307 		return;
308 
309 	spin_lock_bh(&mux->rx_lock);
310 
311 	psock->rx_kcm = NULL;
312 	kcm->rx_psock = NULL;
313 
314 	/* Commit kcm->rx_psock before sk_rmem_alloc_get to sync with
315 	 * kcm_rfree
316 	 */
317 	smp_mb();
318 
319 	if (unlikely(kcm->done)) {
320 		spin_unlock_bh(&mux->rx_lock);
321 
322 		/* Need to run kcm_done in a task since we need to qcquire
323 		 * callback locks which may already be held here.
324 		 */
325 		INIT_WORK(&kcm->done_work, kcm_done_work);
326 		schedule_work(&kcm->done_work);
327 		return;
328 	}
329 
330 	if (unlikely(kcm->rx_disabled)) {
331 		requeue_rx_msgs(mux, &kcm->sk.sk_receive_queue);
332 	} else if (rcv_ready || unlikely(!sk_rmem_alloc_get(&kcm->sk))) {
333 		/* Check for degenerative race with rx_wait that all
334 		 * data was dequeued (accounted for in kcm_rfree).
335 		 */
336 		kcm_rcv_ready(kcm);
337 	}
338 	spin_unlock_bh(&mux->rx_lock);
339 }
340 
341 /* Lower sock lock held */
342 static void psock_data_ready(struct sock *sk)
343 {
344 	struct kcm_psock *psock;
345 
346 	read_lock_bh(&sk->sk_callback_lock);
347 
348 	psock = (struct kcm_psock *)sk->sk_user_data;
349 	if (likely(psock))
350 		strp_data_ready(&psock->strp);
351 
352 	read_unlock_bh(&sk->sk_callback_lock);
353 }
354 
355 /* Called with lower sock held */
356 static void kcm_rcv_strparser(struct strparser *strp, struct sk_buff *skb)
357 {
358 	struct kcm_psock *psock = container_of(strp, struct kcm_psock, strp);
359 	struct kcm_sock *kcm;
360 
361 try_queue:
362 	kcm = reserve_rx_kcm(psock, skb);
363 	if (!kcm) {
364 		 /* Unable to reserve a KCM, message is held in psock and strp
365 		  * is paused.
366 		  */
367 		return;
368 	}
369 
370 	if (kcm_queue_rcv_skb(&kcm->sk, skb)) {
371 		/* Should mean socket buffer full */
372 		unreserve_rx_kcm(psock, false);
373 		goto try_queue;
374 	}
375 }
376 
377 static int kcm_parse_func_strparser(struct strparser *strp, struct sk_buff *skb)
378 {
379 	struct kcm_psock *psock = container_of(strp, struct kcm_psock, strp);
380 	struct bpf_prog *prog = psock->bpf_prog;
381 
382 	return (*prog->bpf_func)(skb, prog->insnsi);
383 }
384 
385 static int kcm_read_sock_done(struct strparser *strp, int err)
386 {
387 	struct kcm_psock *psock = container_of(strp, struct kcm_psock, strp);
388 
389 	unreserve_rx_kcm(psock, true);
390 
391 	return err;
392 }
393 
394 static void psock_state_change(struct sock *sk)
395 {
396 	/* TCP only does a POLLIN for a half close. Do a POLLHUP here
397 	 * since application will normally not poll with POLLIN
398 	 * on the TCP sockets.
399 	 */
400 
401 	report_csk_error(sk, EPIPE);
402 }
403 
404 static void psock_write_space(struct sock *sk)
405 {
406 	struct kcm_psock *psock;
407 	struct kcm_mux *mux;
408 	struct kcm_sock *kcm;
409 
410 	read_lock_bh(&sk->sk_callback_lock);
411 
412 	psock = (struct kcm_psock *)sk->sk_user_data;
413 	if (unlikely(!psock))
414 		goto out;
415 	mux = psock->mux;
416 
417 	spin_lock_bh(&mux->lock);
418 
419 	/* Check if the socket is reserved so someone is waiting for sending. */
420 	kcm = psock->tx_kcm;
421 	if (kcm && !unlikely(kcm->tx_stopped))
422 		queue_work(kcm_wq, &kcm->tx_work);
423 
424 	spin_unlock_bh(&mux->lock);
425 out:
426 	read_unlock_bh(&sk->sk_callback_lock);
427 }
428 
429 static void unreserve_psock(struct kcm_sock *kcm);
430 
431 /* kcm sock is locked. */
432 static struct kcm_psock *reserve_psock(struct kcm_sock *kcm)
433 {
434 	struct kcm_mux *mux = kcm->mux;
435 	struct kcm_psock *psock;
436 
437 	psock = kcm->tx_psock;
438 
439 	smp_rmb(); /* Must read tx_psock before tx_wait */
440 
441 	if (psock) {
442 		WARN_ON(kcm->tx_wait);
443 		if (unlikely(psock->tx_stopped))
444 			unreserve_psock(kcm);
445 		else
446 			return kcm->tx_psock;
447 	}
448 
449 	spin_lock_bh(&mux->lock);
450 
451 	/* Check again under lock to see if psock was reserved for this
452 	 * psock via psock_unreserve.
453 	 */
454 	psock = kcm->tx_psock;
455 	if (unlikely(psock)) {
456 		WARN_ON(kcm->tx_wait);
457 		spin_unlock_bh(&mux->lock);
458 		return kcm->tx_psock;
459 	}
460 
461 	if (!list_empty(&mux->psocks_avail)) {
462 		psock = list_first_entry(&mux->psocks_avail,
463 					 struct kcm_psock,
464 					 psock_avail_list);
465 		list_del(&psock->psock_avail_list);
466 		if (kcm->tx_wait) {
467 			list_del(&kcm->wait_psock_list);
468 			kcm->tx_wait = false;
469 		}
470 		kcm->tx_psock = psock;
471 		psock->tx_kcm = kcm;
472 		KCM_STATS_INCR(psock->stats.reserved);
473 	} else if (!kcm->tx_wait) {
474 		list_add_tail(&kcm->wait_psock_list,
475 			      &mux->kcm_tx_waiters);
476 		kcm->tx_wait = true;
477 	}
478 
479 	spin_unlock_bh(&mux->lock);
480 
481 	return psock;
482 }
483 
484 /* mux lock held */
485 static void psock_now_avail(struct kcm_psock *psock)
486 {
487 	struct kcm_mux *mux = psock->mux;
488 	struct kcm_sock *kcm;
489 
490 	if (list_empty(&mux->kcm_tx_waiters)) {
491 		list_add_tail(&psock->psock_avail_list,
492 			      &mux->psocks_avail);
493 	} else {
494 		kcm = list_first_entry(&mux->kcm_tx_waiters,
495 				       struct kcm_sock,
496 				       wait_psock_list);
497 		list_del(&kcm->wait_psock_list);
498 		kcm->tx_wait = false;
499 		psock->tx_kcm = kcm;
500 
501 		/* Commit before changing tx_psock since that is read in
502 		 * reserve_psock before queuing work.
503 		 */
504 		smp_mb();
505 
506 		kcm->tx_psock = psock;
507 		KCM_STATS_INCR(psock->stats.reserved);
508 		queue_work(kcm_wq, &kcm->tx_work);
509 	}
510 }
511 
512 /* kcm sock is locked. */
513 static void unreserve_psock(struct kcm_sock *kcm)
514 {
515 	struct kcm_psock *psock;
516 	struct kcm_mux *mux = kcm->mux;
517 
518 	spin_lock_bh(&mux->lock);
519 
520 	psock = kcm->tx_psock;
521 
522 	if (WARN_ON(!psock)) {
523 		spin_unlock_bh(&mux->lock);
524 		return;
525 	}
526 
527 	smp_rmb(); /* Read tx_psock before tx_wait */
528 
529 	kcm_update_tx_mux_stats(mux, psock);
530 
531 	WARN_ON(kcm->tx_wait);
532 
533 	kcm->tx_psock = NULL;
534 	psock->tx_kcm = NULL;
535 	KCM_STATS_INCR(psock->stats.unreserved);
536 
537 	if (unlikely(psock->tx_stopped)) {
538 		if (psock->done) {
539 			/* Deferred free */
540 			list_del(&psock->psock_list);
541 			mux->psocks_cnt--;
542 			sock_put(psock->sk);
543 			fput(psock->sk->sk_socket->file);
544 			kmem_cache_free(kcm_psockp, psock);
545 		}
546 
547 		/* Don't put back on available list */
548 
549 		spin_unlock_bh(&mux->lock);
550 
551 		return;
552 	}
553 
554 	psock_now_avail(psock);
555 
556 	spin_unlock_bh(&mux->lock);
557 }
558 
559 static void kcm_report_tx_retry(struct kcm_sock *kcm)
560 {
561 	struct kcm_mux *mux = kcm->mux;
562 
563 	spin_lock_bh(&mux->lock);
564 	KCM_STATS_INCR(mux->stats.tx_retries);
565 	spin_unlock_bh(&mux->lock);
566 }
567 
568 /* Write any messages ready on the kcm socket.  Called with kcm sock lock
569  * held.  Return bytes actually sent or error.
570  */
571 static int kcm_write_msgs(struct kcm_sock *kcm)
572 {
573 	struct sock *sk = &kcm->sk;
574 	struct kcm_psock *psock;
575 	struct sk_buff *skb, *head;
576 	struct kcm_tx_msg *txm;
577 	unsigned short fragidx, frag_offset;
578 	unsigned int sent, total_sent = 0;
579 	int ret = 0;
580 
581 	kcm->tx_wait_more = false;
582 	psock = kcm->tx_psock;
583 	if (unlikely(psock && psock->tx_stopped)) {
584 		/* A reserved psock was aborted asynchronously. Unreserve
585 		 * it and we'll retry the message.
586 		 */
587 		unreserve_psock(kcm);
588 		kcm_report_tx_retry(kcm);
589 		if (skb_queue_empty(&sk->sk_write_queue))
590 			return 0;
591 
592 		kcm_tx_msg(skb_peek(&sk->sk_write_queue))->sent = 0;
593 
594 	} else if (skb_queue_empty(&sk->sk_write_queue)) {
595 		return 0;
596 	}
597 
598 	head = skb_peek(&sk->sk_write_queue);
599 	txm = kcm_tx_msg(head);
600 
601 	if (txm->sent) {
602 		/* Send of first skbuff in queue already in progress */
603 		if (WARN_ON(!psock)) {
604 			ret = -EINVAL;
605 			goto out;
606 		}
607 		sent = txm->sent;
608 		frag_offset = txm->frag_offset;
609 		fragidx = txm->fragidx;
610 		skb = txm->frag_skb;
611 
612 		goto do_frag;
613 	}
614 
615 try_again:
616 	psock = reserve_psock(kcm);
617 	if (!psock)
618 		goto out;
619 
620 	do {
621 		skb = head;
622 		txm = kcm_tx_msg(head);
623 		sent = 0;
624 
625 do_frag_list:
626 		if (WARN_ON(!skb_shinfo(skb)->nr_frags)) {
627 			ret = -EINVAL;
628 			goto out;
629 		}
630 
631 		for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags;
632 		     fragidx++) {
633 			skb_frag_t *frag;
634 
635 			frag_offset = 0;
636 do_frag:
637 			frag = &skb_shinfo(skb)->frags[fragidx];
638 			if (WARN_ON(!frag->size)) {
639 				ret = -EINVAL;
640 				goto out;
641 			}
642 
643 			ret = kernel_sendpage(psock->sk->sk_socket,
644 					      frag->page.p,
645 					      frag->page_offset + frag_offset,
646 					      frag->size - frag_offset,
647 					      MSG_DONTWAIT);
648 			if (ret <= 0) {
649 				if (ret == -EAGAIN) {
650 					/* Save state to try again when there's
651 					 * write space on the socket
652 					 */
653 					txm->sent = sent;
654 					txm->frag_offset = frag_offset;
655 					txm->fragidx = fragidx;
656 					txm->frag_skb = skb;
657 
658 					ret = 0;
659 					goto out;
660 				}
661 
662 				/* Hard failure in sending message, abort this
663 				 * psock since it has lost framing
664 				 * synchonization and retry sending the
665 				 * message from the beginning.
666 				 */
667 				kcm_abort_tx_psock(psock, ret ? -ret : EPIPE,
668 						   true);
669 				unreserve_psock(kcm);
670 
671 				txm->sent = 0;
672 				kcm_report_tx_retry(kcm);
673 				ret = 0;
674 
675 				goto try_again;
676 			}
677 
678 			sent += ret;
679 			frag_offset += ret;
680 			KCM_STATS_ADD(psock->stats.tx_bytes, ret);
681 			if (frag_offset < frag->size) {
682 				/* Not finished with this frag */
683 				goto do_frag;
684 			}
685 		}
686 
687 		if (skb == head) {
688 			if (skb_has_frag_list(skb)) {
689 				skb = skb_shinfo(skb)->frag_list;
690 				goto do_frag_list;
691 			}
692 		} else if (skb->next) {
693 			skb = skb->next;
694 			goto do_frag_list;
695 		}
696 
697 		/* Successfully sent the whole packet, account for it. */
698 		skb_dequeue(&sk->sk_write_queue);
699 		kfree_skb(head);
700 		sk->sk_wmem_queued -= sent;
701 		total_sent += sent;
702 		KCM_STATS_INCR(psock->stats.tx_msgs);
703 	} while ((head = skb_peek(&sk->sk_write_queue)));
704 out:
705 	if (!head) {
706 		/* Done with all queued messages. */
707 		WARN_ON(!skb_queue_empty(&sk->sk_write_queue));
708 		unreserve_psock(kcm);
709 	}
710 
711 	/* Check if write space is available */
712 	sk->sk_write_space(sk);
713 
714 	return total_sent ? : ret;
715 }
716 
717 static void kcm_tx_work(struct work_struct *w)
718 {
719 	struct kcm_sock *kcm = container_of(w, struct kcm_sock, tx_work);
720 	struct sock *sk = &kcm->sk;
721 	int err;
722 
723 	lock_sock(sk);
724 
725 	/* Primarily for SOCK_DGRAM sockets, also handle asynchronous tx
726 	 * aborts
727 	 */
728 	err = kcm_write_msgs(kcm);
729 	if (err < 0) {
730 		/* Hard failure in write, report error on KCM socket */
731 		pr_warn("KCM: Hard failure on kcm_write_msgs %d\n", err);
732 		report_csk_error(&kcm->sk, -err);
733 		goto out;
734 	}
735 
736 	/* Primarily for SOCK_SEQPACKET sockets */
737 	if (likely(sk->sk_socket) &&
738 	    test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
739 		clear_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
740 		sk->sk_write_space(sk);
741 	}
742 
743 out:
744 	release_sock(sk);
745 }
746 
747 static void kcm_push(struct kcm_sock *kcm)
748 {
749 	if (kcm->tx_wait_more)
750 		kcm_write_msgs(kcm);
751 }
752 
753 static ssize_t kcm_sendpage(struct socket *sock, struct page *page,
754 			    int offset, size_t size, int flags)
755 
756 {
757 	struct sock *sk = sock->sk;
758 	struct kcm_sock *kcm = kcm_sk(sk);
759 	struct sk_buff *skb = NULL, *head = NULL;
760 	long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
761 	bool eor;
762 	int err = 0;
763 	int i;
764 
765 	if (flags & MSG_SENDPAGE_NOTLAST)
766 		flags |= MSG_MORE;
767 
768 	/* No MSG_EOR from splice, only look at MSG_MORE */
769 	eor = !(flags & MSG_MORE);
770 
771 	lock_sock(sk);
772 
773 	sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
774 
775 	err = -EPIPE;
776 	if (sk->sk_err)
777 		goto out_error;
778 
779 	if (kcm->seq_skb) {
780 		/* Previously opened message */
781 		head = kcm->seq_skb;
782 		skb = kcm_tx_msg(head)->last_skb;
783 		i = skb_shinfo(skb)->nr_frags;
784 
785 		if (skb_can_coalesce(skb, i, page, offset)) {
786 			skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
787 			skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
788 			goto coalesced;
789 		}
790 
791 		if (i >= MAX_SKB_FRAGS) {
792 			struct sk_buff *tskb;
793 
794 			tskb = alloc_skb(0, sk->sk_allocation);
795 			while (!tskb) {
796 				kcm_push(kcm);
797 				err = sk_stream_wait_memory(sk, &timeo);
798 				if (err)
799 					goto out_error;
800 			}
801 
802 			if (head == skb)
803 				skb_shinfo(head)->frag_list = tskb;
804 			else
805 				skb->next = tskb;
806 
807 			skb = tskb;
808 			skb->ip_summed = CHECKSUM_UNNECESSARY;
809 			i = 0;
810 		}
811 	} else {
812 		/* Call the sk_stream functions to manage the sndbuf mem. */
813 		if (!sk_stream_memory_free(sk)) {
814 			kcm_push(kcm);
815 			set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
816 			err = sk_stream_wait_memory(sk, &timeo);
817 			if (err)
818 				goto out_error;
819 		}
820 
821 		head = alloc_skb(0, sk->sk_allocation);
822 		while (!head) {
823 			kcm_push(kcm);
824 			err = sk_stream_wait_memory(sk, &timeo);
825 			if (err)
826 				goto out_error;
827 		}
828 
829 		skb = head;
830 		i = 0;
831 	}
832 
833 	get_page(page);
834 	skb_fill_page_desc(skb, i, page, offset, size);
835 	skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
836 
837 coalesced:
838 	skb->len += size;
839 	skb->data_len += size;
840 	skb->truesize += size;
841 	sk->sk_wmem_queued += size;
842 	sk_mem_charge(sk, size);
843 
844 	if (head != skb) {
845 		head->len += size;
846 		head->data_len += size;
847 		head->truesize += size;
848 	}
849 
850 	if (eor) {
851 		bool not_busy = skb_queue_empty(&sk->sk_write_queue);
852 
853 		/* Message complete, queue it on send buffer */
854 		__skb_queue_tail(&sk->sk_write_queue, head);
855 		kcm->seq_skb = NULL;
856 		KCM_STATS_INCR(kcm->stats.tx_msgs);
857 
858 		if (flags & MSG_BATCH) {
859 			kcm->tx_wait_more = true;
860 		} else if (kcm->tx_wait_more || not_busy) {
861 			err = kcm_write_msgs(kcm);
862 			if (err < 0) {
863 				/* We got a hard error in write_msgs but have
864 				 * already queued this message. Report an error
865 				 * in the socket, but don't affect return value
866 				 * from sendmsg
867 				 */
868 				pr_warn("KCM: Hard failure on kcm_write_msgs\n");
869 				report_csk_error(&kcm->sk, -err);
870 			}
871 		}
872 	} else {
873 		/* Message not complete, save state */
874 		kcm->seq_skb = head;
875 		kcm_tx_msg(head)->last_skb = skb;
876 	}
877 
878 	KCM_STATS_ADD(kcm->stats.tx_bytes, size);
879 
880 	release_sock(sk);
881 	return size;
882 
883 out_error:
884 	kcm_push(kcm);
885 
886 	err = sk_stream_error(sk, flags, err);
887 
888 	/* make sure we wake any epoll edge trigger waiter */
889 	if (unlikely(skb_queue_len(&sk->sk_write_queue) == 0 && err == -EAGAIN))
890 		sk->sk_write_space(sk);
891 
892 	release_sock(sk);
893 	return err;
894 }
895 
896 static int kcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
897 {
898 	struct sock *sk = sock->sk;
899 	struct kcm_sock *kcm = kcm_sk(sk);
900 	struct sk_buff *skb = NULL, *head = NULL;
901 	size_t copy, copied = 0;
902 	long timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
903 	int eor = (sock->type == SOCK_DGRAM) ?
904 		  !(msg->msg_flags & MSG_MORE) : !!(msg->msg_flags & MSG_EOR);
905 	int err = -EPIPE;
906 
907 	lock_sock(sk);
908 
909 	/* Per tcp_sendmsg this should be in poll */
910 	sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
911 
912 	if (sk->sk_err)
913 		goto out_error;
914 
915 	if (kcm->seq_skb) {
916 		/* Previously opened message */
917 		head = kcm->seq_skb;
918 		skb = kcm_tx_msg(head)->last_skb;
919 		goto start;
920 	}
921 
922 	/* Call the sk_stream functions to manage the sndbuf mem. */
923 	if (!sk_stream_memory_free(sk)) {
924 		kcm_push(kcm);
925 		set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
926 		err = sk_stream_wait_memory(sk, &timeo);
927 		if (err)
928 			goto out_error;
929 	}
930 
931 	/* New message, alloc head skb */
932 	head = alloc_skb(0, sk->sk_allocation);
933 	while (!head) {
934 		kcm_push(kcm);
935 		err = sk_stream_wait_memory(sk, &timeo);
936 		if (err)
937 			goto out_error;
938 
939 		head = alloc_skb(0, sk->sk_allocation);
940 	}
941 
942 	skb = head;
943 
944 	/* Set ip_summed to CHECKSUM_UNNECESSARY to avoid calling
945 	 * csum_and_copy_from_iter from skb_do_copy_data_nocache.
946 	 */
947 	skb->ip_summed = CHECKSUM_UNNECESSARY;
948 
949 start:
950 	while (msg_data_left(msg)) {
951 		bool merge = true;
952 		int i = skb_shinfo(skb)->nr_frags;
953 		struct page_frag *pfrag = sk_page_frag(sk);
954 
955 		if (!sk_page_frag_refill(sk, pfrag))
956 			goto wait_for_memory;
957 
958 		if (!skb_can_coalesce(skb, i, pfrag->page,
959 				      pfrag->offset)) {
960 			if (i == MAX_SKB_FRAGS) {
961 				struct sk_buff *tskb;
962 
963 				tskb = alloc_skb(0, sk->sk_allocation);
964 				if (!tskb)
965 					goto wait_for_memory;
966 
967 				if (head == skb)
968 					skb_shinfo(head)->frag_list = tskb;
969 				else
970 					skb->next = tskb;
971 
972 				skb = tskb;
973 				skb->ip_summed = CHECKSUM_UNNECESSARY;
974 				continue;
975 			}
976 			merge = false;
977 		}
978 
979 		copy = min_t(int, msg_data_left(msg),
980 			     pfrag->size - pfrag->offset);
981 
982 		if (!sk_wmem_schedule(sk, copy))
983 			goto wait_for_memory;
984 
985 		err = skb_copy_to_page_nocache(sk, &msg->msg_iter, skb,
986 					       pfrag->page,
987 					       pfrag->offset,
988 					       copy);
989 		if (err)
990 			goto out_error;
991 
992 		/* Update the skb. */
993 		if (merge) {
994 			skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
995 		} else {
996 			skb_fill_page_desc(skb, i, pfrag->page,
997 					   pfrag->offset, copy);
998 			get_page(pfrag->page);
999 		}
1000 
1001 		pfrag->offset += copy;
1002 		copied += copy;
1003 		if (head != skb) {
1004 			head->len += copy;
1005 			head->data_len += copy;
1006 		}
1007 
1008 		continue;
1009 
1010 wait_for_memory:
1011 		kcm_push(kcm);
1012 		err = sk_stream_wait_memory(sk, &timeo);
1013 		if (err)
1014 			goto out_error;
1015 	}
1016 
1017 	if (eor) {
1018 		bool not_busy = skb_queue_empty(&sk->sk_write_queue);
1019 
1020 		/* Message complete, queue it on send buffer */
1021 		__skb_queue_tail(&sk->sk_write_queue, head);
1022 		kcm->seq_skb = NULL;
1023 		KCM_STATS_INCR(kcm->stats.tx_msgs);
1024 
1025 		if (msg->msg_flags & MSG_BATCH) {
1026 			kcm->tx_wait_more = true;
1027 		} else if (kcm->tx_wait_more || not_busy) {
1028 			err = kcm_write_msgs(kcm);
1029 			if (err < 0) {
1030 				/* We got a hard error in write_msgs but have
1031 				 * already queued this message. Report an error
1032 				 * in the socket, but don't affect return value
1033 				 * from sendmsg
1034 				 */
1035 				pr_warn("KCM: Hard failure on kcm_write_msgs\n");
1036 				report_csk_error(&kcm->sk, -err);
1037 			}
1038 		}
1039 	} else {
1040 		/* Message not complete, save state */
1041 partial_message:
1042 		kcm->seq_skb = head;
1043 		kcm_tx_msg(head)->last_skb = skb;
1044 	}
1045 
1046 	KCM_STATS_ADD(kcm->stats.tx_bytes, copied);
1047 
1048 	release_sock(sk);
1049 	return copied;
1050 
1051 out_error:
1052 	kcm_push(kcm);
1053 
1054 	if (copied && sock->type == SOCK_SEQPACKET) {
1055 		/* Wrote some bytes before encountering an
1056 		 * error, return partial success.
1057 		 */
1058 		goto partial_message;
1059 	}
1060 
1061 	if (head != kcm->seq_skb)
1062 		kfree_skb(head);
1063 
1064 	err = sk_stream_error(sk, msg->msg_flags, err);
1065 
1066 	/* make sure we wake any epoll edge trigger waiter */
1067 	if (unlikely(skb_queue_len(&sk->sk_write_queue) == 0 && err == -EAGAIN))
1068 		sk->sk_write_space(sk);
1069 
1070 	release_sock(sk);
1071 	return err;
1072 }
1073 
1074 static struct sk_buff *kcm_wait_data(struct sock *sk, int flags,
1075 				     long timeo, int *err)
1076 {
1077 	struct sk_buff *skb;
1078 
1079 	while (!(skb = skb_peek(&sk->sk_receive_queue))) {
1080 		if (sk->sk_err) {
1081 			*err = sock_error(sk);
1082 			return NULL;
1083 		}
1084 
1085 		if (sock_flag(sk, SOCK_DONE))
1086 			return NULL;
1087 
1088 		if ((flags & MSG_DONTWAIT) || !timeo) {
1089 			*err = -EAGAIN;
1090 			return NULL;
1091 		}
1092 
1093 		sk_wait_data(sk, &timeo, NULL);
1094 
1095 		/* Handle signals */
1096 		if (signal_pending(current)) {
1097 			*err = sock_intr_errno(timeo);
1098 			return NULL;
1099 		}
1100 	}
1101 
1102 	return skb;
1103 }
1104 
1105 static int kcm_recvmsg(struct socket *sock, struct msghdr *msg,
1106 		       size_t len, int flags)
1107 {
1108 	struct sock *sk = sock->sk;
1109 	struct kcm_sock *kcm = kcm_sk(sk);
1110 	int err = 0;
1111 	long timeo;
1112 	struct strp_rx_msg *rxm;
1113 	int copied = 0;
1114 	struct sk_buff *skb;
1115 
1116 	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1117 
1118 	lock_sock(sk);
1119 
1120 	skb = kcm_wait_data(sk, flags, timeo, &err);
1121 	if (!skb)
1122 		goto out;
1123 
1124 	/* Okay, have a message on the receive queue */
1125 
1126 	rxm = strp_rx_msg(skb);
1127 
1128 	if (len > rxm->full_len)
1129 		len = rxm->full_len;
1130 
1131 	err = skb_copy_datagram_msg(skb, rxm->offset, msg, len);
1132 	if (err < 0)
1133 		goto out;
1134 
1135 	copied = len;
1136 	if (likely(!(flags & MSG_PEEK))) {
1137 		KCM_STATS_ADD(kcm->stats.rx_bytes, copied);
1138 		if (copied < rxm->full_len) {
1139 			if (sock->type == SOCK_DGRAM) {
1140 				/* Truncated message */
1141 				msg->msg_flags |= MSG_TRUNC;
1142 				goto msg_finished;
1143 			}
1144 			rxm->offset += copied;
1145 			rxm->full_len -= copied;
1146 		} else {
1147 msg_finished:
1148 			/* Finished with message */
1149 			msg->msg_flags |= MSG_EOR;
1150 			KCM_STATS_INCR(kcm->stats.rx_msgs);
1151 			skb_unlink(skb, &sk->sk_receive_queue);
1152 			kfree_skb(skb);
1153 		}
1154 	}
1155 
1156 out:
1157 	release_sock(sk);
1158 
1159 	return copied ? : err;
1160 }
1161 
1162 static ssize_t kcm_sock_splice(struct sock *sk,
1163 			       struct pipe_inode_info *pipe,
1164 			       struct splice_pipe_desc *spd)
1165 {
1166 	int ret;
1167 
1168 	release_sock(sk);
1169 	ret = splice_to_pipe(pipe, spd);
1170 	lock_sock(sk);
1171 
1172 	return ret;
1173 }
1174 
1175 static ssize_t kcm_splice_read(struct socket *sock, loff_t *ppos,
1176 			       struct pipe_inode_info *pipe, size_t len,
1177 			       unsigned int flags)
1178 {
1179 	struct sock *sk = sock->sk;
1180 	struct kcm_sock *kcm = kcm_sk(sk);
1181 	long timeo;
1182 	struct strp_rx_msg *rxm;
1183 	int err = 0;
1184 	ssize_t copied;
1185 	struct sk_buff *skb;
1186 
1187 	/* Only support splice for SOCKSEQPACKET */
1188 
1189 	timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1190 
1191 	lock_sock(sk);
1192 
1193 	skb = kcm_wait_data(sk, flags, timeo, &err);
1194 	if (!skb)
1195 		goto err_out;
1196 
1197 	/* Okay, have a message on the receive queue */
1198 
1199 	rxm = strp_rx_msg(skb);
1200 
1201 	if (len > rxm->full_len)
1202 		len = rxm->full_len;
1203 
1204 	copied = skb_splice_bits(skb, sk, rxm->offset, pipe, len, flags,
1205 				 kcm_sock_splice);
1206 	if (copied < 0) {
1207 		err = copied;
1208 		goto err_out;
1209 	}
1210 
1211 	KCM_STATS_ADD(kcm->stats.rx_bytes, copied);
1212 
1213 	rxm->offset += copied;
1214 	rxm->full_len -= copied;
1215 
1216 	/* We have no way to return MSG_EOR. If all the bytes have been
1217 	 * read we still leave the message in the receive socket buffer.
1218 	 * A subsequent recvmsg needs to be done to return MSG_EOR and
1219 	 * finish reading the message.
1220 	 */
1221 
1222 	release_sock(sk);
1223 
1224 	return copied;
1225 
1226 err_out:
1227 	release_sock(sk);
1228 
1229 	return err;
1230 }
1231 
1232 /* kcm sock lock held */
1233 static void kcm_recv_disable(struct kcm_sock *kcm)
1234 {
1235 	struct kcm_mux *mux = kcm->mux;
1236 
1237 	if (kcm->rx_disabled)
1238 		return;
1239 
1240 	spin_lock_bh(&mux->rx_lock);
1241 
1242 	kcm->rx_disabled = 1;
1243 
1244 	/* If a psock is reserved we'll do cleanup in unreserve */
1245 	if (!kcm->rx_psock) {
1246 		if (kcm->rx_wait) {
1247 			list_del(&kcm->wait_rx_list);
1248 			kcm->rx_wait = false;
1249 		}
1250 
1251 		requeue_rx_msgs(mux, &kcm->sk.sk_receive_queue);
1252 	}
1253 
1254 	spin_unlock_bh(&mux->rx_lock);
1255 }
1256 
1257 /* kcm sock lock held */
1258 static void kcm_recv_enable(struct kcm_sock *kcm)
1259 {
1260 	struct kcm_mux *mux = kcm->mux;
1261 
1262 	if (!kcm->rx_disabled)
1263 		return;
1264 
1265 	spin_lock_bh(&mux->rx_lock);
1266 
1267 	kcm->rx_disabled = 0;
1268 	kcm_rcv_ready(kcm);
1269 
1270 	spin_unlock_bh(&mux->rx_lock);
1271 }
1272 
1273 static int kcm_setsockopt(struct socket *sock, int level, int optname,
1274 			  char __user *optval, unsigned int optlen)
1275 {
1276 	struct kcm_sock *kcm = kcm_sk(sock->sk);
1277 	int val, valbool;
1278 	int err = 0;
1279 
1280 	if (level != SOL_KCM)
1281 		return -ENOPROTOOPT;
1282 
1283 	if (optlen < sizeof(int))
1284 		return -EINVAL;
1285 
1286 	if (get_user(val, (int __user *)optval))
1287 		return -EINVAL;
1288 
1289 	valbool = val ? 1 : 0;
1290 
1291 	switch (optname) {
1292 	case KCM_RECV_DISABLE:
1293 		lock_sock(&kcm->sk);
1294 		if (valbool)
1295 			kcm_recv_disable(kcm);
1296 		else
1297 			kcm_recv_enable(kcm);
1298 		release_sock(&kcm->sk);
1299 		break;
1300 	default:
1301 		err = -ENOPROTOOPT;
1302 	}
1303 
1304 	return err;
1305 }
1306 
1307 static int kcm_getsockopt(struct socket *sock, int level, int optname,
1308 			  char __user *optval, int __user *optlen)
1309 {
1310 	struct kcm_sock *kcm = kcm_sk(sock->sk);
1311 	int val, len;
1312 
1313 	if (level != SOL_KCM)
1314 		return -ENOPROTOOPT;
1315 
1316 	if (get_user(len, optlen))
1317 		return -EFAULT;
1318 
1319 	len = min_t(unsigned int, len, sizeof(int));
1320 	if (len < 0)
1321 		return -EINVAL;
1322 
1323 	switch (optname) {
1324 	case KCM_RECV_DISABLE:
1325 		val = kcm->rx_disabled;
1326 		break;
1327 	default:
1328 		return -ENOPROTOOPT;
1329 	}
1330 
1331 	if (put_user(len, optlen))
1332 		return -EFAULT;
1333 	if (copy_to_user(optval, &val, len))
1334 		return -EFAULT;
1335 	return 0;
1336 }
1337 
1338 static void init_kcm_sock(struct kcm_sock *kcm, struct kcm_mux *mux)
1339 {
1340 	struct kcm_sock *tkcm;
1341 	struct list_head *head;
1342 	int index = 0;
1343 
1344 	/* For SOCK_SEQPACKET sock type, datagram_poll checks the sk_state, so
1345 	 * we set sk_state, otherwise epoll_wait always returns right away with
1346 	 * POLLHUP
1347 	 */
1348 	kcm->sk.sk_state = TCP_ESTABLISHED;
1349 
1350 	/* Add to mux's kcm sockets list */
1351 	kcm->mux = mux;
1352 	spin_lock_bh(&mux->lock);
1353 
1354 	head = &mux->kcm_socks;
1355 	list_for_each_entry(tkcm, &mux->kcm_socks, kcm_sock_list) {
1356 		if (tkcm->index != index)
1357 			break;
1358 		head = &tkcm->kcm_sock_list;
1359 		index++;
1360 	}
1361 
1362 	list_add(&kcm->kcm_sock_list, head);
1363 	kcm->index = index;
1364 
1365 	mux->kcm_socks_cnt++;
1366 	spin_unlock_bh(&mux->lock);
1367 
1368 	INIT_WORK(&kcm->tx_work, kcm_tx_work);
1369 
1370 	spin_lock_bh(&mux->rx_lock);
1371 	kcm_rcv_ready(kcm);
1372 	spin_unlock_bh(&mux->rx_lock);
1373 }
1374 
1375 static int kcm_attach(struct socket *sock, struct socket *csock,
1376 		      struct bpf_prog *prog)
1377 {
1378 	struct kcm_sock *kcm = kcm_sk(sock->sk);
1379 	struct kcm_mux *mux = kcm->mux;
1380 	struct sock *csk;
1381 	struct kcm_psock *psock = NULL, *tpsock;
1382 	struct list_head *head;
1383 	int index = 0;
1384 	struct strp_callbacks cb;
1385 	int err;
1386 
1387 	csk = csock->sk;
1388 	if (!csk)
1389 		return -EINVAL;
1390 
1391 	psock = kmem_cache_zalloc(kcm_psockp, GFP_KERNEL);
1392 	if (!psock)
1393 		return -ENOMEM;
1394 
1395 	psock->mux = mux;
1396 	psock->sk = csk;
1397 	psock->bpf_prog = prog;
1398 
1399 	cb.rcv_msg = kcm_rcv_strparser;
1400 	cb.abort_parser = NULL;
1401 	cb.parse_msg = kcm_parse_func_strparser;
1402 	cb.read_sock_done = kcm_read_sock_done;
1403 
1404 	err = strp_init(&psock->strp, csk, &cb);
1405 	if (err) {
1406 		kmem_cache_free(kcm_psockp, psock);
1407 		return err;
1408 	}
1409 
1410 	sock_hold(csk);
1411 
1412 	write_lock_bh(&csk->sk_callback_lock);
1413 	psock->save_data_ready = csk->sk_data_ready;
1414 	psock->save_write_space = csk->sk_write_space;
1415 	psock->save_state_change = csk->sk_state_change;
1416 	csk->sk_user_data = psock;
1417 	csk->sk_data_ready = psock_data_ready;
1418 	csk->sk_write_space = psock_write_space;
1419 	csk->sk_state_change = psock_state_change;
1420 	write_unlock_bh(&csk->sk_callback_lock);
1421 
1422 	/* Finished initialization, now add the psock to the MUX. */
1423 	spin_lock_bh(&mux->lock);
1424 	head = &mux->psocks;
1425 	list_for_each_entry(tpsock, &mux->psocks, psock_list) {
1426 		if (tpsock->index != index)
1427 			break;
1428 		head = &tpsock->psock_list;
1429 		index++;
1430 	}
1431 
1432 	list_add(&psock->psock_list, head);
1433 	psock->index = index;
1434 
1435 	KCM_STATS_INCR(mux->stats.psock_attach);
1436 	mux->psocks_cnt++;
1437 	psock_now_avail(psock);
1438 	spin_unlock_bh(&mux->lock);
1439 
1440 	/* Schedule RX work in case there are already bytes queued */
1441 	strp_check_rcv(&psock->strp);
1442 
1443 	return 0;
1444 }
1445 
1446 static int kcm_attach_ioctl(struct socket *sock, struct kcm_attach *info)
1447 {
1448 	struct socket *csock;
1449 	struct bpf_prog *prog;
1450 	int err;
1451 
1452 	csock = sockfd_lookup(info->fd, &err);
1453 	if (!csock)
1454 		return -ENOENT;
1455 
1456 	prog = bpf_prog_get_type(info->bpf_fd, BPF_PROG_TYPE_SOCKET_FILTER);
1457 	if (IS_ERR(prog)) {
1458 		err = PTR_ERR(prog);
1459 		goto out;
1460 	}
1461 
1462 	err = kcm_attach(sock, csock, prog);
1463 	if (err) {
1464 		bpf_prog_put(prog);
1465 		goto out;
1466 	}
1467 
1468 	/* Keep reference on file also */
1469 
1470 	return 0;
1471 out:
1472 	fput(csock->file);
1473 	return err;
1474 }
1475 
1476 static void kcm_unattach(struct kcm_psock *psock)
1477 {
1478 	struct sock *csk = psock->sk;
1479 	struct kcm_mux *mux = psock->mux;
1480 
1481 	lock_sock(csk);
1482 
1483 	/* Stop getting callbacks from TCP socket. After this there should
1484 	 * be no way to reserve a kcm for this psock.
1485 	 */
1486 	write_lock_bh(&csk->sk_callback_lock);
1487 	csk->sk_user_data = NULL;
1488 	csk->sk_data_ready = psock->save_data_ready;
1489 	csk->sk_write_space = psock->save_write_space;
1490 	csk->sk_state_change = psock->save_state_change;
1491 	strp_stop(&psock->strp);
1492 
1493 	if (WARN_ON(psock->rx_kcm)) {
1494 		write_unlock_bh(&csk->sk_callback_lock);
1495 		return;
1496 	}
1497 
1498 	spin_lock_bh(&mux->rx_lock);
1499 
1500 	/* Stop receiver activities. After this point psock should not be
1501 	 * able to get onto ready list either through callbacks or work.
1502 	 */
1503 	if (psock->ready_rx_msg) {
1504 		list_del(&psock->psock_ready_list);
1505 		kfree_skb(psock->ready_rx_msg);
1506 		psock->ready_rx_msg = NULL;
1507 		KCM_STATS_INCR(mux->stats.rx_ready_drops);
1508 	}
1509 
1510 	spin_unlock_bh(&mux->rx_lock);
1511 
1512 	write_unlock_bh(&csk->sk_callback_lock);
1513 
1514 	/* Call strp_done without sock lock */
1515 	release_sock(csk);
1516 	strp_done(&psock->strp);
1517 	lock_sock(csk);
1518 
1519 	bpf_prog_put(psock->bpf_prog);
1520 
1521 	spin_lock_bh(&mux->lock);
1522 
1523 	aggregate_psock_stats(&psock->stats, &mux->aggregate_psock_stats);
1524 	save_strp_stats(&psock->strp, &mux->aggregate_strp_stats);
1525 
1526 	KCM_STATS_INCR(mux->stats.psock_unattach);
1527 
1528 	if (psock->tx_kcm) {
1529 		/* psock was reserved.  Just mark it finished and we will clean
1530 		 * up in the kcm paths, we need kcm lock which can not be
1531 		 * acquired here.
1532 		 */
1533 		KCM_STATS_INCR(mux->stats.psock_unattach_rsvd);
1534 		spin_unlock_bh(&mux->lock);
1535 
1536 		/* We are unattaching a socket that is reserved. Abort the
1537 		 * socket since we may be out of sync in sending on it. We need
1538 		 * to do this without the mux lock.
1539 		 */
1540 		kcm_abort_tx_psock(psock, EPIPE, false);
1541 
1542 		spin_lock_bh(&mux->lock);
1543 		if (!psock->tx_kcm) {
1544 			/* psock now unreserved in window mux was unlocked */
1545 			goto no_reserved;
1546 		}
1547 		psock->done = 1;
1548 
1549 		/* Commit done before queuing work to process it */
1550 		smp_mb();
1551 
1552 		/* Queue tx work to make sure psock->done is handled */
1553 		queue_work(kcm_wq, &psock->tx_kcm->tx_work);
1554 		spin_unlock_bh(&mux->lock);
1555 	} else {
1556 no_reserved:
1557 		if (!psock->tx_stopped)
1558 			list_del(&psock->psock_avail_list);
1559 		list_del(&psock->psock_list);
1560 		mux->psocks_cnt--;
1561 		spin_unlock_bh(&mux->lock);
1562 
1563 		sock_put(csk);
1564 		fput(csk->sk_socket->file);
1565 		kmem_cache_free(kcm_psockp, psock);
1566 	}
1567 
1568 	release_sock(csk);
1569 }
1570 
1571 static int kcm_unattach_ioctl(struct socket *sock, struct kcm_unattach *info)
1572 {
1573 	struct kcm_sock *kcm = kcm_sk(sock->sk);
1574 	struct kcm_mux *mux = kcm->mux;
1575 	struct kcm_psock *psock;
1576 	struct socket *csock;
1577 	struct sock *csk;
1578 	int err;
1579 
1580 	csock = sockfd_lookup(info->fd, &err);
1581 	if (!csock)
1582 		return -ENOENT;
1583 
1584 	csk = csock->sk;
1585 	if (!csk) {
1586 		err = -EINVAL;
1587 		goto out;
1588 	}
1589 
1590 	err = -ENOENT;
1591 
1592 	spin_lock_bh(&mux->lock);
1593 
1594 	list_for_each_entry(psock, &mux->psocks, psock_list) {
1595 		if (psock->sk != csk)
1596 			continue;
1597 
1598 		/* Found the matching psock */
1599 
1600 		if (psock->unattaching || WARN_ON(psock->done)) {
1601 			err = -EALREADY;
1602 			break;
1603 		}
1604 
1605 		psock->unattaching = 1;
1606 
1607 		spin_unlock_bh(&mux->lock);
1608 
1609 		/* Lower socket lock should already be held */
1610 		kcm_unattach(psock);
1611 
1612 		err = 0;
1613 		goto out;
1614 	}
1615 
1616 	spin_unlock_bh(&mux->lock);
1617 
1618 out:
1619 	fput(csock->file);
1620 	return err;
1621 }
1622 
1623 static struct proto kcm_proto = {
1624 	.name	= "KCM",
1625 	.owner	= THIS_MODULE,
1626 	.obj_size = sizeof(struct kcm_sock),
1627 };
1628 
1629 /* Clone a kcm socket. */
1630 static int kcm_clone(struct socket *osock, struct kcm_clone *info,
1631 		     struct socket **newsockp)
1632 {
1633 	struct socket *newsock;
1634 	struct sock *newsk;
1635 	struct file *newfile;
1636 	int err, newfd;
1637 
1638 	err = -ENFILE;
1639 	newsock = sock_alloc();
1640 	if (!newsock)
1641 		goto out;
1642 
1643 	newsock->type = osock->type;
1644 	newsock->ops = osock->ops;
1645 
1646 	__module_get(newsock->ops->owner);
1647 
1648 	newfd = get_unused_fd_flags(0);
1649 	if (unlikely(newfd < 0)) {
1650 		err = newfd;
1651 		goto out_fd_fail;
1652 	}
1653 
1654 	newfile = sock_alloc_file(newsock, 0, osock->sk->sk_prot_creator->name);
1655 	if (unlikely(IS_ERR(newfile))) {
1656 		err = PTR_ERR(newfile);
1657 		goto out_sock_alloc_fail;
1658 	}
1659 
1660 	newsk = sk_alloc(sock_net(osock->sk), PF_KCM, GFP_KERNEL,
1661 			 &kcm_proto, true);
1662 	if (!newsk) {
1663 		err = -ENOMEM;
1664 		goto out_sk_alloc_fail;
1665 	}
1666 
1667 	sock_init_data(newsock, newsk);
1668 	init_kcm_sock(kcm_sk(newsk), kcm_sk(osock->sk)->mux);
1669 
1670 	fd_install(newfd, newfile);
1671 	*newsockp = newsock;
1672 	info->fd = newfd;
1673 
1674 	return 0;
1675 
1676 out_sk_alloc_fail:
1677 	fput(newfile);
1678 out_sock_alloc_fail:
1679 	put_unused_fd(newfd);
1680 out_fd_fail:
1681 	sock_release(newsock);
1682 out:
1683 	return err;
1684 }
1685 
1686 static int kcm_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
1687 {
1688 	int err;
1689 
1690 	switch (cmd) {
1691 	case SIOCKCMATTACH: {
1692 		struct kcm_attach info;
1693 
1694 		if (copy_from_user(&info, (void __user *)arg, sizeof(info)))
1695 			err = -EFAULT;
1696 
1697 		err = kcm_attach_ioctl(sock, &info);
1698 
1699 		break;
1700 	}
1701 	case SIOCKCMUNATTACH: {
1702 		struct kcm_unattach info;
1703 
1704 		if (copy_from_user(&info, (void __user *)arg, sizeof(info)))
1705 			err = -EFAULT;
1706 
1707 		err = kcm_unattach_ioctl(sock, &info);
1708 
1709 		break;
1710 	}
1711 	case SIOCKCMCLONE: {
1712 		struct kcm_clone info;
1713 		struct socket *newsock = NULL;
1714 
1715 		if (copy_from_user(&info, (void __user *)arg, sizeof(info)))
1716 			err = -EFAULT;
1717 
1718 		err = kcm_clone(sock, &info, &newsock);
1719 
1720 		if (!err) {
1721 			if (copy_to_user((void __user *)arg, &info,
1722 					 sizeof(info))) {
1723 				err = -EFAULT;
1724 				sock_release(newsock);
1725 			}
1726 		}
1727 
1728 		break;
1729 	}
1730 	default:
1731 		err = -ENOIOCTLCMD;
1732 		break;
1733 	}
1734 
1735 	return err;
1736 }
1737 
1738 static void free_mux(struct rcu_head *rcu)
1739 {
1740 	struct kcm_mux *mux = container_of(rcu,
1741 	    struct kcm_mux, rcu);
1742 
1743 	kmem_cache_free(kcm_muxp, mux);
1744 }
1745 
1746 static void release_mux(struct kcm_mux *mux)
1747 {
1748 	struct kcm_net *knet = mux->knet;
1749 	struct kcm_psock *psock, *tmp_psock;
1750 
1751 	/* Release psocks */
1752 	list_for_each_entry_safe(psock, tmp_psock,
1753 				 &mux->psocks, psock_list) {
1754 		if (!WARN_ON(psock->unattaching))
1755 			kcm_unattach(psock);
1756 	}
1757 
1758 	if (WARN_ON(mux->psocks_cnt))
1759 		return;
1760 
1761 	__skb_queue_purge(&mux->rx_hold_queue);
1762 
1763 	mutex_lock(&knet->mutex);
1764 	aggregate_mux_stats(&mux->stats, &knet->aggregate_mux_stats);
1765 	aggregate_psock_stats(&mux->aggregate_psock_stats,
1766 			      &knet->aggregate_psock_stats);
1767 	aggregate_strp_stats(&mux->aggregate_strp_stats,
1768 			     &knet->aggregate_strp_stats);
1769 	list_del_rcu(&mux->kcm_mux_list);
1770 	knet->count--;
1771 	mutex_unlock(&knet->mutex);
1772 
1773 	call_rcu(&mux->rcu, free_mux);
1774 }
1775 
1776 static void kcm_done(struct kcm_sock *kcm)
1777 {
1778 	struct kcm_mux *mux = kcm->mux;
1779 	struct sock *sk = &kcm->sk;
1780 	int socks_cnt;
1781 
1782 	spin_lock_bh(&mux->rx_lock);
1783 	if (kcm->rx_psock) {
1784 		/* Cleanup in unreserve_rx_kcm */
1785 		WARN_ON(kcm->done);
1786 		kcm->rx_disabled = 1;
1787 		kcm->done = 1;
1788 		spin_unlock_bh(&mux->rx_lock);
1789 		return;
1790 	}
1791 
1792 	if (kcm->rx_wait) {
1793 		list_del(&kcm->wait_rx_list);
1794 		kcm->rx_wait = false;
1795 	}
1796 	/* Move any pending receive messages to other kcm sockets */
1797 	requeue_rx_msgs(mux, &sk->sk_receive_queue);
1798 
1799 	spin_unlock_bh(&mux->rx_lock);
1800 
1801 	if (WARN_ON(sk_rmem_alloc_get(sk)))
1802 		return;
1803 
1804 	/* Detach from MUX */
1805 	spin_lock_bh(&mux->lock);
1806 
1807 	list_del(&kcm->kcm_sock_list);
1808 	mux->kcm_socks_cnt--;
1809 	socks_cnt = mux->kcm_socks_cnt;
1810 
1811 	spin_unlock_bh(&mux->lock);
1812 
1813 	if (!socks_cnt) {
1814 		/* We are done with the mux now. */
1815 		release_mux(mux);
1816 	}
1817 
1818 	WARN_ON(kcm->rx_wait);
1819 
1820 	sock_put(&kcm->sk);
1821 }
1822 
1823 /* Called by kcm_release to close a KCM socket.
1824  * If this is the last KCM socket on the MUX, destroy the MUX.
1825  */
1826 static int kcm_release(struct socket *sock)
1827 {
1828 	struct sock *sk = sock->sk;
1829 	struct kcm_sock *kcm;
1830 	struct kcm_mux *mux;
1831 	struct kcm_psock *psock;
1832 
1833 	if (!sk)
1834 		return 0;
1835 
1836 	kcm = kcm_sk(sk);
1837 	mux = kcm->mux;
1838 
1839 	sock_orphan(sk);
1840 	kfree_skb(kcm->seq_skb);
1841 
1842 	lock_sock(sk);
1843 	/* Purge queue under lock to avoid race condition with tx_work trying
1844 	 * to act when queue is nonempty. If tx_work runs after this point
1845 	 * it will just return.
1846 	 */
1847 	__skb_queue_purge(&sk->sk_write_queue);
1848 
1849 	/* Set tx_stopped. This is checked when psock is bound to a kcm and we
1850 	 * get a writespace callback. This prevents further work being queued
1851 	 * from the callback (unbinding the psock occurs after canceling work.
1852 	 */
1853 	kcm->tx_stopped = 1;
1854 
1855 	release_sock(sk);
1856 
1857 	spin_lock_bh(&mux->lock);
1858 	if (kcm->tx_wait) {
1859 		/* Take of tx_wait list, after this point there should be no way
1860 		 * that a psock will be assigned to this kcm.
1861 		 */
1862 		list_del(&kcm->wait_psock_list);
1863 		kcm->tx_wait = false;
1864 	}
1865 	spin_unlock_bh(&mux->lock);
1866 
1867 	/* Cancel work. After this point there should be no outside references
1868 	 * to the kcm socket.
1869 	 */
1870 	cancel_work_sync(&kcm->tx_work);
1871 
1872 	lock_sock(sk);
1873 	psock = kcm->tx_psock;
1874 	if (psock) {
1875 		/* A psock was reserved, so we need to kill it since it
1876 		 * may already have some bytes queued from a message. We
1877 		 * need to do this after removing kcm from tx_wait list.
1878 		 */
1879 		kcm_abort_tx_psock(psock, EPIPE, false);
1880 		unreserve_psock(kcm);
1881 	}
1882 	release_sock(sk);
1883 
1884 	WARN_ON(kcm->tx_wait);
1885 	WARN_ON(kcm->tx_psock);
1886 
1887 	sock->sk = NULL;
1888 
1889 	kcm_done(kcm);
1890 
1891 	return 0;
1892 }
1893 
1894 static const struct proto_ops kcm_dgram_ops = {
1895 	.family =	PF_KCM,
1896 	.owner =	THIS_MODULE,
1897 	.release =	kcm_release,
1898 	.bind =		sock_no_bind,
1899 	.connect =	sock_no_connect,
1900 	.socketpair =	sock_no_socketpair,
1901 	.accept =	sock_no_accept,
1902 	.getname =	sock_no_getname,
1903 	.poll =		datagram_poll,
1904 	.ioctl =	kcm_ioctl,
1905 	.listen =	sock_no_listen,
1906 	.shutdown =	sock_no_shutdown,
1907 	.setsockopt =	kcm_setsockopt,
1908 	.getsockopt =	kcm_getsockopt,
1909 	.sendmsg =	kcm_sendmsg,
1910 	.recvmsg =	kcm_recvmsg,
1911 	.mmap =		sock_no_mmap,
1912 	.sendpage =	kcm_sendpage,
1913 };
1914 
1915 static const struct proto_ops kcm_seqpacket_ops = {
1916 	.family =	PF_KCM,
1917 	.owner =	THIS_MODULE,
1918 	.release =	kcm_release,
1919 	.bind =		sock_no_bind,
1920 	.connect =	sock_no_connect,
1921 	.socketpair =	sock_no_socketpair,
1922 	.accept =	sock_no_accept,
1923 	.getname =	sock_no_getname,
1924 	.poll =		datagram_poll,
1925 	.ioctl =	kcm_ioctl,
1926 	.listen =	sock_no_listen,
1927 	.shutdown =	sock_no_shutdown,
1928 	.setsockopt =	kcm_setsockopt,
1929 	.getsockopt =	kcm_getsockopt,
1930 	.sendmsg =	kcm_sendmsg,
1931 	.recvmsg =	kcm_recvmsg,
1932 	.mmap =		sock_no_mmap,
1933 	.sendpage =	kcm_sendpage,
1934 	.splice_read =	kcm_splice_read,
1935 };
1936 
1937 /* Create proto operation for kcm sockets */
1938 static int kcm_create(struct net *net, struct socket *sock,
1939 		      int protocol, int kern)
1940 {
1941 	struct kcm_net *knet = net_generic(net, kcm_net_id);
1942 	struct sock *sk;
1943 	struct kcm_mux *mux;
1944 
1945 	switch (sock->type) {
1946 	case SOCK_DGRAM:
1947 		sock->ops = &kcm_dgram_ops;
1948 		break;
1949 	case SOCK_SEQPACKET:
1950 		sock->ops = &kcm_seqpacket_ops;
1951 		break;
1952 	default:
1953 		return -ESOCKTNOSUPPORT;
1954 	}
1955 
1956 	if (protocol != KCMPROTO_CONNECTED)
1957 		return -EPROTONOSUPPORT;
1958 
1959 	sk = sk_alloc(net, PF_KCM, GFP_KERNEL, &kcm_proto, kern);
1960 	if (!sk)
1961 		return -ENOMEM;
1962 
1963 	/* Allocate a kcm mux, shared between KCM sockets */
1964 	mux = kmem_cache_zalloc(kcm_muxp, GFP_KERNEL);
1965 	if (!mux) {
1966 		sk_free(sk);
1967 		return -ENOMEM;
1968 	}
1969 
1970 	spin_lock_init(&mux->lock);
1971 	spin_lock_init(&mux->rx_lock);
1972 	INIT_LIST_HEAD(&mux->kcm_socks);
1973 	INIT_LIST_HEAD(&mux->kcm_rx_waiters);
1974 	INIT_LIST_HEAD(&mux->kcm_tx_waiters);
1975 
1976 	INIT_LIST_HEAD(&mux->psocks);
1977 	INIT_LIST_HEAD(&mux->psocks_ready);
1978 	INIT_LIST_HEAD(&mux->psocks_avail);
1979 
1980 	mux->knet = knet;
1981 
1982 	/* Add new MUX to list */
1983 	mutex_lock(&knet->mutex);
1984 	list_add_rcu(&mux->kcm_mux_list, &knet->mux_list);
1985 	knet->count++;
1986 	mutex_unlock(&knet->mutex);
1987 
1988 	skb_queue_head_init(&mux->rx_hold_queue);
1989 
1990 	/* Init KCM socket */
1991 	sock_init_data(sock, sk);
1992 	init_kcm_sock(kcm_sk(sk), mux);
1993 
1994 	return 0;
1995 }
1996 
1997 static struct net_proto_family kcm_family_ops = {
1998 	.family = PF_KCM,
1999 	.create = kcm_create,
2000 	.owner  = THIS_MODULE,
2001 };
2002 
2003 static __net_init int kcm_init_net(struct net *net)
2004 {
2005 	struct kcm_net *knet = net_generic(net, kcm_net_id);
2006 
2007 	INIT_LIST_HEAD_RCU(&knet->mux_list);
2008 	mutex_init(&knet->mutex);
2009 
2010 	return 0;
2011 }
2012 
2013 static __net_exit void kcm_exit_net(struct net *net)
2014 {
2015 	struct kcm_net *knet = net_generic(net, kcm_net_id);
2016 
2017 	/* All KCM sockets should be closed at this point, which should mean
2018 	 * that all multiplexors and psocks have been destroyed.
2019 	 */
2020 	WARN_ON(!list_empty(&knet->mux_list));
2021 }
2022 
2023 static struct pernet_operations kcm_net_ops = {
2024 	.init = kcm_init_net,
2025 	.exit = kcm_exit_net,
2026 	.id   = &kcm_net_id,
2027 	.size = sizeof(struct kcm_net),
2028 };
2029 
2030 static int __init kcm_init(void)
2031 {
2032 	int err = -ENOMEM;
2033 
2034 	kcm_muxp = kmem_cache_create("kcm_mux_cache",
2035 				     sizeof(struct kcm_mux), 0,
2036 				     SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
2037 	if (!kcm_muxp)
2038 		goto fail;
2039 
2040 	kcm_psockp = kmem_cache_create("kcm_psock_cache",
2041 				       sizeof(struct kcm_psock), 0,
2042 					SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
2043 	if (!kcm_psockp)
2044 		goto fail;
2045 
2046 	kcm_wq = create_singlethread_workqueue("kkcmd");
2047 	if (!kcm_wq)
2048 		goto fail;
2049 
2050 	err = proto_register(&kcm_proto, 1);
2051 	if (err)
2052 		goto fail;
2053 
2054 	err = sock_register(&kcm_family_ops);
2055 	if (err)
2056 		goto sock_register_fail;
2057 
2058 	err = register_pernet_device(&kcm_net_ops);
2059 	if (err)
2060 		goto net_ops_fail;
2061 
2062 	err = kcm_proc_init();
2063 	if (err)
2064 		goto proc_init_fail;
2065 
2066 	return 0;
2067 
2068 proc_init_fail:
2069 	unregister_pernet_device(&kcm_net_ops);
2070 
2071 net_ops_fail:
2072 	sock_unregister(PF_KCM);
2073 
2074 sock_register_fail:
2075 	proto_unregister(&kcm_proto);
2076 
2077 fail:
2078 	kmem_cache_destroy(kcm_muxp);
2079 	kmem_cache_destroy(kcm_psockp);
2080 
2081 	if (kcm_wq)
2082 		destroy_workqueue(kcm_wq);
2083 
2084 	return err;
2085 }
2086 
2087 static void __exit kcm_exit(void)
2088 {
2089 	kcm_proc_exit();
2090 	unregister_pernet_device(&kcm_net_ops);
2091 	sock_unregister(PF_KCM);
2092 	proto_unregister(&kcm_proto);
2093 	destroy_workqueue(kcm_wq);
2094 
2095 	kmem_cache_destroy(kcm_muxp);
2096 	kmem_cache_destroy(kcm_psockp);
2097 }
2098 
2099 module_init(kcm_init);
2100 module_exit(kcm_exit);
2101 
2102 MODULE_LICENSE("GPL");
2103 MODULE_ALIAS_NETPROTO(PF_KCM);
2104 
2105