xref: /kernel/linux/linux-5.10/net/dccp/proto.c (revision 8c2ecf20)
1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 *  net/dccp/proto.c
4 *
5 *  An implementation of the DCCP protocol
6 *  Arnaldo Carvalho de Melo <acme@conectiva.com.br>
7 */
8
9#include <linux/dccp.h>
10#include <linux/module.h>
11#include <linux/types.h>
12#include <linux/sched.h>
13#include <linux/kernel.h>
14#include <linux/skbuff.h>
15#include <linux/netdevice.h>
16#include <linux/in.h>
17#include <linux/if_arp.h>
18#include <linux/init.h>
19#include <linux/random.h>
20#include <linux/slab.h>
21#include <net/checksum.h>
22
23#include <net/inet_sock.h>
24#include <net/inet_common.h>
25#include <net/sock.h>
26#include <net/xfrm.h>
27
28#include <asm/ioctls.h>
29#include <linux/spinlock.h>
30#include <linux/timer.h>
31#include <linux/delay.h>
32#include <linux/poll.h>
33
34#include "ccid.h"
35#include "dccp.h"
36#include "feat.h"
37
38#define CREATE_TRACE_POINTS
39#include "trace.h"
40
41DEFINE_SNMP_STAT(struct dccp_mib, dccp_statistics) __read_mostly;
42
43EXPORT_SYMBOL_GPL(dccp_statistics);
44
45DEFINE_PER_CPU(unsigned int, dccp_orphan_count);
46EXPORT_PER_CPU_SYMBOL_GPL(dccp_orphan_count);
47
48struct inet_hashinfo dccp_hashinfo;
49EXPORT_SYMBOL_GPL(dccp_hashinfo);
50
51/* the maximum queue length for tx in packets. 0 is no limit */
52int sysctl_dccp_tx_qlen __read_mostly = 5;
53
54#ifdef CONFIG_IP_DCCP_DEBUG
55static const char *dccp_state_name(const int state)
56{
57	static const char *const dccp_state_names[] = {
58	[DCCP_OPEN]		= "OPEN",
59	[DCCP_REQUESTING]	= "REQUESTING",
60	[DCCP_PARTOPEN]		= "PARTOPEN",
61	[DCCP_LISTEN]		= "LISTEN",
62	[DCCP_RESPOND]		= "RESPOND",
63	[DCCP_CLOSING]		= "CLOSING",
64	[DCCP_ACTIVE_CLOSEREQ]	= "CLOSEREQ",
65	[DCCP_PASSIVE_CLOSE]	= "PASSIVE_CLOSE",
66	[DCCP_PASSIVE_CLOSEREQ]	= "PASSIVE_CLOSEREQ",
67	[DCCP_TIME_WAIT]	= "TIME_WAIT",
68	[DCCP_CLOSED]		= "CLOSED",
69	};
70
71	if (state >= DCCP_MAX_STATES)
72		return "INVALID STATE!";
73	else
74		return dccp_state_names[state];
75}
76#endif
77
78void dccp_set_state(struct sock *sk, const int state)
79{
80	const int oldstate = sk->sk_state;
81
82	dccp_pr_debug("%s(%p)  %s  -->  %s\n", dccp_role(sk), sk,
83		      dccp_state_name(oldstate), dccp_state_name(state));
84	WARN_ON(state == oldstate);
85
86	switch (state) {
87	case DCCP_OPEN:
88		if (oldstate != DCCP_OPEN)
89			DCCP_INC_STATS(DCCP_MIB_CURRESTAB);
90		/* Client retransmits all Confirm options until entering OPEN */
91		if (oldstate == DCCP_PARTOPEN)
92			dccp_feat_list_purge(&dccp_sk(sk)->dccps_featneg);
93		break;
94
95	case DCCP_CLOSED:
96		if (oldstate == DCCP_OPEN || oldstate == DCCP_ACTIVE_CLOSEREQ ||
97		    oldstate == DCCP_CLOSING)
98			DCCP_INC_STATS(DCCP_MIB_ESTABRESETS);
99
100		sk->sk_prot->unhash(sk);
101		if (inet_csk(sk)->icsk_bind_hash != NULL &&
102		    !(sk->sk_userlocks & SOCK_BINDPORT_LOCK))
103			inet_put_port(sk);
104		fallthrough;
105	default:
106		if (oldstate == DCCP_OPEN)
107			DCCP_DEC_STATS(DCCP_MIB_CURRESTAB);
108	}
109
110	/* Change state AFTER socket is unhashed to avoid closed
111	 * socket sitting in hash tables.
112	 */
113	inet_sk_set_state(sk, state);
114}
115
116EXPORT_SYMBOL_GPL(dccp_set_state);
117
118static void dccp_finish_passive_close(struct sock *sk)
119{
120	switch (sk->sk_state) {
121	case DCCP_PASSIVE_CLOSE:
122		/* Node (client or server) has received Close packet. */
123		dccp_send_reset(sk, DCCP_RESET_CODE_CLOSED);
124		dccp_set_state(sk, DCCP_CLOSED);
125		break;
126	case DCCP_PASSIVE_CLOSEREQ:
127		/*
128		 * Client received CloseReq. We set the `active' flag so that
129		 * dccp_send_close() retransmits the Close as per RFC 4340, 8.3.
130		 */
131		dccp_send_close(sk, 1);
132		dccp_set_state(sk, DCCP_CLOSING);
133	}
134}
135
136void dccp_done(struct sock *sk)
137{
138	dccp_set_state(sk, DCCP_CLOSED);
139	dccp_clear_xmit_timers(sk);
140
141	sk->sk_shutdown = SHUTDOWN_MASK;
142
143	if (!sock_flag(sk, SOCK_DEAD))
144		sk->sk_state_change(sk);
145	else
146		inet_csk_destroy_sock(sk);
147}
148
149EXPORT_SYMBOL_GPL(dccp_done);
150
151const char *dccp_packet_name(const int type)
152{
153	static const char *const dccp_packet_names[] = {
154		[DCCP_PKT_REQUEST]  = "REQUEST",
155		[DCCP_PKT_RESPONSE] = "RESPONSE",
156		[DCCP_PKT_DATA]	    = "DATA",
157		[DCCP_PKT_ACK]	    = "ACK",
158		[DCCP_PKT_DATAACK]  = "DATAACK",
159		[DCCP_PKT_CLOSEREQ] = "CLOSEREQ",
160		[DCCP_PKT_CLOSE]    = "CLOSE",
161		[DCCP_PKT_RESET]    = "RESET",
162		[DCCP_PKT_SYNC]	    = "SYNC",
163		[DCCP_PKT_SYNCACK]  = "SYNCACK",
164	};
165
166	if (type >= DCCP_NR_PKT_TYPES)
167		return "INVALID";
168	else
169		return dccp_packet_names[type];
170}
171
172EXPORT_SYMBOL_GPL(dccp_packet_name);
173
174void dccp_destruct_common(struct sock *sk)
175{
176	struct dccp_sock *dp = dccp_sk(sk);
177
178	ccid_hc_tx_delete(dp->dccps_hc_tx_ccid, sk);
179	dp->dccps_hc_tx_ccid = NULL;
180}
181EXPORT_SYMBOL_GPL(dccp_destruct_common);
182
183static void dccp_sk_destruct(struct sock *sk)
184{
185	dccp_destruct_common(sk);
186	inet_sock_destruct(sk);
187}
188
189int dccp_init_sock(struct sock *sk, const __u8 ctl_sock_initialized)
190{
191	struct dccp_sock *dp = dccp_sk(sk);
192	struct inet_connection_sock *icsk = inet_csk(sk);
193
194	icsk->icsk_rto		= DCCP_TIMEOUT_INIT;
195	icsk->icsk_syn_retries	= sysctl_dccp_request_retries;
196	sk->sk_state		= DCCP_CLOSED;
197	sk->sk_write_space	= dccp_write_space;
198	sk->sk_destruct		= dccp_sk_destruct;
199	icsk->icsk_sync_mss	= dccp_sync_mss;
200	dp->dccps_mss_cache	= 536;
201	dp->dccps_rate_last	= jiffies;
202	dp->dccps_role		= DCCP_ROLE_UNDEFINED;
203	dp->dccps_service	= DCCP_SERVICE_CODE_IS_ABSENT;
204	dp->dccps_tx_qlen	= sysctl_dccp_tx_qlen;
205
206	dccp_init_xmit_timers(sk);
207
208	INIT_LIST_HEAD(&dp->dccps_featneg);
209	/* control socket doesn't need feat nego */
210	if (likely(ctl_sock_initialized))
211		return dccp_feat_init(sk);
212	return 0;
213}
214
215EXPORT_SYMBOL_GPL(dccp_init_sock);
216
217void dccp_destroy_sock(struct sock *sk)
218{
219	struct dccp_sock *dp = dccp_sk(sk);
220
221	__skb_queue_purge(&sk->sk_write_queue);
222	if (sk->sk_send_head != NULL) {
223		kfree_skb(sk->sk_send_head);
224		sk->sk_send_head = NULL;
225	}
226
227	/* Clean up a referenced DCCP bind bucket. */
228	if (inet_csk(sk)->icsk_bind_hash != NULL)
229		inet_put_port(sk);
230
231	kfree(dp->dccps_service_list);
232	dp->dccps_service_list = NULL;
233
234	if (dp->dccps_hc_rx_ackvec != NULL) {
235		dccp_ackvec_free(dp->dccps_hc_rx_ackvec);
236		dp->dccps_hc_rx_ackvec = NULL;
237	}
238	ccid_hc_rx_delete(dp->dccps_hc_rx_ccid, sk);
239	dp->dccps_hc_rx_ccid = NULL;
240
241	/* clean up feature negotiation state */
242	dccp_feat_list_purge(&dp->dccps_featneg);
243}
244
245EXPORT_SYMBOL_GPL(dccp_destroy_sock);
246
247static inline int dccp_listen_start(struct sock *sk, int backlog)
248{
249	struct dccp_sock *dp = dccp_sk(sk);
250
251	dp->dccps_role = DCCP_ROLE_LISTEN;
252	/* do not start to listen if feature negotiation setup fails */
253	if (dccp_feat_finalise_settings(dp))
254		return -EPROTO;
255	return inet_csk_listen_start(sk, backlog);
256}
257
258static inline int dccp_need_reset(int state)
259{
260	return state != DCCP_CLOSED && state != DCCP_LISTEN &&
261	       state != DCCP_REQUESTING;
262}
263
264int dccp_disconnect(struct sock *sk, int flags)
265{
266	struct inet_connection_sock *icsk = inet_csk(sk);
267	struct inet_sock *inet = inet_sk(sk);
268	struct dccp_sock *dp = dccp_sk(sk);
269	const int old_state = sk->sk_state;
270
271	if (old_state != DCCP_CLOSED)
272		dccp_set_state(sk, DCCP_CLOSED);
273
274	/*
275	 * This corresponds to the ABORT function of RFC793, sec. 3.8
276	 * TCP uses a RST segment, DCCP a Reset packet with Code 2, "Aborted".
277	 */
278	if (old_state == DCCP_LISTEN) {
279		inet_csk_listen_stop(sk);
280	} else if (dccp_need_reset(old_state)) {
281		dccp_send_reset(sk, DCCP_RESET_CODE_ABORTED);
282		sk->sk_err = ECONNRESET;
283	} else if (old_state == DCCP_REQUESTING)
284		sk->sk_err = ECONNRESET;
285
286	dccp_clear_xmit_timers(sk);
287	ccid_hc_rx_delete(dp->dccps_hc_rx_ccid, sk);
288	dp->dccps_hc_rx_ccid = NULL;
289
290	__skb_queue_purge(&sk->sk_receive_queue);
291	__skb_queue_purge(&sk->sk_write_queue);
292	if (sk->sk_send_head != NULL) {
293		__kfree_skb(sk->sk_send_head);
294		sk->sk_send_head = NULL;
295	}
296
297	inet->inet_dport = 0;
298
299	if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
300		inet_reset_saddr(sk);
301
302	sk->sk_shutdown = 0;
303	sock_reset_flag(sk, SOCK_DONE);
304
305	icsk->icsk_backoff = 0;
306	inet_csk_delack_init(sk);
307	__sk_dst_reset(sk);
308
309	WARN_ON(inet->inet_num && !icsk->icsk_bind_hash);
310
311	sk->sk_error_report(sk);
312	return 0;
313}
314
315EXPORT_SYMBOL_GPL(dccp_disconnect);
316
317/*
318 *	Wait for a DCCP event.
319 *
320 *	Note that we don't need to lock the socket, as the upper poll layers
321 *	take care of normal races (between the test and the event) and we don't
322 *	go look at any of the socket buffers directly.
323 */
324__poll_t dccp_poll(struct file *file, struct socket *sock,
325		       poll_table *wait)
326{
327	struct sock *sk = sock->sk;
328	__poll_t mask;
329	u8 shutdown;
330	int state;
331
332	sock_poll_wait(file, sock, wait);
333
334	state = inet_sk_state_load(sk);
335	if (state == DCCP_LISTEN)
336		return inet_csk_listen_poll(sk);
337
338	/* Socket is not locked. We are protected from async events
339	   by poll logic and correct handling of state changes
340	   made by another threads is impossible in any case.
341	 */
342
343	mask = 0;
344	if (READ_ONCE(sk->sk_err))
345		mask = EPOLLERR;
346	shutdown = READ_ONCE(sk->sk_shutdown);
347
348	if (shutdown == SHUTDOWN_MASK || state == DCCP_CLOSED)
349		mask |= EPOLLHUP;
350	if (shutdown & RCV_SHUTDOWN)
351		mask |= EPOLLIN | EPOLLRDNORM | EPOLLRDHUP;
352
353	/* Connected? */
354	if ((1 << state) & ~(DCCPF_REQUESTING | DCCPF_RESPOND)) {
355		if (atomic_read(&sk->sk_rmem_alloc) > 0)
356			mask |= EPOLLIN | EPOLLRDNORM;
357
358		if (!(shutdown & SEND_SHUTDOWN)) {
359			if (sk_stream_is_writeable(sk)) {
360				mask |= EPOLLOUT | EPOLLWRNORM;
361			} else {  /* send SIGIO later */
362				sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
363				set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
364
365				/* Race breaker. If space is freed after
366				 * wspace test but before the flags are set,
367				 * IO signal will be lost.
368				 */
369				if (sk_stream_is_writeable(sk))
370					mask |= EPOLLOUT | EPOLLWRNORM;
371			}
372		}
373	}
374	return mask;
375}
376EXPORT_SYMBOL_GPL(dccp_poll);
377
378int dccp_ioctl(struct sock *sk, int cmd, unsigned long arg)
379{
380	int rc = -ENOTCONN;
381
382	lock_sock(sk);
383
384	if (sk->sk_state == DCCP_LISTEN)
385		goto out;
386
387	switch (cmd) {
388	case SIOCOUTQ: {
389		int amount = sk_wmem_alloc_get(sk);
390		/* Using sk_wmem_alloc here because sk_wmem_queued is not used by DCCP and
391		 * always 0, comparably to UDP.
392		 */
393
394		rc = put_user(amount, (int __user *)arg);
395	}
396		break;
397	case SIOCINQ: {
398		struct sk_buff *skb;
399		unsigned long amount = 0;
400
401		skb = skb_peek(&sk->sk_receive_queue);
402		if (skb != NULL) {
403			/*
404			 * We will only return the amount of this packet since
405			 * that is all that will be read.
406			 */
407			amount = skb->len;
408		}
409		rc = put_user(amount, (int __user *)arg);
410	}
411		break;
412	default:
413		rc = -ENOIOCTLCMD;
414		break;
415	}
416out:
417	release_sock(sk);
418	return rc;
419}
420
421EXPORT_SYMBOL_GPL(dccp_ioctl);
422
423static int dccp_setsockopt_service(struct sock *sk, const __be32 service,
424				   sockptr_t optval, unsigned int optlen)
425{
426	struct dccp_sock *dp = dccp_sk(sk);
427	struct dccp_service_list *sl = NULL;
428
429	if (service == DCCP_SERVICE_INVALID_VALUE ||
430	    optlen > DCCP_SERVICE_LIST_MAX_LEN * sizeof(u32))
431		return -EINVAL;
432
433	if (optlen > sizeof(service)) {
434		sl = kmalloc(optlen, GFP_KERNEL);
435		if (sl == NULL)
436			return -ENOMEM;
437
438		sl->dccpsl_nr = optlen / sizeof(u32) - 1;
439		if (copy_from_sockptr_offset(sl->dccpsl_list, optval,
440				sizeof(service), optlen - sizeof(service)) ||
441		    dccp_list_has_service(sl, DCCP_SERVICE_INVALID_VALUE)) {
442			kfree(sl);
443			return -EFAULT;
444		}
445	}
446
447	lock_sock(sk);
448	dp->dccps_service = service;
449
450	kfree(dp->dccps_service_list);
451
452	dp->dccps_service_list = sl;
453	release_sock(sk);
454	return 0;
455}
456
457static int dccp_setsockopt_cscov(struct sock *sk, int cscov, bool rx)
458{
459	u8 *list, len;
460	int i, rc;
461
462	if (cscov < 0 || cscov > 15)
463		return -EINVAL;
464	/*
465	 * Populate a list of permissible values, in the range cscov...15. This
466	 * is necessary since feature negotiation of single values only works if
467	 * both sides incidentally choose the same value. Since the list starts
468	 * lowest-value first, negotiation will pick the smallest shared value.
469	 */
470	if (cscov == 0)
471		return 0;
472	len = 16 - cscov;
473
474	list = kmalloc(len, GFP_KERNEL);
475	if (list == NULL)
476		return -ENOBUFS;
477
478	for (i = 0; i < len; i++)
479		list[i] = cscov++;
480
481	rc = dccp_feat_register_sp(sk, DCCPF_MIN_CSUM_COVER, rx, list, len);
482
483	if (rc == 0) {
484		if (rx)
485			dccp_sk(sk)->dccps_pcrlen = cscov;
486		else
487			dccp_sk(sk)->dccps_pcslen = cscov;
488	}
489	kfree(list);
490	return rc;
491}
492
493static int dccp_setsockopt_ccid(struct sock *sk, int type,
494				sockptr_t optval, unsigned int optlen)
495{
496	u8 *val;
497	int rc = 0;
498
499	if (optlen < 1 || optlen > DCCP_FEAT_MAX_SP_VALS)
500		return -EINVAL;
501
502	val = memdup_sockptr(optval, optlen);
503	if (IS_ERR(val))
504		return PTR_ERR(val);
505
506	lock_sock(sk);
507	if (type == DCCP_SOCKOPT_TX_CCID || type == DCCP_SOCKOPT_CCID)
508		rc = dccp_feat_register_sp(sk, DCCPF_CCID, 1, val, optlen);
509
510	if (!rc && (type == DCCP_SOCKOPT_RX_CCID || type == DCCP_SOCKOPT_CCID))
511		rc = dccp_feat_register_sp(sk, DCCPF_CCID, 0, val, optlen);
512	release_sock(sk);
513
514	kfree(val);
515	return rc;
516}
517
518static int do_dccp_setsockopt(struct sock *sk, int level, int optname,
519		sockptr_t optval, unsigned int optlen)
520{
521	struct dccp_sock *dp = dccp_sk(sk);
522	int val, err = 0;
523
524	switch (optname) {
525	case DCCP_SOCKOPT_PACKET_SIZE:
526		DCCP_WARN("sockopt(PACKET_SIZE) is deprecated: fix your app\n");
527		return 0;
528	case DCCP_SOCKOPT_CHANGE_L:
529	case DCCP_SOCKOPT_CHANGE_R:
530		DCCP_WARN("sockopt(CHANGE_L/R) is deprecated: fix your app\n");
531		return 0;
532	case DCCP_SOCKOPT_CCID:
533	case DCCP_SOCKOPT_RX_CCID:
534	case DCCP_SOCKOPT_TX_CCID:
535		return dccp_setsockopt_ccid(sk, optname, optval, optlen);
536	}
537
538	if (optlen < (int)sizeof(int))
539		return -EINVAL;
540
541	if (copy_from_sockptr(&val, optval, sizeof(int)))
542		return -EFAULT;
543
544	if (optname == DCCP_SOCKOPT_SERVICE)
545		return dccp_setsockopt_service(sk, val, optval, optlen);
546
547	lock_sock(sk);
548	switch (optname) {
549	case DCCP_SOCKOPT_SERVER_TIMEWAIT:
550		if (dp->dccps_role != DCCP_ROLE_SERVER)
551			err = -EOPNOTSUPP;
552		else
553			dp->dccps_server_timewait = (val != 0);
554		break;
555	case DCCP_SOCKOPT_SEND_CSCOV:
556		err = dccp_setsockopt_cscov(sk, val, false);
557		break;
558	case DCCP_SOCKOPT_RECV_CSCOV:
559		err = dccp_setsockopt_cscov(sk, val, true);
560		break;
561	case DCCP_SOCKOPT_QPOLICY_ID:
562		if (sk->sk_state != DCCP_CLOSED)
563			err = -EISCONN;
564		else if (val < 0 || val >= DCCPQ_POLICY_MAX)
565			err = -EINVAL;
566		else
567			dp->dccps_qpolicy = val;
568		break;
569	case DCCP_SOCKOPT_QPOLICY_TXQLEN:
570		if (val < 0)
571			err = -EINVAL;
572		else
573			dp->dccps_tx_qlen = val;
574		break;
575	default:
576		err = -ENOPROTOOPT;
577		break;
578	}
579	release_sock(sk);
580
581	return err;
582}
583
584int dccp_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval,
585		    unsigned int optlen)
586{
587	if (level != SOL_DCCP)
588		return inet_csk(sk)->icsk_af_ops->setsockopt(sk, level,
589							     optname, optval,
590							     optlen);
591	return do_dccp_setsockopt(sk, level, optname, optval, optlen);
592}
593
594EXPORT_SYMBOL_GPL(dccp_setsockopt);
595
596static int dccp_getsockopt_service(struct sock *sk, int len,
597				   __be32 __user *optval,
598				   int __user *optlen)
599{
600	const struct dccp_sock *dp = dccp_sk(sk);
601	const struct dccp_service_list *sl;
602	int err = -ENOENT, slen = 0, total_len = sizeof(u32);
603
604	lock_sock(sk);
605	if ((sl = dp->dccps_service_list) != NULL) {
606		slen = sl->dccpsl_nr * sizeof(u32);
607		total_len += slen;
608	}
609
610	err = -EINVAL;
611	if (total_len > len)
612		goto out;
613
614	err = 0;
615	if (put_user(total_len, optlen) ||
616	    put_user(dp->dccps_service, optval) ||
617	    (sl != NULL && copy_to_user(optval + 1, sl->dccpsl_list, slen)))
618		err = -EFAULT;
619out:
620	release_sock(sk);
621	return err;
622}
623
624static int do_dccp_getsockopt(struct sock *sk, int level, int optname,
625		    char __user *optval, int __user *optlen)
626{
627	struct dccp_sock *dp;
628	int val, len;
629
630	if (get_user(len, optlen))
631		return -EFAULT;
632
633	if (len < (int)sizeof(int))
634		return -EINVAL;
635
636	dp = dccp_sk(sk);
637
638	switch (optname) {
639	case DCCP_SOCKOPT_PACKET_SIZE:
640		DCCP_WARN("sockopt(PACKET_SIZE) is deprecated: fix your app\n");
641		return 0;
642	case DCCP_SOCKOPT_SERVICE:
643		return dccp_getsockopt_service(sk, len,
644					       (__be32 __user *)optval, optlen);
645	case DCCP_SOCKOPT_GET_CUR_MPS:
646		val = READ_ONCE(dp->dccps_mss_cache);
647		break;
648	case DCCP_SOCKOPT_AVAILABLE_CCIDS:
649		return ccid_getsockopt_builtin_ccids(sk, len, optval, optlen);
650	case DCCP_SOCKOPT_TX_CCID:
651		val = ccid_get_current_tx_ccid(dp);
652		if (val < 0)
653			return -ENOPROTOOPT;
654		break;
655	case DCCP_SOCKOPT_RX_CCID:
656		val = ccid_get_current_rx_ccid(dp);
657		if (val < 0)
658			return -ENOPROTOOPT;
659		break;
660	case DCCP_SOCKOPT_SERVER_TIMEWAIT:
661		val = dp->dccps_server_timewait;
662		break;
663	case DCCP_SOCKOPT_SEND_CSCOV:
664		val = dp->dccps_pcslen;
665		break;
666	case DCCP_SOCKOPT_RECV_CSCOV:
667		val = dp->dccps_pcrlen;
668		break;
669	case DCCP_SOCKOPT_QPOLICY_ID:
670		val = dp->dccps_qpolicy;
671		break;
672	case DCCP_SOCKOPT_QPOLICY_TXQLEN:
673		val = dp->dccps_tx_qlen;
674		break;
675	case 128 ... 191:
676		return ccid_hc_rx_getsockopt(dp->dccps_hc_rx_ccid, sk, optname,
677					     len, (u32 __user *)optval, optlen);
678	case 192 ... 255:
679		return ccid_hc_tx_getsockopt(dp->dccps_hc_tx_ccid, sk, optname,
680					     len, (u32 __user *)optval, optlen);
681	default:
682		return -ENOPROTOOPT;
683	}
684
685	len = sizeof(val);
686	if (put_user(len, optlen) || copy_to_user(optval, &val, len))
687		return -EFAULT;
688
689	return 0;
690}
691
692int dccp_getsockopt(struct sock *sk, int level, int optname,
693		    char __user *optval, int __user *optlen)
694{
695	if (level != SOL_DCCP)
696		return inet_csk(sk)->icsk_af_ops->getsockopt(sk, level,
697							     optname, optval,
698							     optlen);
699	return do_dccp_getsockopt(sk, level, optname, optval, optlen);
700}
701
702EXPORT_SYMBOL_GPL(dccp_getsockopt);
703
704static int dccp_msghdr_parse(struct msghdr *msg, struct sk_buff *skb)
705{
706	struct cmsghdr *cmsg;
707
708	/*
709	 * Assign an (opaque) qpolicy priority value to skb->priority.
710	 *
711	 * We are overloading this skb field for use with the qpolicy subystem.
712	 * The skb->priority is normally used for the SO_PRIORITY option, which
713	 * is initialised from sk_priority. Since the assignment of sk_priority
714	 * to skb->priority happens later (on layer 3), we overload this field
715	 * for use with queueing priorities as long as the skb is on layer 4.
716	 * The default priority value (if nothing is set) is 0.
717	 */
718	skb->priority = 0;
719
720	for_each_cmsghdr(cmsg, msg) {
721		if (!CMSG_OK(msg, cmsg))
722			return -EINVAL;
723
724		if (cmsg->cmsg_level != SOL_DCCP)
725			continue;
726
727		if (cmsg->cmsg_type <= DCCP_SCM_QPOLICY_MAX &&
728		    !dccp_qpolicy_param_ok(skb->sk, cmsg->cmsg_type))
729			return -EINVAL;
730
731		switch (cmsg->cmsg_type) {
732		case DCCP_SCM_PRIORITY:
733			if (cmsg->cmsg_len != CMSG_LEN(sizeof(__u32)))
734				return -EINVAL;
735			skb->priority = *(__u32 *)CMSG_DATA(cmsg);
736			break;
737		default:
738			return -EINVAL;
739		}
740	}
741	return 0;
742}
743
744int dccp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
745{
746	const struct dccp_sock *dp = dccp_sk(sk);
747	const int flags = msg->msg_flags;
748	const int noblock = flags & MSG_DONTWAIT;
749	struct sk_buff *skb;
750	int rc, size;
751	long timeo;
752
753	trace_dccp_probe(sk, len);
754
755	if (len > READ_ONCE(dp->dccps_mss_cache))
756		return -EMSGSIZE;
757
758	lock_sock(sk);
759
760	timeo = sock_sndtimeo(sk, noblock);
761
762	/*
763	 * We have to use sk_stream_wait_connect here to set sk_write_pending,
764	 * so that the trick in dccp_rcv_request_sent_state_process.
765	 */
766	/* Wait for a connection to finish. */
767	if ((1 << sk->sk_state) & ~(DCCPF_OPEN | DCCPF_PARTOPEN))
768		if ((rc = sk_stream_wait_connect(sk, &timeo)) != 0)
769			goto out_release;
770
771	size = sk->sk_prot->max_header + len;
772	release_sock(sk);
773	skb = sock_alloc_send_skb(sk, size, noblock, &rc);
774	lock_sock(sk);
775	if (skb == NULL)
776		goto out_release;
777
778	if (dccp_qpolicy_full(sk)) {
779		rc = -EAGAIN;
780		goto out_discard;
781	}
782
783	if (sk->sk_state == DCCP_CLOSED) {
784		rc = -ENOTCONN;
785		goto out_discard;
786	}
787
788	/* We need to check dccps_mss_cache after socket is locked. */
789	if (len > dp->dccps_mss_cache) {
790		rc = -EMSGSIZE;
791		goto out_discard;
792	}
793
794	skb_reserve(skb, sk->sk_prot->max_header);
795	rc = memcpy_from_msg(skb_put(skb, len), msg, len);
796	if (rc != 0)
797		goto out_discard;
798
799	rc = dccp_msghdr_parse(msg, skb);
800	if (rc != 0)
801		goto out_discard;
802
803	dccp_qpolicy_push(sk, skb);
804	/*
805	 * The xmit_timer is set if the TX CCID is rate-based and will expire
806	 * when congestion control permits to release further packets into the
807	 * network. Window-based CCIDs do not use this timer.
808	 */
809	if (!timer_pending(&dp->dccps_xmit_timer))
810		dccp_write_xmit(sk);
811out_release:
812	release_sock(sk);
813	return rc ? : len;
814out_discard:
815	kfree_skb(skb);
816	goto out_release;
817}
818
819EXPORT_SYMBOL_GPL(dccp_sendmsg);
820
821int dccp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int nonblock,
822		 int flags, int *addr_len)
823{
824	const struct dccp_hdr *dh;
825	long timeo;
826
827	lock_sock(sk);
828
829	if (sk->sk_state == DCCP_LISTEN) {
830		len = -ENOTCONN;
831		goto out;
832	}
833
834	timeo = sock_rcvtimeo(sk, nonblock);
835
836	do {
837		struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
838
839		if (skb == NULL)
840			goto verify_sock_status;
841
842		dh = dccp_hdr(skb);
843
844		switch (dh->dccph_type) {
845		case DCCP_PKT_DATA:
846		case DCCP_PKT_DATAACK:
847			goto found_ok_skb;
848
849		case DCCP_PKT_CLOSE:
850		case DCCP_PKT_CLOSEREQ:
851			if (!(flags & MSG_PEEK))
852				dccp_finish_passive_close(sk);
853			fallthrough;
854		case DCCP_PKT_RESET:
855			dccp_pr_debug("found fin (%s) ok!\n",
856				      dccp_packet_name(dh->dccph_type));
857			len = 0;
858			goto found_fin_ok;
859		default:
860			dccp_pr_debug("packet_type=%s\n",
861				      dccp_packet_name(dh->dccph_type));
862			sk_eat_skb(sk, skb);
863		}
864verify_sock_status:
865		if (sock_flag(sk, SOCK_DONE)) {
866			len = 0;
867			break;
868		}
869
870		if (sk->sk_err) {
871			len = sock_error(sk);
872			break;
873		}
874
875		if (sk->sk_shutdown & RCV_SHUTDOWN) {
876			len = 0;
877			break;
878		}
879
880		if (sk->sk_state == DCCP_CLOSED) {
881			if (!sock_flag(sk, SOCK_DONE)) {
882				/* This occurs when user tries to read
883				 * from never connected socket.
884				 */
885				len = -ENOTCONN;
886				break;
887			}
888			len = 0;
889			break;
890		}
891
892		if (!timeo) {
893			len = -EAGAIN;
894			break;
895		}
896
897		if (signal_pending(current)) {
898			len = sock_intr_errno(timeo);
899			break;
900		}
901
902		sk_wait_data(sk, &timeo, NULL);
903		continue;
904	found_ok_skb:
905		if (len > skb->len)
906			len = skb->len;
907		else if (len < skb->len)
908			msg->msg_flags |= MSG_TRUNC;
909
910		if (skb_copy_datagram_msg(skb, 0, msg, len)) {
911			/* Exception. Bailout! */
912			len = -EFAULT;
913			break;
914		}
915		if (flags & MSG_TRUNC)
916			len = skb->len;
917	found_fin_ok:
918		if (!(flags & MSG_PEEK))
919			sk_eat_skb(sk, skb);
920		break;
921	} while (1);
922out:
923	release_sock(sk);
924	return len;
925}
926
927EXPORT_SYMBOL_GPL(dccp_recvmsg);
928
929int inet_dccp_listen(struct socket *sock, int backlog)
930{
931	struct sock *sk = sock->sk;
932	unsigned char old_state;
933	int err;
934
935	lock_sock(sk);
936
937	err = -EINVAL;
938	if (sock->state != SS_UNCONNECTED || sock->type != SOCK_DCCP)
939		goto out;
940
941	old_state = sk->sk_state;
942	if (!((1 << old_state) & (DCCPF_CLOSED | DCCPF_LISTEN)))
943		goto out;
944
945	WRITE_ONCE(sk->sk_max_ack_backlog, backlog);
946	/* Really, if the socket is already in listen state
947	 * we can only allow the backlog to be adjusted.
948	 */
949	if (old_state != DCCP_LISTEN) {
950		/*
951		 * FIXME: here it probably should be sk->sk_prot->listen_start
952		 * see tcp_listen_start
953		 */
954		err = dccp_listen_start(sk, backlog);
955		if (err)
956			goto out;
957	}
958	err = 0;
959
960out:
961	release_sock(sk);
962	return err;
963}
964
965EXPORT_SYMBOL_GPL(inet_dccp_listen);
966
967static void dccp_terminate_connection(struct sock *sk)
968{
969	u8 next_state = DCCP_CLOSED;
970
971	switch (sk->sk_state) {
972	case DCCP_PASSIVE_CLOSE:
973	case DCCP_PASSIVE_CLOSEREQ:
974		dccp_finish_passive_close(sk);
975		break;
976	case DCCP_PARTOPEN:
977		dccp_pr_debug("Stop PARTOPEN timer (%p)\n", sk);
978		inet_csk_clear_xmit_timer(sk, ICSK_TIME_DACK);
979		fallthrough;
980	case DCCP_OPEN:
981		dccp_send_close(sk, 1);
982
983		if (dccp_sk(sk)->dccps_role == DCCP_ROLE_SERVER &&
984		    !dccp_sk(sk)->dccps_server_timewait)
985			next_state = DCCP_ACTIVE_CLOSEREQ;
986		else
987			next_state = DCCP_CLOSING;
988		fallthrough;
989	default:
990		dccp_set_state(sk, next_state);
991	}
992}
993
994void dccp_close(struct sock *sk, long timeout)
995{
996	struct dccp_sock *dp = dccp_sk(sk);
997	struct sk_buff *skb;
998	u32 data_was_unread = 0;
999	int state;
1000
1001	lock_sock(sk);
1002
1003	sk->sk_shutdown = SHUTDOWN_MASK;
1004
1005	if (sk->sk_state == DCCP_LISTEN) {
1006		dccp_set_state(sk, DCCP_CLOSED);
1007
1008		/* Special case. */
1009		inet_csk_listen_stop(sk);
1010
1011		goto adjudge_to_death;
1012	}
1013
1014	sk_stop_timer(sk, &dp->dccps_xmit_timer);
1015
1016	/*
1017	 * We need to flush the recv. buffs.  We do this only on the
1018	 * descriptor close, not protocol-sourced closes, because the
1019	  *reader process may not have drained the data yet!
1020	 */
1021	while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
1022		data_was_unread += skb->len;
1023		__kfree_skb(skb);
1024	}
1025
1026	/* If socket has been already reset kill it. */
1027	if (sk->sk_state == DCCP_CLOSED)
1028		goto adjudge_to_death;
1029
1030	if (data_was_unread) {
1031		/* Unread data was tossed, send an appropriate Reset Code */
1032		DCCP_WARN("ABORT with %u bytes unread\n", data_was_unread);
1033		dccp_send_reset(sk, DCCP_RESET_CODE_ABORTED);
1034		dccp_set_state(sk, DCCP_CLOSED);
1035	} else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
1036		/* Check zero linger _after_ checking for unread data. */
1037		sk->sk_prot->disconnect(sk, 0);
1038	} else if (sk->sk_state != DCCP_CLOSED) {
1039		/*
1040		 * Normal connection termination. May need to wait if there are
1041		 * still packets in the TX queue that are delayed by the CCID.
1042		 */
1043		dccp_flush_write_queue(sk, &timeout);
1044		dccp_terminate_connection(sk);
1045	}
1046
1047	/*
1048	 * Flush write queue. This may be necessary in several cases:
1049	 * - we have been closed by the peer but still have application data;
1050	 * - abortive termination (unread data or zero linger time),
1051	 * - normal termination but queue could not be flushed within time limit
1052	 */
1053	__skb_queue_purge(&sk->sk_write_queue);
1054
1055	sk_stream_wait_close(sk, timeout);
1056
1057adjudge_to_death:
1058	state = sk->sk_state;
1059	sock_hold(sk);
1060	sock_orphan(sk);
1061
1062	/*
1063	 * It is the last release_sock in its life. It will remove backlog.
1064	 */
1065	release_sock(sk);
1066	/*
1067	 * Now socket is owned by kernel and we acquire BH lock
1068	 * to finish close. No need to check for user refs.
1069	 */
1070	local_bh_disable();
1071	bh_lock_sock(sk);
1072	WARN_ON(sock_owned_by_user(sk));
1073
1074	this_cpu_inc(dccp_orphan_count);
1075
1076	/* Have we already been destroyed by a softirq or backlog? */
1077	if (state != DCCP_CLOSED && sk->sk_state == DCCP_CLOSED)
1078		goto out;
1079
1080	if (sk->sk_state == DCCP_CLOSED)
1081		inet_csk_destroy_sock(sk);
1082
1083	/* Otherwise, socket is reprieved until protocol close. */
1084
1085out:
1086	bh_unlock_sock(sk);
1087	local_bh_enable();
1088	sock_put(sk);
1089}
1090
1091EXPORT_SYMBOL_GPL(dccp_close);
1092
1093void dccp_shutdown(struct sock *sk, int how)
1094{
1095	dccp_pr_debug("called shutdown(%x)\n", how);
1096}
1097
1098EXPORT_SYMBOL_GPL(dccp_shutdown);
1099
1100static inline int __init dccp_mib_init(void)
1101{
1102	dccp_statistics = alloc_percpu(struct dccp_mib);
1103	if (!dccp_statistics)
1104		return -ENOMEM;
1105	return 0;
1106}
1107
1108static inline void dccp_mib_exit(void)
1109{
1110	free_percpu(dccp_statistics);
1111}
1112
1113static int thash_entries;
1114module_param(thash_entries, int, 0444);
1115MODULE_PARM_DESC(thash_entries, "Number of ehash buckets");
1116
1117#ifdef CONFIG_IP_DCCP_DEBUG
1118bool dccp_debug;
1119module_param(dccp_debug, bool, 0644);
1120MODULE_PARM_DESC(dccp_debug, "Enable debug messages");
1121
1122EXPORT_SYMBOL_GPL(dccp_debug);
1123#endif
1124
1125static int __init dccp_init(void)
1126{
1127	unsigned long goal;
1128	unsigned long nr_pages = totalram_pages();
1129	int ehash_order, bhash_order, i;
1130	int rc;
1131
1132	BUILD_BUG_ON(sizeof(struct dccp_skb_cb) >
1133		     sizeof_field(struct sk_buff, cb));
1134	inet_hashinfo_init(&dccp_hashinfo);
1135	rc = inet_hashinfo2_init_mod(&dccp_hashinfo);
1136	if (rc)
1137		goto out_fail;
1138	rc = -ENOBUFS;
1139	dccp_hashinfo.bind_bucket_cachep =
1140		kmem_cache_create("dccp_bind_bucket",
1141				  sizeof(struct inet_bind_bucket), 0,
1142				  SLAB_HWCACHE_ALIGN, NULL);
1143	if (!dccp_hashinfo.bind_bucket_cachep)
1144		goto out_free_hashinfo2;
1145
1146	/*
1147	 * Size and allocate the main established and bind bucket
1148	 * hash tables.
1149	 *
1150	 * The methodology is similar to that of the buffer cache.
1151	 */
1152	if (nr_pages >= (128 * 1024))
1153		goal = nr_pages >> (21 - PAGE_SHIFT);
1154	else
1155		goal = nr_pages >> (23 - PAGE_SHIFT);
1156
1157	if (thash_entries)
1158		goal = (thash_entries *
1159			sizeof(struct inet_ehash_bucket)) >> PAGE_SHIFT;
1160	for (ehash_order = 0; (1UL << ehash_order) < goal; ehash_order++)
1161		;
1162	do {
1163		unsigned long hash_size = (1UL << ehash_order) * PAGE_SIZE /
1164					sizeof(struct inet_ehash_bucket);
1165
1166		while (hash_size & (hash_size - 1))
1167			hash_size--;
1168		dccp_hashinfo.ehash_mask = hash_size - 1;
1169		dccp_hashinfo.ehash = (struct inet_ehash_bucket *)
1170			__get_free_pages(GFP_ATOMIC|__GFP_NOWARN, ehash_order);
1171	} while (!dccp_hashinfo.ehash && --ehash_order > 0);
1172
1173	if (!dccp_hashinfo.ehash) {
1174		DCCP_CRIT("Failed to allocate DCCP established hash table");
1175		goto out_free_bind_bucket_cachep;
1176	}
1177
1178	for (i = 0; i <= dccp_hashinfo.ehash_mask; i++)
1179		INIT_HLIST_NULLS_HEAD(&dccp_hashinfo.ehash[i].chain, i);
1180
1181	if (inet_ehash_locks_alloc(&dccp_hashinfo))
1182			goto out_free_dccp_ehash;
1183
1184	bhash_order = ehash_order;
1185
1186	do {
1187		dccp_hashinfo.bhash_size = (1UL << bhash_order) * PAGE_SIZE /
1188					sizeof(struct inet_bind_hashbucket);
1189		if ((dccp_hashinfo.bhash_size > (64 * 1024)) &&
1190		    bhash_order > 0)
1191			continue;
1192		dccp_hashinfo.bhash = (struct inet_bind_hashbucket *)
1193			__get_free_pages(GFP_ATOMIC|__GFP_NOWARN, bhash_order);
1194	} while (!dccp_hashinfo.bhash && --bhash_order >= 0);
1195
1196	if (!dccp_hashinfo.bhash) {
1197		DCCP_CRIT("Failed to allocate DCCP bind hash table");
1198		goto out_free_dccp_locks;
1199	}
1200
1201	for (i = 0; i < dccp_hashinfo.bhash_size; i++) {
1202		spin_lock_init(&dccp_hashinfo.bhash[i].lock);
1203		INIT_HLIST_HEAD(&dccp_hashinfo.bhash[i].chain);
1204	}
1205
1206	rc = dccp_mib_init();
1207	if (rc)
1208		goto out_free_dccp_bhash;
1209
1210	rc = dccp_ackvec_init();
1211	if (rc)
1212		goto out_free_dccp_mib;
1213
1214	rc = dccp_sysctl_init();
1215	if (rc)
1216		goto out_ackvec_exit;
1217
1218	rc = ccid_initialize_builtins();
1219	if (rc)
1220		goto out_sysctl_exit;
1221
1222	dccp_timestamping_init();
1223
1224	return 0;
1225
1226out_sysctl_exit:
1227	dccp_sysctl_exit();
1228out_ackvec_exit:
1229	dccp_ackvec_exit();
1230out_free_dccp_mib:
1231	dccp_mib_exit();
1232out_free_dccp_bhash:
1233	free_pages((unsigned long)dccp_hashinfo.bhash, bhash_order);
1234out_free_dccp_locks:
1235	inet_ehash_locks_free(&dccp_hashinfo);
1236out_free_dccp_ehash:
1237	free_pages((unsigned long)dccp_hashinfo.ehash, ehash_order);
1238out_free_bind_bucket_cachep:
1239	kmem_cache_destroy(dccp_hashinfo.bind_bucket_cachep);
1240out_free_hashinfo2:
1241	inet_hashinfo2_free_mod(&dccp_hashinfo);
1242out_fail:
1243	dccp_hashinfo.bhash = NULL;
1244	dccp_hashinfo.ehash = NULL;
1245	dccp_hashinfo.bind_bucket_cachep = NULL;
1246	return rc;
1247}
1248
1249static void __exit dccp_fini(void)
1250{
1251	ccid_cleanup_builtins();
1252	dccp_mib_exit();
1253	free_pages((unsigned long)dccp_hashinfo.bhash,
1254		   get_order(dccp_hashinfo.bhash_size *
1255			     sizeof(struct inet_bind_hashbucket)));
1256	free_pages((unsigned long)dccp_hashinfo.ehash,
1257		   get_order((dccp_hashinfo.ehash_mask + 1) *
1258			     sizeof(struct inet_ehash_bucket)));
1259	inet_ehash_locks_free(&dccp_hashinfo);
1260	kmem_cache_destroy(dccp_hashinfo.bind_bucket_cachep);
1261	dccp_ackvec_exit();
1262	dccp_sysctl_exit();
1263	inet_hashinfo2_free_mod(&dccp_hashinfo);
1264}
1265
1266module_init(dccp_init);
1267module_exit(dccp_fini);
1268
1269MODULE_LICENSE("GPL");
1270MODULE_AUTHOR("Arnaldo Carvalho de Melo <acme@conectiva.com.br>");
1271MODULE_DESCRIPTION("DCCP - Datagram Congestion Controlled Protocol");
1272