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