xref: /linux/net/caif/caif_socket.c (revision 811f35ff59b6f99ae272d6f5b96bc9e974f88196)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) ST-Ericsson AB 2010
4  * Author:	Sjur Brendeland
5  */
6 
7 #define pr_fmt(fmt) KBUILD_MODNAME ":%s(): " fmt, __func__
8 
9 #include <linux/filter.h>
10 #include <linux/fs.h>
11 #include <linux/init.h>
12 #include <linux/module.h>
13 #include <linux/sched/signal.h>
14 #include <linux/spinlock.h>
15 #include <linux/mutex.h>
16 #include <linux/list.h>
17 #include <linux/wait.h>
18 #include <linux/poll.h>
19 #include <linux/tcp.h>
20 #include <linux/uaccess.h>
21 #include <linux/debugfs.h>
22 #include <linux/caif/caif_socket.h>
23 #include <linux/pkt_sched.h>
24 #include <net/sock.h>
25 #include <net/tcp_states.h>
26 #include <net/caif/caif_layer.h>
27 #include <net/caif/caif_dev.h>
28 #include <net/caif/cfpkt.h>
29 
30 MODULE_LICENSE("GPL");
31 MODULE_ALIAS_NETPROTO(AF_CAIF);
32 
33 /*
34  * CAIF state is re-using the TCP socket states.
35  * caif_states stored in sk_state reflect the state as reported by
36  * the CAIF stack, while sk_socket->state is the state of the socket.
37  */
38 enum caif_states {
39 	CAIF_CONNECTED		= TCP_ESTABLISHED,
40 	CAIF_CONNECTING	= TCP_SYN_SENT,
41 	CAIF_DISCONNECTED	= TCP_CLOSE
42 };
43 
44 #define TX_FLOW_ON_BIT	1
45 #define RX_FLOW_ON_BIT	2
46 
47 struct caifsock {
48 	struct sock sk; /* must be first member */
49 	struct cflayer layer;
50 	unsigned long flow_state;
51 	struct caif_connect_request conn_req;
52 	struct mutex readlock;
53 	struct dentry *debugfs_socket_dir;
54 	int headroom, tailroom, maxframe;
55 };
56 
57 static int rx_flow_is_on(struct caifsock *cf_sk)
58 {
59 	return test_bit(RX_FLOW_ON_BIT, &cf_sk->flow_state);
60 }
61 
62 static int tx_flow_is_on(struct caifsock *cf_sk)
63 {
64 	return test_bit(TX_FLOW_ON_BIT, &cf_sk->flow_state);
65 }
66 
67 static void set_rx_flow_off(struct caifsock *cf_sk)
68 {
69 	clear_bit(RX_FLOW_ON_BIT, &cf_sk->flow_state);
70 }
71 
72 static void set_rx_flow_on(struct caifsock *cf_sk)
73 {
74 	set_bit(RX_FLOW_ON_BIT, &cf_sk->flow_state);
75 }
76 
77 static void set_tx_flow_off(struct caifsock *cf_sk)
78 {
79 	clear_bit(TX_FLOW_ON_BIT, &cf_sk->flow_state);
80 }
81 
82 static void set_tx_flow_on(struct caifsock *cf_sk)
83 {
84 	set_bit(TX_FLOW_ON_BIT, &cf_sk->flow_state);
85 }
86 
87 static void caif_read_lock(struct sock *sk)
88 {
89 	struct caifsock *cf_sk;
90 	cf_sk = container_of(sk, struct caifsock, sk);
91 	mutex_lock(&cf_sk->readlock);
92 }
93 
94 static void caif_read_unlock(struct sock *sk)
95 {
96 	struct caifsock *cf_sk;
97 	cf_sk = container_of(sk, struct caifsock, sk);
98 	mutex_unlock(&cf_sk->readlock);
99 }
100 
101 static int sk_rcvbuf_lowwater(struct caifsock *cf_sk)
102 {
103 	/* A quarter of full buffer is used a low water mark */
104 	return cf_sk->sk.sk_rcvbuf / 4;
105 }
106 
107 static void caif_flow_ctrl(struct sock *sk, int mode)
108 {
109 	struct caifsock *cf_sk;
110 	cf_sk = container_of(sk, struct caifsock, sk);
111 	if (cf_sk->layer.dn && cf_sk->layer.dn->modemcmd)
112 		cf_sk->layer.dn->modemcmd(cf_sk->layer.dn, mode);
113 }
114 
115 /*
116  * Copied from sock.c:sock_queue_rcv_skb(), but changed so packets are
117  * not dropped, but CAIF is sending flow off instead.
118  */
119 static void caif_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
120 {
121 	int err;
122 	unsigned long flags;
123 	struct sk_buff_head *list = &sk->sk_receive_queue;
124 	struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
125 	bool queued = false;
126 
127 	if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
128 		(unsigned int)sk->sk_rcvbuf && rx_flow_is_on(cf_sk)) {
129 		net_dbg_ratelimited("sending flow OFF (queue len = %d %d)\n",
130 				    atomic_read(&cf_sk->sk.sk_rmem_alloc),
131 				    sk_rcvbuf_lowwater(cf_sk));
132 		set_rx_flow_off(cf_sk);
133 		caif_flow_ctrl(sk, CAIF_MODEMCMD_FLOW_OFF_REQ);
134 	}
135 
136 	err = sk_filter(sk, skb);
137 	if (err)
138 		goto out;
139 
140 	if (!sk_rmem_schedule(sk, skb, skb->truesize) && rx_flow_is_on(cf_sk)) {
141 		set_rx_flow_off(cf_sk);
142 		net_dbg_ratelimited("sending flow OFF due to rmem_schedule\n");
143 		caif_flow_ctrl(sk, CAIF_MODEMCMD_FLOW_OFF_REQ);
144 	}
145 	skb->dev = NULL;
146 	skb_set_owner_r(skb, sk);
147 	spin_lock_irqsave(&list->lock, flags);
148 	queued = !sock_flag(sk, SOCK_DEAD);
149 	if (queued)
150 		__skb_queue_tail(list, skb);
151 	spin_unlock_irqrestore(&list->lock, flags);
152 out:
153 	if (queued)
154 		sk->sk_data_ready(sk);
155 	else
156 		kfree_skb(skb);
157 }
158 
159 /* Packet Receive Callback function called from CAIF Stack */
160 static int caif_sktrecv_cb(struct cflayer *layr, struct cfpkt *pkt)
161 {
162 	struct caifsock *cf_sk;
163 	struct sk_buff *skb;
164 
165 	cf_sk = container_of(layr, struct caifsock, layer);
166 	skb = cfpkt_tonative(pkt);
167 
168 	if (unlikely(cf_sk->sk.sk_state != CAIF_CONNECTED)) {
169 		kfree_skb(skb);
170 		return 0;
171 	}
172 	caif_queue_rcv_skb(&cf_sk->sk, skb);
173 	return 0;
174 }
175 
176 static void cfsk_hold(struct cflayer *layr)
177 {
178 	struct caifsock *cf_sk = container_of(layr, struct caifsock, layer);
179 	sock_hold(&cf_sk->sk);
180 }
181 
182 static void cfsk_put(struct cflayer *layr)
183 {
184 	struct caifsock *cf_sk = container_of(layr, struct caifsock, layer);
185 	sock_put(&cf_sk->sk);
186 }
187 
188 /* Packet Control Callback function called from CAIF */
189 static void caif_ctrl_cb(struct cflayer *layr,
190 			 enum caif_ctrlcmd flow,
191 			 int phyid)
192 {
193 	struct caifsock *cf_sk = container_of(layr, struct caifsock, layer);
194 	switch (flow) {
195 	case CAIF_CTRLCMD_FLOW_ON_IND:
196 		/* OK from modem to start sending again */
197 		set_tx_flow_on(cf_sk);
198 		cf_sk->sk.sk_state_change(&cf_sk->sk);
199 		break;
200 
201 	case CAIF_CTRLCMD_FLOW_OFF_IND:
202 		/* Modem asks us to shut up */
203 		set_tx_flow_off(cf_sk);
204 		cf_sk->sk.sk_state_change(&cf_sk->sk);
205 		break;
206 
207 	case CAIF_CTRLCMD_INIT_RSP:
208 		/* We're now connected */
209 		caif_client_register_refcnt(&cf_sk->layer,
210 						cfsk_hold, cfsk_put);
211 		cf_sk->sk.sk_state = CAIF_CONNECTED;
212 		set_tx_flow_on(cf_sk);
213 		cf_sk->sk.sk_shutdown = 0;
214 		cf_sk->sk.sk_state_change(&cf_sk->sk);
215 		break;
216 
217 	case CAIF_CTRLCMD_DEINIT_RSP:
218 		/* We're now disconnected */
219 		cf_sk->sk.sk_state = CAIF_DISCONNECTED;
220 		cf_sk->sk.sk_state_change(&cf_sk->sk);
221 		break;
222 
223 	case CAIF_CTRLCMD_INIT_FAIL_RSP:
224 		/* Connect request failed */
225 		cf_sk->sk.sk_err = ECONNREFUSED;
226 		cf_sk->sk.sk_state = CAIF_DISCONNECTED;
227 		cf_sk->sk.sk_shutdown = SHUTDOWN_MASK;
228 		/*
229 		 * Socket "standards" seems to require POLLOUT to
230 		 * be set at connect failure.
231 		 */
232 		set_tx_flow_on(cf_sk);
233 		cf_sk->sk.sk_state_change(&cf_sk->sk);
234 		break;
235 
236 	case CAIF_CTRLCMD_REMOTE_SHUTDOWN_IND:
237 		/* Modem has closed this connection, or device is down. */
238 		cf_sk->sk.sk_shutdown = SHUTDOWN_MASK;
239 		cf_sk->sk.sk_err = ECONNRESET;
240 		set_rx_flow_on(cf_sk);
241 		sk_error_report(&cf_sk->sk);
242 		break;
243 
244 	default:
245 		pr_debug("Unexpected flow command %d\n", flow);
246 	}
247 }
248 
249 static void caif_check_flow_release(struct sock *sk)
250 {
251 	struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
252 
253 	if (rx_flow_is_on(cf_sk))
254 		return;
255 
256 	if (atomic_read(&sk->sk_rmem_alloc) <= sk_rcvbuf_lowwater(cf_sk)) {
257 			set_rx_flow_on(cf_sk);
258 			caif_flow_ctrl(sk, CAIF_MODEMCMD_FLOW_ON_REQ);
259 	}
260 }
261 
262 /*
263  * Copied from unix_dgram_recvmsg, but removed credit checks,
264  * changed locking, address handling and added MSG_TRUNC.
265  */
266 static int caif_seqpkt_recvmsg(struct socket *sock, struct msghdr *m,
267 			       size_t len, int flags)
268 
269 {
270 	struct sock *sk = sock->sk;
271 	struct sk_buff *skb;
272 	int ret;
273 	int copylen;
274 
275 	ret = -EOPNOTSUPP;
276 	if (flags & MSG_OOB)
277 		goto read_error;
278 
279 	skb = skb_recv_datagram(sk, flags, &ret);
280 	if (!skb)
281 		goto read_error;
282 	copylen = skb->len;
283 	if (len < copylen) {
284 		m->msg_flags |= MSG_TRUNC;
285 		copylen = len;
286 	}
287 
288 	ret = skb_copy_datagram_msg(skb, 0, m, copylen);
289 	if (ret)
290 		goto out_free;
291 
292 	ret = (flags & MSG_TRUNC) ? skb->len : copylen;
293 out_free:
294 	skb_free_datagram(sk, skb);
295 	caif_check_flow_release(sk);
296 	return ret;
297 
298 read_error:
299 	return ret;
300 }
301 
302 
303 /* Copied from unix_stream_wait_data, identical except for lock call. */
304 static long caif_stream_data_wait(struct sock *sk, long timeo)
305 {
306 	DEFINE_WAIT(wait);
307 	lock_sock(sk);
308 
309 	for (;;) {
310 		prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
311 
312 		if (!skb_queue_empty(&sk->sk_receive_queue) ||
313 			sk->sk_err ||
314 			sk->sk_state != CAIF_CONNECTED ||
315 			sock_flag(sk, SOCK_DEAD) ||
316 			(sk->sk_shutdown & RCV_SHUTDOWN) ||
317 			signal_pending(current) ||
318 			!timeo)
319 			break;
320 
321 		sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
322 		release_sock(sk);
323 		timeo = schedule_timeout(timeo);
324 		lock_sock(sk);
325 
326 		if (sock_flag(sk, SOCK_DEAD))
327 			break;
328 
329 		sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
330 	}
331 
332 	finish_wait(sk_sleep(sk), &wait);
333 	release_sock(sk);
334 	return timeo;
335 }
336 
337 
338 /*
339  * Copied from unix_stream_recvmsg, but removed credit checks,
340  * changed locking calls, changed address handling.
341  */
342 static int caif_stream_recvmsg(struct socket *sock, struct msghdr *msg,
343 			       size_t size, int flags)
344 {
345 	struct sock *sk = sock->sk;
346 	int copied = 0;
347 	int target;
348 	int err = 0;
349 	long timeo;
350 
351 	err = -EOPNOTSUPP;
352 	if (flags&MSG_OOB)
353 		goto out;
354 
355 	/*
356 	 * Lock the socket to prevent queue disordering
357 	 * while sleeps in memcpy_tomsg
358 	 */
359 	err = -EAGAIN;
360 	if (sk->sk_state == CAIF_CONNECTING)
361 		goto out;
362 
363 	caif_read_lock(sk);
364 	target = sock_rcvlowat(sk, flags&MSG_WAITALL, size);
365 	timeo = sock_rcvtimeo(sk, flags&MSG_DONTWAIT);
366 
367 	do {
368 		int chunk;
369 		struct sk_buff *skb;
370 
371 		lock_sock(sk);
372 		if (sock_flag(sk, SOCK_DEAD)) {
373 			err = -ECONNRESET;
374 			goto unlock;
375 		}
376 		skb = skb_dequeue(&sk->sk_receive_queue);
377 		caif_check_flow_release(sk);
378 
379 		if (skb == NULL) {
380 			if (copied >= target)
381 				goto unlock;
382 			/*
383 			 *	POSIX 1003.1g mandates this order.
384 			 */
385 			err = sock_error(sk);
386 			if (err)
387 				goto unlock;
388 			err = -ECONNRESET;
389 			if (sk->sk_shutdown & RCV_SHUTDOWN)
390 				goto unlock;
391 
392 			err = -EPIPE;
393 			if (sk->sk_state != CAIF_CONNECTED)
394 				goto unlock;
395 			if (sock_flag(sk, SOCK_DEAD))
396 				goto unlock;
397 
398 			release_sock(sk);
399 
400 			err = -EAGAIN;
401 			if (!timeo)
402 				break;
403 
404 			caif_read_unlock(sk);
405 
406 			timeo = caif_stream_data_wait(sk, timeo);
407 
408 			if (signal_pending(current)) {
409 				err = sock_intr_errno(timeo);
410 				goto out;
411 			}
412 			caif_read_lock(sk);
413 			continue;
414 unlock:
415 			release_sock(sk);
416 			break;
417 		}
418 		release_sock(sk);
419 		chunk = min_t(unsigned int, skb->len, size);
420 		if (memcpy_to_msg(msg, skb->data, chunk)) {
421 			skb_queue_head(&sk->sk_receive_queue, skb);
422 			if (copied == 0)
423 				copied = -EFAULT;
424 			break;
425 		}
426 		copied += chunk;
427 		size -= chunk;
428 
429 		/* Mark read part of skb as used */
430 		if (!(flags & MSG_PEEK)) {
431 			skb_pull(skb, chunk);
432 
433 			/* put the skb back if we didn't use it up. */
434 			if (skb->len) {
435 				skb_queue_head(&sk->sk_receive_queue, skb);
436 				break;
437 			}
438 			kfree_skb(skb);
439 
440 		} else {
441 			/*
442 			 * It is questionable, see note in unix_dgram_recvmsg.
443 			 */
444 			/* put message back and return */
445 			skb_queue_head(&sk->sk_receive_queue, skb);
446 			break;
447 		}
448 	} while (size);
449 	caif_read_unlock(sk);
450 
451 out:
452 	return copied ? : err;
453 }
454 
455 /*
456  * Copied from sock.c:sock_wait_for_wmem, but change to wait for
457  * CAIF flow-on and sock_writable.
458  */
459 static long caif_wait_for_flow_on(struct caifsock *cf_sk,
460 				  int wait_writeable, long timeo, int *err)
461 {
462 	struct sock *sk = &cf_sk->sk;
463 	DEFINE_WAIT(wait);
464 	for (;;) {
465 		*err = 0;
466 		if (tx_flow_is_on(cf_sk) &&
467 			(!wait_writeable || sock_writeable(&cf_sk->sk)))
468 			break;
469 		*err = -ETIMEDOUT;
470 		if (!timeo)
471 			break;
472 		*err = -ERESTARTSYS;
473 		if (signal_pending(current))
474 			break;
475 		prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
476 		*err = -ECONNRESET;
477 		if (sk->sk_shutdown & SHUTDOWN_MASK)
478 			break;
479 		*err = -sk->sk_err;
480 		if (sk->sk_err)
481 			break;
482 		*err = -EPIPE;
483 		if (cf_sk->sk.sk_state != CAIF_CONNECTED)
484 			break;
485 		timeo = schedule_timeout(timeo);
486 	}
487 	finish_wait(sk_sleep(sk), &wait);
488 	return timeo;
489 }
490 
491 /*
492  * Transmit a SKB. The device may temporarily request re-transmission
493  * by returning EAGAIN.
494  */
495 static int transmit_skb(struct sk_buff *skb, struct caifsock *cf_sk,
496 			int noblock, long timeo)
497 {
498 	struct cfpkt *pkt;
499 
500 	pkt = cfpkt_fromnative(CAIF_DIR_OUT, skb);
501 	memset(skb->cb, 0, sizeof(struct caif_payload_info));
502 	cfpkt_set_prio(pkt, cf_sk->sk.sk_priority);
503 
504 	if (cf_sk->layer.dn == NULL) {
505 		kfree_skb(skb);
506 		return -EINVAL;
507 	}
508 
509 	return cf_sk->layer.dn->transmit(cf_sk->layer.dn, pkt);
510 }
511 
512 /* Copied from af_unix:unix_dgram_sendmsg, and adapted to CAIF */
513 static int caif_seqpkt_sendmsg(struct socket *sock, struct msghdr *msg,
514 			       size_t len)
515 {
516 	struct sock *sk = sock->sk;
517 	struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
518 	int buffer_size;
519 	int ret = 0;
520 	struct sk_buff *skb = NULL;
521 	int noblock;
522 	long timeo;
523 	caif_assert(cf_sk);
524 	ret = sock_error(sk);
525 	if (ret)
526 		goto err;
527 
528 	ret = -EOPNOTSUPP;
529 	if (msg->msg_flags&MSG_OOB)
530 		goto err;
531 
532 	ret = -EOPNOTSUPP;
533 	if (msg->msg_namelen)
534 		goto err;
535 
536 	ret = -EINVAL;
537 	if (unlikely(msg->msg_iter.nr_segs == 0) ||
538 	    unlikely(msg->msg_iter.iov->iov_base == NULL))
539 		goto err;
540 	noblock = msg->msg_flags & MSG_DONTWAIT;
541 
542 	timeo = sock_sndtimeo(sk, noblock);
543 	timeo = caif_wait_for_flow_on(container_of(sk, struct caifsock, sk),
544 				1, timeo, &ret);
545 
546 	if (ret)
547 		goto err;
548 	ret = -EPIPE;
549 	if (cf_sk->sk.sk_state != CAIF_CONNECTED ||
550 		sock_flag(sk, SOCK_DEAD) ||
551 		(sk->sk_shutdown & RCV_SHUTDOWN))
552 		goto err;
553 
554 	/* Error if trying to write more than maximum frame size. */
555 	ret = -EMSGSIZE;
556 	if (len > cf_sk->maxframe && cf_sk->sk.sk_protocol != CAIFPROTO_RFM)
557 		goto err;
558 
559 	buffer_size = len + cf_sk->headroom + cf_sk->tailroom;
560 
561 	ret = -ENOMEM;
562 	skb = sock_alloc_send_skb(sk, buffer_size, noblock, &ret);
563 
564 	if (!skb || skb_tailroom(skb) < buffer_size)
565 		goto err;
566 
567 	skb_reserve(skb, cf_sk->headroom);
568 
569 	ret = memcpy_from_msg(skb_put(skb, len), msg, len);
570 
571 	if (ret)
572 		goto err;
573 	ret = transmit_skb(skb, cf_sk, noblock, timeo);
574 	if (ret < 0)
575 		/* skb is already freed */
576 		return ret;
577 
578 	return len;
579 err:
580 	kfree_skb(skb);
581 	return ret;
582 }
583 
584 /*
585  * Copied from unix_stream_sendmsg and adapted to CAIF:
586  * Changed removed permission handling and added waiting for flow on
587  * and other minor adaptations.
588  */
589 static int caif_stream_sendmsg(struct socket *sock, struct msghdr *msg,
590 			       size_t len)
591 {
592 	struct sock *sk = sock->sk;
593 	struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
594 	int err, size;
595 	struct sk_buff *skb;
596 	int sent = 0;
597 	long timeo;
598 
599 	err = -EOPNOTSUPP;
600 	if (unlikely(msg->msg_flags&MSG_OOB))
601 		goto out_err;
602 
603 	if (unlikely(msg->msg_namelen))
604 		goto out_err;
605 
606 	timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
607 	timeo = caif_wait_for_flow_on(cf_sk, 1, timeo, &err);
608 
609 	if (unlikely(sk->sk_shutdown & SEND_SHUTDOWN))
610 		goto pipe_err;
611 
612 	while (sent < len) {
613 
614 		size = len-sent;
615 
616 		if (size > cf_sk->maxframe)
617 			size = cf_sk->maxframe;
618 
619 		/* If size is more than half of sndbuf, chop up message */
620 		if (size > ((sk->sk_sndbuf >> 1) - 64))
621 			size = (sk->sk_sndbuf >> 1) - 64;
622 
623 		if (size > SKB_MAX_ALLOC)
624 			size = SKB_MAX_ALLOC;
625 
626 		skb = sock_alloc_send_skb(sk,
627 					size + cf_sk->headroom +
628 					cf_sk->tailroom,
629 					msg->msg_flags&MSG_DONTWAIT,
630 					&err);
631 		if (skb == NULL)
632 			goto out_err;
633 
634 		skb_reserve(skb, cf_sk->headroom);
635 		/*
636 		 *	If you pass two values to the sock_alloc_send_skb
637 		 *	it tries to grab the large buffer with GFP_NOFS
638 		 *	(which can fail easily), and if it fails grab the
639 		 *	fallback size buffer which is under a page and will
640 		 *	succeed. [Alan]
641 		 */
642 		size = min_t(int, size, skb_tailroom(skb));
643 
644 		err = memcpy_from_msg(skb_put(skb, size), msg, size);
645 		if (err) {
646 			kfree_skb(skb);
647 			goto out_err;
648 		}
649 		err = transmit_skb(skb, cf_sk,
650 				msg->msg_flags&MSG_DONTWAIT, timeo);
651 		if (err < 0)
652 			/* skb is already freed */
653 			goto pipe_err;
654 
655 		sent += size;
656 	}
657 
658 	return sent;
659 
660 pipe_err:
661 	if (sent == 0 && !(msg->msg_flags&MSG_NOSIGNAL))
662 		send_sig(SIGPIPE, current, 0);
663 	err = -EPIPE;
664 out_err:
665 	return sent ? : err;
666 }
667 
668 static int setsockopt(struct socket *sock, int lvl, int opt, sockptr_t ov,
669 		unsigned int ol)
670 {
671 	struct sock *sk = sock->sk;
672 	struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
673 	int linksel;
674 
675 	if (cf_sk->sk.sk_socket->state != SS_UNCONNECTED)
676 		return -ENOPROTOOPT;
677 
678 	switch (opt) {
679 	case CAIFSO_LINK_SELECT:
680 		if (ol < sizeof(int))
681 			return -EINVAL;
682 		if (lvl != SOL_CAIF)
683 			goto bad_sol;
684 		if (copy_from_sockptr(&linksel, ov, sizeof(int)))
685 			return -EINVAL;
686 		lock_sock(&(cf_sk->sk));
687 		cf_sk->conn_req.link_selector = linksel;
688 		release_sock(&cf_sk->sk);
689 		return 0;
690 
691 	case CAIFSO_REQ_PARAM:
692 		if (lvl != SOL_CAIF)
693 			goto bad_sol;
694 		if (cf_sk->sk.sk_protocol != CAIFPROTO_UTIL)
695 			return -ENOPROTOOPT;
696 		lock_sock(&(cf_sk->sk));
697 		if (ol > sizeof(cf_sk->conn_req.param.data) ||
698 		    copy_from_sockptr(&cf_sk->conn_req.param.data, ov, ol)) {
699 			release_sock(&cf_sk->sk);
700 			return -EINVAL;
701 		}
702 		cf_sk->conn_req.param.size = ol;
703 		release_sock(&cf_sk->sk);
704 		return 0;
705 
706 	default:
707 		return -ENOPROTOOPT;
708 	}
709 
710 	return 0;
711 bad_sol:
712 	return -ENOPROTOOPT;
713 
714 }
715 
716 /*
717  * caif_connect() - Connect a CAIF Socket
718  * Copied and modified af_irda.c:irda_connect().
719  *
720  * Note : by consulting "errno", the user space caller may learn the cause
721  * of the failure. Most of them are visible in the function, others may come
722  * from subroutines called and are listed here :
723  *  o -EAFNOSUPPORT: bad socket family or type.
724  *  o -ESOCKTNOSUPPORT: bad socket type or protocol
725  *  o -EINVAL: bad socket address, or CAIF link type
726  *  o -ECONNREFUSED: remote end refused the connection.
727  *  o -EINPROGRESS: connect request sent but timed out (or non-blocking)
728  *  o -EISCONN: already connected.
729  *  o -ETIMEDOUT: Connection timed out (send timeout)
730  *  o -ENODEV: No link layer to send request
731  *  o -ECONNRESET: Received Shutdown indication or lost link layer
732  *  o -ENOMEM: Out of memory
733  *
734  *  State Strategy:
735  *  o sk_state: holds the CAIF_* protocol state, it's updated by
736  *	caif_ctrl_cb.
737  *  o sock->state: holds the SS_* socket state and is updated by connect and
738  *	disconnect.
739  */
740 static int caif_connect(struct socket *sock, struct sockaddr *uaddr,
741 			int addr_len, int flags)
742 {
743 	struct sock *sk = sock->sk;
744 	struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
745 	long timeo;
746 	int err;
747 	int ifindex, headroom, tailroom;
748 	unsigned int mtu;
749 	struct net_device *dev;
750 
751 	lock_sock(sk);
752 
753 	err = -EINVAL;
754 	if (addr_len < offsetofend(struct sockaddr, sa_family))
755 		goto out;
756 
757 	err = -EAFNOSUPPORT;
758 	if (uaddr->sa_family != AF_CAIF)
759 		goto out;
760 
761 	switch (sock->state) {
762 	case SS_UNCONNECTED:
763 		/* Normal case, a fresh connect */
764 		caif_assert(sk->sk_state == CAIF_DISCONNECTED);
765 		break;
766 	case SS_CONNECTING:
767 		switch (sk->sk_state) {
768 		case CAIF_CONNECTED:
769 			sock->state = SS_CONNECTED;
770 			err = -EISCONN;
771 			goto out;
772 		case CAIF_DISCONNECTED:
773 			/* Reconnect allowed */
774 			break;
775 		case CAIF_CONNECTING:
776 			err = -EALREADY;
777 			if (flags & O_NONBLOCK)
778 				goto out;
779 			goto wait_connect;
780 		}
781 		break;
782 	case SS_CONNECTED:
783 		caif_assert(sk->sk_state == CAIF_CONNECTED ||
784 				sk->sk_state == CAIF_DISCONNECTED);
785 		if (sk->sk_shutdown & SHUTDOWN_MASK) {
786 			/* Allow re-connect after SHUTDOWN_IND */
787 			caif_disconnect_client(sock_net(sk), &cf_sk->layer);
788 			caif_free_client(&cf_sk->layer);
789 			break;
790 		}
791 		/* No reconnect on a seqpacket socket */
792 		err = -EISCONN;
793 		goto out;
794 	case SS_DISCONNECTING:
795 	case SS_FREE:
796 		caif_assert(1); /*Should never happen */
797 		break;
798 	}
799 	sk->sk_state = CAIF_DISCONNECTED;
800 	sock->state = SS_UNCONNECTED;
801 	sk_stream_kill_queues(&cf_sk->sk);
802 
803 	err = -EINVAL;
804 	if (addr_len != sizeof(struct sockaddr_caif))
805 		goto out;
806 
807 	memcpy(&cf_sk->conn_req.sockaddr, uaddr,
808 		sizeof(struct sockaddr_caif));
809 
810 	/* Move to connecting socket, start sending Connect Requests */
811 	sock->state = SS_CONNECTING;
812 	sk->sk_state = CAIF_CONNECTING;
813 
814 	/* Check priority value comming from socket */
815 	/* if priority value is out of range it will be ajusted */
816 	if (cf_sk->sk.sk_priority > CAIF_PRIO_MAX)
817 		cf_sk->conn_req.priority = CAIF_PRIO_MAX;
818 	else if (cf_sk->sk.sk_priority < CAIF_PRIO_MIN)
819 		cf_sk->conn_req.priority = CAIF_PRIO_MIN;
820 	else
821 		cf_sk->conn_req.priority = cf_sk->sk.sk_priority;
822 
823 	/*ifindex = id of the interface.*/
824 	cf_sk->conn_req.ifindex = cf_sk->sk.sk_bound_dev_if;
825 
826 	cf_sk->layer.receive = caif_sktrecv_cb;
827 
828 	err = caif_connect_client(sock_net(sk), &cf_sk->conn_req,
829 				&cf_sk->layer, &ifindex, &headroom, &tailroom);
830 
831 	if (err < 0) {
832 		cf_sk->sk.sk_socket->state = SS_UNCONNECTED;
833 		cf_sk->sk.sk_state = CAIF_DISCONNECTED;
834 		goto out;
835 	}
836 
837 	err = -ENODEV;
838 	rcu_read_lock();
839 	dev = dev_get_by_index_rcu(sock_net(sk), ifindex);
840 	if (!dev) {
841 		rcu_read_unlock();
842 		goto out;
843 	}
844 	cf_sk->headroom = LL_RESERVED_SPACE_EXTRA(dev, headroom);
845 	mtu = dev->mtu;
846 	rcu_read_unlock();
847 
848 	cf_sk->tailroom = tailroom;
849 	cf_sk->maxframe = mtu - (headroom + tailroom);
850 	if (cf_sk->maxframe < 1) {
851 		pr_warn("CAIF Interface MTU too small (%d)\n", dev->mtu);
852 		err = -ENODEV;
853 		goto out;
854 	}
855 
856 	err = -EINPROGRESS;
857 wait_connect:
858 
859 	if (sk->sk_state != CAIF_CONNECTED && (flags & O_NONBLOCK))
860 		goto out;
861 
862 	timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
863 
864 	release_sock(sk);
865 	err = -ERESTARTSYS;
866 	timeo = wait_event_interruptible_timeout(*sk_sleep(sk),
867 			sk->sk_state != CAIF_CONNECTING,
868 			timeo);
869 	lock_sock(sk);
870 	if (timeo < 0)
871 		goto out; /* -ERESTARTSYS */
872 
873 	err = -ETIMEDOUT;
874 	if (timeo == 0 && sk->sk_state != CAIF_CONNECTED)
875 		goto out;
876 	if (sk->sk_state != CAIF_CONNECTED) {
877 		sock->state = SS_UNCONNECTED;
878 		err = sock_error(sk);
879 		if (!err)
880 			err = -ECONNREFUSED;
881 		goto out;
882 	}
883 	sock->state = SS_CONNECTED;
884 	err = 0;
885 out:
886 	release_sock(sk);
887 	return err;
888 }
889 
890 /*
891  * caif_release() - Disconnect a CAIF Socket
892  * Copied and modified af_irda.c:irda_release().
893  */
894 static int caif_release(struct socket *sock)
895 {
896 	struct sock *sk = sock->sk;
897 	struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
898 
899 	if (!sk)
900 		return 0;
901 
902 	set_tx_flow_off(cf_sk);
903 
904 	/*
905 	 * Ensure that packets are not queued after this point in time.
906 	 * caif_queue_rcv_skb checks SOCK_DEAD holding the queue lock,
907 	 * this ensures no packets when sock is dead.
908 	 */
909 	spin_lock_bh(&sk->sk_receive_queue.lock);
910 	sock_set_flag(sk, SOCK_DEAD);
911 	spin_unlock_bh(&sk->sk_receive_queue.lock);
912 	sock->sk = NULL;
913 
914 	WARN_ON(IS_ERR(cf_sk->debugfs_socket_dir));
915 	debugfs_remove_recursive(cf_sk->debugfs_socket_dir);
916 
917 	lock_sock(&(cf_sk->sk));
918 	sk->sk_state = CAIF_DISCONNECTED;
919 	sk->sk_shutdown = SHUTDOWN_MASK;
920 
921 	caif_disconnect_client(sock_net(sk), &cf_sk->layer);
922 	cf_sk->sk.sk_socket->state = SS_DISCONNECTING;
923 	wake_up_interruptible_poll(sk_sleep(sk), EPOLLERR|EPOLLHUP);
924 
925 	sock_orphan(sk);
926 	sk_stream_kill_queues(&cf_sk->sk);
927 	release_sock(sk);
928 	sock_put(sk);
929 	return 0;
930 }
931 
932 /* Copied from af_unix.c:unix_poll(), added CAIF tx_flow handling */
933 static __poll_t caif_poll(struct file *file,
934 			      struct socket *sock, poll_table *wait)
935 {
936 	struct sock *sk = sock->sk;
937 	__poll_t mask;
938 	struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
939 
940 	sock_poll_wait(file, sock, wait);
941 	mask = 0;
942 
943 	/* exceptional events? */
944 	if (sk->sk_err)
945 		mask |= EPOLLERR;
946 	if (sk->sk_shutdown == SHUTDOWN_MASK)
947 		mask |= EPOLLHUP;
948 	if (sk->sk_shutdown & RCV_SHUTDOWN)
949 		mask |= EPOLLRDHUP;
950 
951 	/* readable? */
952 	if (!skb_queue_empty_lockless(&sk->sk_receive_queue) ||
953 		(sk->sk_shutdown & RCV_SHUTDOWN))
954 		mask |= EPOLLIN | EPOLLRDNORM;
955 
956 	/*
957 	 * we set writable also when the other side has shut down the
958 	 * connection. This prevents stuck sockets.
959 	 */
960 	if (sock_writeable(sk) && tx_flow_is_on(cf_sk))
961 		mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
962 
963 	return mask;
964 }
965 
966 static const struct proto_ops caif_seqpacket_ops = {
967 	.family = PF_CAIF,
968 	.owner = THIS_MODULE,
969 	.release = caif_release,
970 	.bind = sock_no_bind,
971 	.connect = caif_connect,
972 	.socketpair = sock_no_socketpair,
973 	.accept = sock_no_accept,
974 	.getname = sock_no_getname,
975 	.poll = caif_poll,
976 	.ioctl = sock_no_ioctl,
977 	.listen = sock_no_listen,
978 	.shutdown = sock_no_shutdown,
979 	.setsockopt = setsockopt,
980 	.sendmsg = caif_seqpkt_sendmsg,
981 	.recvmsg = caif_seqpkt_recvmsg,
982 	.mmap = sock_no_mmap,
983 	.sendpage = sock_no_sendpage,
984 };
985 
986 static const struct proto_ops caif_stream_ops = {
987 	.family = PF_CAIF,
988 	.owner = THIS_MODULE,
989 	.release = caif_release,
990 	.bind = sock_no_bind,
991 	.connect = caif_connect,
992 	.socketpair = sock_no_socketpair,
993 	.accept = sock_no_accept,
994 	.getname = sock_no_getname,
995 	.poll = caif_poll,
996 	.ioctl = sock_no_ioctl,
997 	.listen = sock_no_listen,
998 	.shutdown = sock_no_shutdown,
999 	.setsockopt = setsockopt,
1000 	.sendmsg = caif_stream_sendmsg,
1001 	.recvmsg = caif_stream_recvmsg,
1002 	.mmap = sock_no_mmap,
1003 	.sendpage = sock_no_sendpage,
1004 };
1005 
1006 /* This function is called when a socket is finally destroyed. */
1007 static void caif_sock_destructor(struct sock *sk)
1008 {
1009 	struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
1010 	caif_assert(!refcount_read(&sk->sk_wmem_alloc));
1011 	caif_assert(sk_unhashed(sk));
1012 	caif_assert(!sk->sk_socket);
1013 	if (!sock_flag(sk, SOCK_DEAD)) {
1014 		pr_debug("Attempt to release alive CAIF socket: %p\n", sk);
1015 		return;
1016 	}
1017 	sk_stream_kill_queues(&cf_sk->sk);
1018 	caif_free_client(&cf_sk->layer);
1019 }
1020 
1021 static int caif_create(struct net *net, struct socket *sock, int protocol,
1022 		       int kern)
1023 {
1024 	struct sock *sk = NULL;
1025 	struct caifsock *cf_sk = NULL;
1026 	static struct proto prot = {.name = "PF_CAIF",
1027 		.owner = THIS_MODULE,
1028 		.obj_size = sizeof(struct caifsock),
1029 		.useroffset = offsetof(struct caifsock, conn_req.param),
1030 		.usersize = sizeof_field(struct caifsock, conn_req.param)
1031 	};
1032 
1033 	if (!capable(CAP_SYS_ADMIN) && !capable(CAP_NET_ADMIN))
1034 		return -EPERM;
1035 	/*
1036 	 * The sock->type specifies the socket type to use.
1037 	 * The CAIF socket is a packet stream in the sense
1038 	 * that it is packet based. CAIF trusts the reliability
1039 	 * of the link, no resending is implemented.
1040 	 */
1041 	if (sock->type == SOCK_SEQPACKET)
1042 		sock->ops = &caif_seqpacket_ops;
1043 	else if (sock->type == SOCK_STREAM)
1044 		sock->ops = &caif_stream_ops;
1045 	else
1046 		return -ESOCKTNOSUPPORT;
1047 
1048 	if (protocol < 0 || protocol >= CAIFPROTO_MAX)
1049 		return -EPROTONOSUPPORT;
1050 	/*
1051 	 * Set the socket state to unconnected.	 The socket state
1052 	 * is really not used at all in the net/core or socket.c but the
1053 	 * initialization makes sure that sock->state is not uninitialized.
1054 	 */
1055 	sk = sk_alloc(net, PF_CAIF, GFP_KERNEL, &prot, kern);
1056 	if (!sk)
1057 		return -ENOMEM;
1058 
1059 	cf_sk = container_of(sk, struct caifsock, sk);
1060 
1061 	/* Store the protocol */
1062 	sk->sk_protocol = (unsigned char) protocol;
1063 
1064 	/* Initialize default priority for well-known cases */
1065 	switch (protocol) {
1066 	case CAIFPROTO_AT:
1067 		sk->sk_priority = TC_PRIO_CONTROL;
1068 		break;
1069 	case CAIFPROTO_RFM:
1070 		sk->sk_priority = TC_PRIO_INTERACTIVE_BULK;
1071 		break;
1072 	default:
1073 		sk->sk_priority = TC_PRIO_BESTEFFORT;
1074 	}
1075 
1076 	/*
1077 	 * Lock in order to try to stop someone from opening the socket
1078 	 * too early.
1079 	 */
1080 	lock_sock(&(cf_sk->sk));
1081 
1082 	/* Initialize the nozero default sock structure data. */
1083 	sock_init_data(sock, sk);
1084 	sk->sk_destruct = caif_sock_destructor;
1085 
1086 	mutex_init(&cf_sk->readlock); /* single task reading lock */
1087 	cf_sk->layer.ctrlcmd = caif_ctrl_cb;
1088 	cf_sk->sk.sk_socket->state = SS_UNCONNECTED;
1089 	cf_sk->sk.sk_state = CAIF_DISCONNECTED;
1090 
1091 	set_tx_flow_off(cf_sk);
1092 	set_rx_flow_on(cf_sk);
1093 
1094 	/* Set default options on configuration */
1095 	cf_sk->conn_req.link_selector = CAIF_LINK_LOW_LATENCY;
1096 	cf_sk->conn_req.protocol = protocol;
1097 	release_sock(&cf_sk->sk);
1098 	return 0;
1099 }
1100 
1101 
1102 static const struct net_proto_family caif_family_ops = {
1103 	.family = PF_CAIF,
1104 	.create = caif_create,
1105 	.owner = THIS_MODULE,
1106 };
1107 
1108 static int __init caif_sktinit_module(void)
1109 {
1110 	return sock_register(&caif_family_ops);
1111 }
1112 
1113 static void __exit caif_sktexit_module(void)
1114 {
1115 	sock_unregister(PF_CAIF);
1116 }
1117 module_init(caif_sktinit_module);
1118 module_exit(caif_sktexit_module);
1119