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