xref: /openbmc/linux/net/caif/caif_socket.c (revision 71de0a05)
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 	noblock = msg->msg_flags & MSG_DONTWAIT;
537 
538 	timeo = sock_sndtimeo(sk, noblock);
539 	timeo = caif_wait_for_flow_on(container_of(sk, struct caifsock, sk),
540 				1, timeo, &ret);
541 
542 	if (ret)
543 		goto err;
544 	ret = -EPIPE;
545 	if (cf_sk->sk.sk_state != CAIF_CONNECTED ||
546 		sock_flag(sk, SOCK_DEAD) ||
547 		(sk->sk_shutdown & RCV_SHUTDOWN))
548 		goto err;
549 
550 	/* Error if trying to write more than maximum frame size. */
551 	ret = -EMSGSIZE;
552 	if (len > cf_sk->maxframe && cf_sk->sk.sk_protocol != CAIFPROTO_RFM)
553 		goto err;
554 
555 	buffer_size = len + cf_sk->headroom + cf_sk->tailroom;
556 
557 	ret = -ENOMEM;
558 	skb = sock_alloc_send_skb(sk, buffer_size, noblock, &ret);
559 
560 	if (!skb || skb_tailroom(skb) < buffer_size)
561 		goto err;
562 
563 	skb_reserve(skb, cf_sk->headroom);
564 
565 	ret = memcpy_from_msg(skb_put(skb, len), msg, len);
566 
567 	if (ret)
568 		goto err;
569 	ret = transmit_skb(skb, cf_sk, noblock, timeo);
570 	if (ret < 0)
571 		/* skb is already freed */
572 		return ret;
573 
574 	return len;
575 err:
576 	kfree_skb(skb);
577 	return ret;
578 }
579 
580 /*
581  * Copied from unix_stream_sendmsg and adapted to CAIF:
582  * Changed removed permission handling and added waiting for flow on
583  * and other minor adaptations.
584  */
585 static int caif_stream_sendmsg(struct socket *sock, struct msghdr *msg,
586 			       size_t len)
587 {
588 	struct sock *sk = sock->sk;
589 	struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
590 	int err, size;
591 	struct sk_buff *skb;
592 	int sent = 0;
593 	long timeo;
594 
595 	err = -EOPNOTSUPP;
596 	if (unlikely(msg->msg_flags&MSG_OOB))
597 		goto out_err;
598 
599 	if (unlikely(msg->msg_namelen))
600 		goto out_err;
601 
602 	timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
603 	timeo = caif_wait_for_flow_on(cf_sk, 1, timeo, &err);
604 
605 	if (unlikely(sk->sk_shutdown & SEND_SHUTDOWN))
606 		goto pipe_err;
607 
608 	while (sent < len) {
609 
610 		size = len-sent;
611 
612 		if (size > cf_sk->maxframe)
613 			size = cf_sk->maxframe;
614 
615 		/* If size is more than half of sndbuf, chop up message */
616 		if (size > ((sk->sk_sndbuf >> 1) - 64))
617 			size = (sk->sk_sndbuf >> 1) - 64;
618 
619 		if (size > SKB_MAX_ALLOC)
620 			size = SKB_MAX_ALLOC;
621 
622 		skb = sock_alloc_send_skb(sk,
623 					size + cf_sk->headroom +
624 					cf_sk->tailroom,
625 					msg->msg_flags&MSG_DONTWAIT,
626 					&err);
627 		if (skb == NULL)
628 			goto out_err;
629 
630 		skb_reserve(skb, cf_sk->headroom);
631 		/*
632 		 *	If you pass two values to the sock_alloc_send_skb
633 		 *	it tries to grab the large buffer with GFP_NOFS
634 		 *	(which can fail easily), and if it fails grab the
635 		 *	fallback size buffer which is under a page and will
636 		 *	succeed. [Alan]
637 		 */
638 		size = min_t(int, size, skb_tailroom(skb));
639 
640 		err = memcpy_from_msg(skb_put(skb, size), msg, size);
641 		if (err) {
642 			kfree_skb(skb);
643 			goto out_err;
644 		}
645 		err = transmit_skb(skb, cf_sk,
646 				msg->msg_flags&MSG_DONTWAIT, timeo);
647 		if (err < 0)
648 			/* skb is already freed */
649 			goto pipe_err;
650 
651 		sent += size;
652 	}
653 
654 	return sent;
655 
656 pipe_err:
657 	if (sent == 0 && !(msg->msg_flags&MSG_NOSIGNAL))
658 		send_sig(SIGPIPE, current, 0);
659 	err = -EPIPE;
660 out_err:
661 	return sent ? : err;
662 }
663 
664 static int setsockopt(struct socket *sock, int lvl, int opt, sockptr_t ov,
665 		unsigned int ol)
666 {
667 	struct sock *sk = sock->sk;
668 	struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
669 	int linksel;
670 
671 	if (cf_sk->sk.sk_socket->state != SS_UNCONNECTED)
672 		return -ENOPROTOOPT;
673 
674 	switch (opt) {
675 	case CAIFSO_LINK_SELECT:
676 		if (ol < sizeof(int))
677 			return -EINVAL;
678 		if (lvl != SOL_CAIF)
679 			goto bad_sol;
680 		if (copy_from_sockptr(&linksel, ov, sizeof(int)))
681 			return -EINVAL;
682 		lock_sock(&(cf_sk->sk));
683 		cf_sk->conn_req.link_selector = linksel;
684 		release_sock(&cf_sk->sk);
685 		return 0;
686 
687 	case CAIFSO_REQ_PARAM:
688 		if (lvl != SOL_CAIF)
689 			goto bad_sol;
690 		if (cf_sk->sk.sk_protocol != CAIFPROTO_UTIL)
691 			return -ENOPROTOOPT;
692 		lock_sock(&(cf_sk->sk));
693 		if (ol > sizeof(cf_sk->conn_req.param.data) ||
694 		    copy_from_sockptr(&cf_sk->conn_req.param.data, ov, ol)) {
695 			release_sock(&cf_sk->sk);
696 			return -EINVAL;
697 		}
698 		cf_sk->conn_req.param.size = ol;
699 		release_sock(&cf_sk->sk);
700 		return 0;
701 
702 	default:
703 		return -ENOPROTOOPT;
704 	}
705 
706 	return 0;
707 bad_sol:
708 	return -ENOPROTOOPT;
709 
710 }
711 
712 /*
713  * caif_connect() - Connect a CAIF Socket
714  * Copied and modified af_irda.c:irda_connect().
715  *
716  * Note : by consulting "errno", the user space caller may learn the cause
717  * of the failure. Most of them are visible in the function, others may come
718  * from subroutines called and are listed here :
719  *  o -EAFNOSUPPORT: bad socket family or type.
720  *  o -ESOCKTNOSUPPORT: bad socket type or protocol
721  *  o -EINVAL: bad socket address, or CAIF link type
722  *  o -ECONNREFUSED: remote end refused the connection.
723  *  o -EINPROGRESS: connect request sent but timed out (or non-blocking)
724  *  o -EISCONN: already connected.
725  *  o -ETIMEDOUT: Connection timed out (send timeout)
726  *  o -ENODEV: No link layer to send request
727  *  o -ECONNRESET: Received Shutdown indication or lost link layer
728  *  o -ENOMEM: Out of memory
729  *
730  *  State Strategy:
731  *  o sk_state: holds the CAIF_* protocol state, it's updated by
732  *	caif_ctrl_cb.
733  *  o sock->state: holds the SS_* socket state and is updated by connect and
734  *	disconnect.
735  */
736 static int caif_connect(struct socket *sock, struct sockaddr *uaddr,
737 			int addr_len, int flags)
738 {
739 	struct sock *sk = sock->sk;
740 	struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
741 	long timeo;
742 	int err;
743 	int ifindex, headroom, tailroom;
744 	unsigned int mtu;
745 	struct net_device *dev;
746 
747 	lock_sock(sk);
748 
749 	err = -EINVAL;
750 	if (addr_len < offsetofend(struct sockaddr, sa_family))
751 		goto out;
752 
753 	err = -EAFNOSUPPORT;
754 	if (uaddr->sa_family != AF_CAIF)
755 		goto out;
756 
757 	switch (sock->state) {
758 	case SS_UNCONNECTED:
759 		/* Normal case, a fresh connect */
760 		caif_assert(sk->sk_state == CAIF_DISCONNECTED);
761 		break;
762 	case SS_CONNECTING:
763 		switch (sk->sk_state) {
764 		case CAIF_CONNECTED:
765 			sock->state = SS_CONNECTED;
766 			err = -EISCONN;
767 			goto out;
768 		case CAIF_DISCONNECTED:
769 			/* Reconnect allowed */
770 			break;
771 		case CAIF_CONNECTING:
772 			err = -EALREADY;
773 			if (flags & O_NONBLOCK)
774 				goto out;
775 			goto wait_connect;
776 		}
777 		break;
778 	case SS_CONNECTED:
779 		caif_assert(sk->sk_state == CAIF_CONNECTED ||
780 				sk->sk_state == CAIF_DISCONNECTED);
781 		if (sk->sk_shutdown & SHUTDOWN_MASK) {
782 			/* Allow re-connect after SHUTDOWN_IND */
783 			caif_disconnect_client(sock_net(sk), &cf_sk->layer);
784 			caif_free_client(&cf_sk->layer);
785 			break;
786 		}
787 		/* No reconnect on a seqpacket socket */
788 		err = -EISCONN;
789 		goto out;
790 	case SS_DISCONNECTING:
791 	case SS_FREE:
792 		caif_assert(1); /*Should never happen */
793 		break;
794 	}
795 	sk->sk_state = CAIF_DISCONNECTED;
796 	sock->state = SS_UNCONNECTED;
797 	sk_stream_kill_queues(&cf_sk->sk);
798 
799 	err = -EINVAL;
800 	if (addr_len != sizeof(struct sockaddr_caif))
801 		goto out;
802 
803 	memcpy(&cf_sk->conn_req.sockaddr, uaddr,
804 		sizeof(struct sockaddr_caif));
805 
806 	/* Move to connecting socket, start sending Connect Requests */
807 	sock->state = SS_CONNECTING;
808 	sk->sk_state = CAIF_CONNECTING;
809 
810 	/* Check priority value comming from socket */
811 	/* if priority value is out of range it will be ajusted */
812 	if (cf_sk->sk.sk_priority > CAIF_PRIO_MAX)
813 		cf_sk->conn_req.priority = CAIF_PRIO_MAX;
814 	else if (cf_sk->sk.sk_priority < CAIF_PRIO_MIN)
815 		cf_sk->conn_req.priority = CAIF_PRIO_MIN;
816 	else
817 		cf_sk->conn_req.priority = cf_sk->sk.sk_priority;
818 
819 	/*ifindex = id of the interface.*/
820 	cf_sk->conn_req.ifindex = cf_sk->sk.sk_bound_dev_if;
821 
822 	cf_sk->layer.receive = caif_sktrecv_cb;
823 
824 	err = caif_connect_client(sock_net(sk), &cf_sk->conn_req,
825 				&cf_sk->layer, &ifindex, &headroom, &tailroom);
826 
827 	if (err < 0) {
828 		cf_sk->sk.sk_socket->state = SS_UNCONNECTED;
829 		cf_sk->sk.sk_state = CAIF_DISCONNECTED;
830 		goto out;
831 	}
832 
833 	err = -ENODEV;
834 	rcu_read_lock();
835 	dev = dev_get_by_index_rcu(sock_net(sk), ifindex);
836 	if (!dev) {
837 		rcu_read_unlock();
838 		goto out;
839 	}
840 	cf_sk->headroom = LL_RESERVED_SPACE_EXTRA(dev, headroom);
841 	mtu = dev->mtu;
842 	rcu_read_unlock();
843 
844 	cf_sk->tailroom = tailroom;
845 	cf_sk->maxframe = mtu - (headroom + tailroom);
846 	if (cf_sk->maxframe < 1) {
847 		pr_warn("CAIF Interface MTU too small (%d)\n", dev->mtu);
848 		err = -ENODEV;
849 		goto out;
850 	}
851 
852 	err = -EINPROGRESS;
853 wait_connect:
854 
855 	if (sk->sk_state != CAIF_CONNECTED && (flags & O_NONBLOCK))
856 		goto out;
857 
858 	timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
859 
860 	release_sock(sk);
861 	err = -ERESTARTSYS;
862 	timeo = wait_event_interruptible_timeout(*sk_sleep(sk),
863 			sk->sk_state != CAIF_CONNECTING,
864 			timeo);
865 	lock_sock(sk);
866 	if (timeo < 0)
867 		goto out; /* -ERESTARTSYS */
868 
869 	err = -ETIMEDOUT;
870 	if (timeo == 0 && sk->sk_state != CAIF_CONNECTED)
871 		goto out;
872 	if (sk->sk_state != CAIF_CONNECTED) {
873 		sock->state = SS_UNCONNECTED;
874 		err = sock_error(sk);
875 		if (!err)
876 			err = -ECONNREFUSED;
877 		goto out;
878 	}
879 	sock->state = SS_CONNECTED;
880 	err = 0;
881 out:
882 	release_sock(sk);
883 	return err;
884 }
885 
886 /*
887  * caif_release() - Disconnect a CAIF Socket
888  * Copied and modified af_irda.c:irda_release().
889  */
890 static int caif_release(struct socket *sock)
891 {
892 	struct sock *sk = sock->sk;
893 	struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
894 
895 	if (!sk)
896 		return 0;
897 
898 	set_tx_flow_off(cf_sk);
899 
900 	/*
901 	 * Ensure that packets are not queued after this point in time.
902 	 * caif_queue_rcv_skb checks SOCK_DEAD holding the queue lock,
903 	 * this ensures no packets when sock is dead.
904 	 */
905 	spin_lock_bh(&sk->sk_receive_queue.lock);
906 	sock_set_flag(sk, SOCK_DEAD);
907 	spin_unlock_bh(&sk->sk_receive_queue.lock);
908 	sock->sk = NULL;
909 
910 	WARN_ON(IS_ERR(cf_sk->debugfs_socket_dir));
911 	debugfs_remove_recursive(cf_sk->debugfs_socket_dir);
912 
913 	lock_sock(&(cf_sk->sk));
914 	sk->sk_state = CAIF_DISCONNECTED;
915 	sk->sk_shutdown = SHUTDOWN_MASK;
916 
917 	caif_disconnect_client(sock_net(sk), &cf_sk->layer);
918 	cf_sk->sk.sk_socket->state = SS_DISCONNECTING;
919 	wake_up_interruptible_poll(sk_sleep(sk), EPOLLERR|EPOLLHUP);
920 
921 	sock_orphan(sk);
922 	sk_stream_kill_queues(&cf_sk->sk);
923 	release_sock(sk);
924 	sock_put(sk);
925 	return 0;
926 }
927 
928 /* Copied from af_unix.c:unix_poll(), added CAIF tx_flow handling */
929 static __poll_t caif_poll(struct file *file,
930 			      struct socket *sock, poll_table *wait)
931 {
932 	struct sock *sk = sock->sk;
933 	__poll_t mask;
934 	struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
935 
936 	sock_poll_wait(file, sock, wait);
937 	mask = 0;
938 
939 	/* exceptional events? */
940 	if (sk->sk_err)
941 		mask |= EPOLLERR;
942 	if (sk->sk_shutdown == SHUTDOWN_MASK)
943 		mask |= EPOLLHUP;
944 	if (sk->sk_shutdown & RCV_SHUTDOWN)
945 		mask |= EPOLLRDHUP;
946 
947 	/* readable? */
948 	if (!skb_queue_empty_lockless(&sk->sk_receive_queue) ||
949 		(sk->sk_shutdown & RCV_SHUTDOWN))
950 		mask |= EPOLLIN | EPOLLRDNORM;
951 
952 	/*
953 	 * we set writable also when the other side has shut down the
954 	 * connection. This prevents stuck sockets.
955 	 */
956 	if (sock_writeable(sk) && tx_flow_is_on(cf_sk))
957 		mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
958 
959 	return mask;
960 }
961 
962 static const struct proto_ops caif_seqpacket_ops = {
963 	.family = PF_CAIF,
964 	.owner = THIS_MODULE,
965 	.release = caif_release,
966 	.bind = sock_no_bind,
967 	.connect = caif_connect,
968 	.socketpair = sock_no_socketpair,
969 	.accept = sock_no_accept,
970 	.getname = sock_no_getname,
971 	.poll = caif_poll,
972 	.ioctl = sock_no_ioctl,
973 	.listen = sock_no_listen,
974 	.shutdown = sock_no_shutdown,
975 	.setsockopt = setsockopt,
976 	.sendmsg = caif_seqpkt_sendmsg,
977 	.recvmsg = caif_seqpkt_recvmsg,
978 	.mmap = sock_no_mmap,
979 	.sendpage = sock_no_sendpage,
980 };
981 
982 static const struct proto_ops caif_stream_ops = {
983 	.family = PF_CAIF,
984 	.owner = THIS_MODULE,
985 	.release = caif_release,
986 	.bind = sock_no_bind,
987 	.connect = caif_connect,
988 	.socketpair = sock_no_socketpair,
989 	.accept = sock_no_accept,
990 	.getname = sock_no_getname,
991 	.poll = caif_poll,
992 	.ioctl = sock_no_ioctl,
993 	.listen = sock_no_listen,
994 	.shutdown = sock_no_shutdown,
995 	.setsockopt = setsockopt,
996 	.sendmsg = caif_stream_sendmsg,
997 	.recvmsg = caif_stream_recvmsg,
998 	.mmap = sock_no_mmap,
999 	.sendpage = sock_no_sendpage,
1000 };
1001 
1002 /* This function is called when a socket is finally destroyed. */
1003 static void caif_sock_destructor(struct sock *sk)
1004 {
1005 	struct caifsock *cf_sk = container_of(sk, struct caifsock, sk);
1006 	caif_assert(!refcount_read(&sk->sk_wmem_alloc));
1007 	caif_assert(sk_unhashed(sk));
1008 	caif_assert(!sk->sk_socket);
1009 	if (!sock_flag(sk, SOCK_DEAD)) {
1010 		pr_debug("Attempt to release alive CAIF socket: %p\n", sk);
1011 		return;
1012 	}
1013 	sk_stream_kill_queues(&cf_sk->sk);
1014 	WARN_ON_ONCE(sk->sk_forward_alloc);
1015 	caif_free_client(&cf_sk->layer);
1016 }
1017 
1018 static int caif_create(struct net *net, struct socket *sock, int protocol,
1019 		       int kern)
1020 {
1021 	struct sock *sk = NULL;
1022 	struct caifsock *cf_sk = NULL;
1023 	static struct proto prot = {.name = "PF_CAIF",
1024 		.owner = THIS_MODULE,
1025 		.obj_size = sizeof(struct caifsock),
1026 		.useroffset = offsetof(struct caifsock, conn_req.param),
1027 		.usersize = sizeof_field(struct caifsock, conn_req.param)
1028 	};
1029 
1030 	if (!capable(CAP_SYS_ADMIN) && !capable(CAP_NET_ADMIN))
1031 		return -EPERM;
1032 	/*
1033 	 * The sock->type specifies the socket type to use.
1034 	 * The CAIF socket is a packet stream in the sense
1035 	 * that it is packet based. CAIF trusts the reliability
1036 	 * of the link, no resending is implemented.
1037 	 */
1038 	if (sock->type == SOCK_SEQPACKET)
1039 		sock->ops = &caif_seqpacket_ops;
1040 	else if (sock->type == SOCK_STREAM)
1041 		sock->ops = &caif_stream_ops;
1042 	else
1043 		return -ESOCKTNOSUPPORT;
1044 
1045 	if (protocol < 0 || protocol >= CAIFPROTO_MAX)
1046 		return -EPROTONOSUPPORT;
1047 	/*
1048 	 * Set the socket state to unconnected.	 The socket state
1049 	 * is really not used at all in the net/core or socket.c but the
1050 	 * initialization makes sure that sock->state is not uninitialized.
1051 	 */
1052 	sk = sk_alloc(net, PF_CAIF, GFP_KERNEL, &prot, kern);
1053 	if (!sk)
1054 		return -ENOMEM;
1055 
1056 	cf_sk = container_of(sk, struct caifsock, sk);
1057 
1058 	/* Store the protocol */
1059 	sk->sk_protocol = (unsigned char) protocol;
1060 
1061 	/* Initialize default priority for well-known cases */
1062 	switch (protocol) {
1063 	case CAIFPROTO_AT:
1064 		sk->sk_priority = TC_PRIO_CONTROL;
1065 		break;
1066 	case CAIFPROTO_RFM:
1067 		sk->sk_priority = TC_PRIO_INTERACTIVE_BULK;
1068 		break;
1069 	default:
1070 		sk->sk_priority = TC_PRIO_BESTEFFORT;
1071 	}
1072 
1073 	/*
1074 	 * Lock in order to try to stop someone from opening the socket
1075 	 * too early.
1076 	 */
1077 	lock_sock(&(cf_sk->sk));
1078 
1079 	/* Initialize the nozero default sock structure data. */
1080 	sock_init_data(sock, sk);
1081 	sk->sk_destruct = caif_sock_destructor;
1082 
1083 	mutex_init(&cf_sk->readlock); /* single task reading lock */
1084 	cf_sk->layer.ctrlcmd = caif_ctrl_cb;
1085 	cf_sk->sk.sk_socket->state = SS_UNCONNECTED;
1086 	cf_sk->sk.sk_state = CAIF_DISCONNECTED;
1087 
1088 	set_tx_flow_off(cf_sk);
1089 	set_rx_flow_on(cf_sk);
1090 
1091 	/* Set default options on configuration */
1092 	cf_sk->conn_req.link_selector = CAIF_LINK_LOW_LATENCY;
1093 	cf_sk->conn_req.protocol = protocol;
1094 	release_sock(&cf_sk->sk);
1095 	return 0;
1096 }
1097 
1098 
1099 static const struct net_proto_family caif_family_ops = {
1100 	.family = PF_CAIF,
1101 	.create = caif_create,
1102 	.owner = THIS_MODULE,
1103 };
1104 
1105 static int __init caif_sktinit_module(void)
1106 {
1107 	return sock_register(&caif_family_ops);
1108 }
1109 
1110 static void __exit caif_sktexit_module(void)
1111 {
1112 	sock_unregister(PF_CAIF);
1113 }
1114 module_init(caif_sktinit_module);
1115 module_exit(caif_sktexit_module);
1116