pvcalls-front: properly allocate sk
[linux-2.6-block.git] / drivers / xen / pvcalls-front.c
1 /*
2  * (c) 2017 Stefano Stabellini <stefano@aporeto.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include <linux/module.h>
16 #include <linux/net.h>
17 #include <linux/socket.h>
18
19 #include <net/sock.h>
20
21 #include <xen/events.h>
22 #include <xen/grant_table.h>
23 #include <xen/xen.h>
24 #include <xen/xenbus.h>
25 #include <xen/interface/io/pvcalls.h>
26
27 #include "pvcalls-front.h"
28
29 #define PVCALLS_INVALID_ID UINT_MAX
30 #define PVCALLS_RING_ORDER XENBUS_MAX_RING_GRANT_ORDER
31 #define PVCALLS_NR_RSP_PER_RING __CONST_RING_SIZE(xen_pvcalls, XEN_PAGE_SIZE)
32 #define PVCALLS_FRONT_MAX_SPIN 5000
33
34 static struct proto pvcalls_proto = {
35         .name   = "PVCalls",
36         .owner  = THIS_MODULE,
37         .obj_size = sizeof(struct sock),
38 };
39
40 struct pvcalls_bedata {
41         struct xen_pvcalls_front_ring ring;
42         grant_ref_t ref;
43         int irq;
44
45         struct list_head socket_mappings;
46         spinlock_t socket_lock;
47
48         wait_queue_head_t inflight_req;
49         struct xen_pvcalls_response rsp[PVCALLS_NR_RSP_PER_RING];
50 };
51 /* Only one front/back connection supported. */
52 static struct xenbus_device *pvcalls_front_dev;
53 static atomic_t pvcalls_refcount;
54
55 /* first increment refcount, then proceed */
56 #define pvcalls_enter() {               \
57         atomic_inc(&pvcalls_refcount);      \
58 }
59
60 /* first complete other operations, then decrement refcount */
61 #define pvcalls_exit() {                \
62         atomic_dec(&pvcalls_refcount);      \
63 }
64
65 struct sock_mapping {
66         bool active_socket;
67         struct list_head list;
68         struct socket *sock;
69         atomic_t refcount;
70         union {
71                 struct {
72                         int irq;
73                         grant_ref_t ref;
74                         struct pvcalls_data_intf *ring;
75                         struct pvcalls_data data;
76                         struct mutex in_mutex;
77                         struct mutex out_mutex;
78
79                         wait_queue_head_t inflight_conn_req;
80                 } active;
81                 struct {
82                 /*
83                  * Socket status, needs to be 64-bit aligned due to the
84                  * test_and_* functions which have this requirement on arm64.
85                  */
86 #define PVCALLS_STATUS_UNINITALIZED  0
87 #define PVCALLS_STATUS_BIND          1
88 #define PVCALLS_STATUS_LISTEN        2
89                         uint8_t status __attribute__((aligned(8)));
90                 /*
91                  * Internal state-machine flags.
92                  * Only one accept operation can be inflight for a socket.
93                  * Only one poll operation can be inflight for a given socket.
94                  * flags needs to be 64-bit aligned due to the test_and_*
95                  * functions which have this requirement on arm64.
96                  */
97 #define PVCALLS_FLAG_ACCEPT_INFLIGHT 0
98 #define PVCALLS_FLAG_POLL_INFLIGHT   1
99 #define PVCALLS_FLAG_POLL_RET        2
100                         uint8_t flags __attribute__((aligned(8)));
101                         uint32_t inflight_req_id;
102                         struct sock_mapping *accept_map;
103                         wait_queue_head_t inflight_accept_req;
104                 } passive;
105         };
106 };
107
108 static inline struct sock_mapping *pvcalls_enter_sock(struct socket *sock)
109 {
110         struct sock_mapping *map;
111
112         if (!pvcalls_front_dev ||
113                 dev_get_drvdata(&pvcalls_front_dev->dev) == NULL)
114                 return ERR_PTR(-ENOTCONN);
115
116         map = (struct sock_mapping *)sock->sk->sk_send_head;
117         if (map == NULL)
118                 return ERR_PTR(-ENOTSOCK);
119
120         pvcalls_enter();
121         atomic_inc(&map->refcount);
122         return map;
123 }
124
125 static inline void pvcalls_exit_sock(struct socket *sock)
126 {
127         struct sock_mapping *map;
128
129         map = (struct sock_mapping *)sock->sk->sk_send_head;
130         atomic_dec(&map->refcount);
131         pvcalls_exit();
132 }
133
134 static inline int get_request(struct pvcalls_bedata *bedata, int *req_id)
135 {
136         *req_id = bedata->ring.req_prod_pvt & (RING_SIZE(&bedata->ring) - 1);
137         if (RING_FULL(&bedata->ring) ||
138             bedata->rsp[*req_id].req_id != PVCALLS_INVALID_ID)
139                 return -EAGAIN;
140         return 0;
141 }
142
143 static bool pvcalls_front_write_todo(struct sock_mapping *map)
144 {
145         struct pvcalls_data_intf *intf = map->active.ring;
146         RING_IDX cons, prod, size = XEN_FLEX_RING_SIZE(PVCALLS_RING_ORDER);
147         int32_t error;
148
149         error = intf->out_error;
150         if (error == -ENOTCONN)
151                 return false;
152         if (error != 0)
153                 return true;
154
155         cons = intf->out_cons;
156         prod = intf->out_prod;
157         return !!(size - pvcalls_queued(prod, cons, size));
158 }
159
160 static bool pvcalls_front_read_todo(struct sock_mapping *map)
161 {
162         struct pvcalls_data_intf *intf = map->active.ring;
163         RING_IDX cons, prod;
164         int32_t error;
165
166         cons = intf->in_cons;
167         prod = intf->in_prod;
168         error = intf->in_error;
169         return (error != 0 ||
170                 pvcalls_queued(prod, cons,
171                                XEN_FLEX_RING_SIZE(PVCALLS_RING_ORDER)) != 0);
172 }
173
174 static irqreturn_t pvcalls_front_event_handler(int irq, void *dev_id)
175 {
176         struct xenbus_device *dev = dev_id;
177         struct pvcalls_bedata *bedata;
178         struct xen_pvcalls_response *rsp;
179         uint8_t *src, *dst;
180         int req_id = 0, more = 0, done = 0;
181
182         if (dev == NULL)
183                 return IRQ_HANDLED;
184
185         pvcalls_enter();
186         bedata = dev_get_drvdata(&dev->dev);
187         if (bedata == NULL) {
188                 pvcalls_exit();
189                 return IRQ_HANDLED;
190         }
191
192 again:
193         while (RING_HAS_UNCONSUMED_RESPONSES(&bedata->ring)) {
194                 rsp = RING_GET_RESPONSE(&bedata->ring, bedata->ring.rsp_cons);
195
196                 req_id = rsp->req_id;
197                 if (rsp->cmd == PVCALLS_POLL) {
198                         struct sock_mapping *map = (struct sock_mapping *)(uintptr_t)
199                                                    rsp->u.poll.id;
200
201                         clear_bit(PVCALLS_FLAG_POLL_INFLIGHT,
202                                   (void *)&map->passive.flags);
203                         /*
204                          * clear INFLIGHT, then set RET. It pairs with
205                          * the checks at the beginning of
206                          * pvcalls_front_poll_passive.
207                          */
208                         smp_wmb();
209                         set_bit(PVCALLS_FLAG_POLL_RET,
210                                 (void *)&map->passive.flags);
211                 } else {
212                         dst = (uint8_t *)&bedata->rsp[req_id] +
213                               sizeof(rsp->req_id);
214                         src = (uint8_t *)rsp + sizeof(rsp->req_id);
215                         memcpy(dst, src, sizeof(*rsp) - sizeof(rsp->req_id));
216                         /*
217                          * First copy the rest of the data, then req_id. It is
218                          * paired with the barrier when accessing bedata->rsp.
219                          */
220                         smp_wmb();
221                         bedata->rsp[req_id].req_id = req_id;
222                 }
223
224                 done = 1;
225                 bedata->ring.rsp_cons++;
226         }
227
228         RING_FINAL_CHECK_FOR_RESPONSES(&bedata->ring, more);
229         if (more)
230                 goto again;
231         if (done)
232                 wake_up(&bedata->inflight_req);
233         pvcalls_exit();
234         return IRQ_HANDLED;
235 }
236
237 static void pvcalls_front_free_map(struct pvcalls_bedata *bedata,
238                                    struct sock_mapping *map)
239 {
240         int i;
241
242         unbind_from_irqhandler(map->active.irq, map);
243
244         spin_lock(&bedata->socket_lock);
245         if (!list_empty(&map->list))
246                 list_del_init(&map->list);
247         spin_unlock(&bedata->socket_lock);
248
249         for (i = 0; i < (1 << PVCALLS_RING_ORDER); i++)
250                 gnttab_end_foreign_access(map->active.ring->ref[i], 0, 0);
251         gnttab_end_foreign_access(map->active.ref, 0, 0);
252         free_page((unsigned long)map->active.ring);
253
254         kfree(map);
255 }
256
257 static irqreturn_t pvcalls_front_conn_handler(int irq, void *sock_map)
258 {
259         struct sock_mapping *map = sock_map;
260
261         if (map == NULL)
262                 return IRQ_HANDLED;
263
264         wake_up_interruptible(&map->active.inflight_conn_req);
265
266         return IRQ_HANDLED;
267 }
268
269 int pvcalls_front_socket(struct socket *sock)
270 {
271         struct pvcalls_bedata *bedata;
272         struct sock_mapping *map = NULL;
273         struct xen_pvcalls_request *req;
274         int notify, req_id, ret;
275
276         /*
277          * PVCalls only supports domain AF_INET,
278          * type SOCK_STREAM and protocol 0 sockets for now.
279          *
280          * Check socket type here, AF_INET and protocol checks are done
281          * by the caller.
282          */
283         if (sock->type != SOCK_STREAM)
284                 return -EOPNOTSUPP;
285
286         pvcalls_enter();
287         if (!pvcalls_front_dev) {
288                 pvcalls_exit();
289                 return -EACCES;
290         }
291         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
292
293         map = kzalloc(sizeof(*map), GFP_KERNEL);
294         if (map == NULL) {
295                 pvcalls_exit();
296                 return -ENOMEM;
297         }
298
299         spin_lock(&bedata->socket_lock);
300
301         ret = get_request(bedata, &req_id);
302         if (ret < 0) {
303                 kfree(map);
304                 spin_unlock(&bedata->socket_lock);
305                 pvcalls_exit();
306                 return ret;
307         }
308
309         /*
310          * sock->sk->sk_send_head is not used for ip sockets: reuse the
311          * field to store a pointer to the struct sock_mapping
312          * corresponding to the socket. This way, we can easily get the
313          * struct sock_mapping from the struct socket.
314          */
315         sock->sk->sk_send_head = (void *)map;
316         list_add_tail(&map->list, &bedata->socket_mappings);
317
318         req = RING_GET_REQUEST(&bedata->ring, req_id);
319         req->req_id = req_id;
320         req->cmd = PVCALLS_SOCKET;
321         req->u.socket.id = (uintptr_t) map;
322         req->u.socket.domain = AF_INET;
323         req->u.socket.type = SOCK_STREAM;
324         req->u.socket.protocol = IPPROTO_IP;
325
326         bedata->ring.req_prod_pvt++;
327         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&bedata->ring, notify);
328         spin_unlock(&bedata->socket_lock);
329         if (notify)
330                 notify_remote_via_irq(bedata->irq);
331
332         wait_event(bedata->inflight_req,
333                    READ_ONCE(bedata->rsp[req_id].req_id) == req_id);
334
335         /* read req_id, then the content */
336         smp_rmb();
337         ret = bedata->rsp[req_id].ret;
338         bedata->rsp[req_id].req_id = PVCALLS_INVALID_ID;
339
340         pvcalls_exit();
341         return ret;
342 }
343
344 static int create_active(struct sock_mapping *map, int *evtchn)
345 {
346         void *bytes;
347         int ret = -ENOMEM, irq = -1, i;
348
349         *evtchn = -1;
350         init_waitqueue_head(&map->active.inflight_conn_req);
351
352         map->active.ring = (struct pvcalls_data_intf *)
353                 __get_free_page(GFP_KERNEL | __GFP_ZERO);
354         if (map->active.ring == NULL)
355                 goto out_error;
356         map->active.ring->ring_order = PVCALLS_RING_ORDER;
357         bytes = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
358                                         PVCALLS_RING_ORDER);
359         if (bytes == NULL)
360                 goto out_error;
361         for (i = 0; i < (1 << PVCALLS_RING_ORDER); i++)
362                 map->active.ring->ref[i] = gnttab_grant_foreign_access(
363                         pvcalls_front_dev->otherend_id,
364                         pfn_to_gfn(virt_to_pfn(bytes) + i), 0);
365
366         map->active.ref = gnttab_grant_foreign_access(
367                 pvcalls_front_dev->otherend_id,
368                 pfn_to_gfn(virt_to_pfn((void *)map->active.ring)), 0);
369
370         map->active.data.in = bytes;
371         map->active.data.out = bytes +
372                 XEN_FLEX_RING_SIZE(PVCALLS_RING_ORDER);
373
374         ret = xenbus_alloc_evtchn(pvcalls_front_dev, evtchn);
375         if (ret)
376                 goto out_error;
377         irq = bind_evtchn_to_irqhandler(*evtchn, pvcalls_front_conn_handler,
378                                         0, "pvcalls-frontend", map);
379         if (irq < 0) {
380                 ret = irq;
381                 goto out_error;
382         }
383
384         map->active.irq = irq;
385         map->active_socket = true;
386         mutex_init(&map->active.in_mutex);
387         mutex_init(&map->active.out_mutex);
388
389         return 0;
390
391 out_error:
392         if (*evtchn >= 0)
393                 xenbus_free_evtchn(pvcalls_front_dev, *evtchn);
394         free_pages((unsigned long)map->active.data.in, PVCALLS_RING_ORDER);
395         free_page((unsigned long)map->active.ring);
396         return ret;
397 }
398
399 int pvcalls_front_connect(struct socket *sock, struct sockaddr *addr,
400                                 int addr_len, int flags)
401 {
402         struct pvcalls_bedata *bedata;
403         struct sock_mapping *map = NULL;
404         struct xen_pvcalls_request *req;
405         int notify, req_id, ret, evtchn;
406
407         if (addr->sa_family != AF_INET || sock->type != SOCK_STREAM)
408                 return -EOPNOTSUPP;
409
410         map = pvcalls_enter_sock(sock);
411         if (IS_ERR(map))
412                 return PTR_ERR(map);
413
414         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
415
416         spin_lock(&bedata->socket_lock);
417         ret = get_request(bedata, &req_id);
418         if (ret < 0) {
419                 spin_unlock(&bedata->socket_lock);
420                 pvcalls_exit_sock(sock);
421                 return ret;
422         }
423         ret = create_active(map, &evtchn);
424         if (ret < 0) {
425                 spin_unlock(&bedata->socket_lock);
426                 pvcalls_exit_sock(sock);
427                 return ret;
428         }
429
430         req = RING_GET_REQUEST(&bedata->ring, req_id);
431         req->req_id = req_id;
432         req->cmd = PVCALLS_CONNECT;
433         req->u.connect.id = (uintptr_t)map;
434         req->u.connect.len = addr_len;
435         req->u.connect.flags = flags;
436         req->u.connect.ref = map->active.ref;
437         req->u.connect.evtchn = evtchn;
438         memcpy(req->u.connect.addr, addr, sizeof(*addr));
439
440         map->sock = sock;
441
442         bedata->ring.req_prod_pvt++;
443         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&bedata->ring, notify);
444         spin_unlock(&bedata->socket_lock);
445
446         if (notify)
447                 notify_remote_via_irq(bedata->irq);
448
449         wait_event(bedata->inflight_req,
450                    READ_ONCE(bedata->rsp[req_id].req_id) == req_id);
451
452         /* read req_id, then the content */
453         smp_rmb();
454         ret = bedata->rsp[req_id].ret;
455         bedata->rsp[req_id].req_id = PVCALLS_INVALID_ID;
456         pvcalls_exit_sock(sock);
457         return ret;
458 }
459
460 static int __write_ring(struct pvcalls_data_intf *intf,
461                         struct pvcalls_data *data,
462                         struct iov_iter *msg_iter,
463                         int len)
464 {
465         RING_IDX cons, prod, size, masked_prod, masked_cons;
466         RING_IDX array_size = XEN_FLEX_RING_SIZE(PVCALLS_RING_ORDER);
467         int32_t error;
468
469         error = intf->out_error;
470         if (error < 0)
471                 return error;
472         cons = intf->out_cons;
473         prod = intf->out_prod;
474         /* read indexes before continuing */
475         virt_mb();
476
477         size = pvcalls_queued(prod, cons, array_size);
478         if (size >= array_size)
479                 return -EINVAL;
480         if (len > array_size - size)
481                 len = array_size - size;
482
483         masked_prod = pvcalls_mask(prod, array_size);
484         masked_cons = pvcalls_mask(cons, array_size);
485
486         if (masked_prod < masked_cons) {
487                 len = copy_from_iter(data->out + masked_prod, len, msg_iter);
488         } else {
489                 if (len > array_size - masked_prod) {
490                         int ret = copy_from_iter(data->out + masked_prod,
491                                        array_size - masked_prod, msg_iter);
492                         if (ret != array_size - masked_prod) {
493                                 len = ret;
494                                 goto out;
495                         }
496                         len = ret + copy_from_iter(data->out, len - ret, msg_iter);
497                 } else {
498                         len = copy_from_iter(data->out + masked_prod, len, msg_iter);
499                 }
500         }
501 out:
502         /* write to ring before updating pointer */
503         virt_wmb();
504         intf->out_prod += len;
505
506         return len;
507 }
508
509 int pvcalls_front_sendmsg(struct socket *sock, struct msghdr *msg,
510                           size_t len)
511 {
512         struct pvcalls_bedata *bedata;
513         struct sock_mapping *map;
514         int sent, tot_sent = 0;
515         int count = 0, flags;
516
517         flags = msg->msg_flags;
518         if (flags & (MSG_CONFIRM|MSG_DONTROUTE|MSG_EOR|MSG_OOB))
519                 return -EOPNOTSUPP;
520
521         map = pvcalls_enter_sock(sock);
522         if (IS_ERR(map))
523                 return PTR_ERR(map);
524         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
525
526         mutex_lock(&map->active.out_mutex);
527         if ((flags & MSG_DONTWAIT) && !pvcalls_front_write_todo(map)) {
528                 mutex_unlock(&map->active.out_mutex);
529                 pvcalls_exit_sock(sock);
530                 return -EAGAIN;
531         }
532         if (len > INT_MAX)
533                 len = INT_MAX;
534
535 again:
536         count++;
537         sent = __write_ring(map->active.ring,
538                             &map->active.data, &msg->msg_iter,
539                             len);
540         if (sent > 0) {
541                 len -= sent;
542                 tot_sent += sent;
543                 notify_remote_via_irq(map->active.irq);
544         }
545         if (sent >= 0 && len > 0 && count < PVCALLS_FRONT_MAX_SPIN)
546                 goto again;
547         if (sent < 0)
548                 tot_sent = sent;
549
550         mutex_unlock(&map->active.out_mutex);
551         pvcalls_exit_sock(sock);
552         return tot_sent;
553 }
554
555 static int __read_ring(struct pvcalls_data_intf *intf,
556                        struct pvcalls_data *data,
557                        struct iov_iter *msg_iter,
558                        size_t len, int flags)
559 {
560         RING_IDX cons, prod, size, masked_prod, masked_cons;
561         RING_IDX array_size = XEN_FLEX_RING_SIZE(PVCALLS_RING_ORDER);
562         int32_t error;
563
564         cons = intf->in_cons;
565         prod = intf->in_prod;
566         error = intf->in_error;
567         /* get pointers before reading from the ring */
568         virt_rmb();
569
570         size = pvcalls_queued(prod, cons, array_size);
571         masked_prod = pvcalls_mask(prod, array_size);
572         masked_cons = pvcalls_mask(cons, array_size);
573
574         if (size == 0)
575                 return error ?: size;
576
577         if (len > size)
578                 len = size;
579
580         if (masked_prod > masked_cons) {
581                 len = copy_to_iter(data->in + masked_cons, len, msg_iter);
582         } else {
583                 if (len > (array_size - masked_cons)) {
584                         int ret = copy_to_iter(data->in + masked_cons,
585                                      array_size - masked_cons, msg_iter);
586                         if (ret != array_size - masked_cons) {
587                                 len = ret;
588                                 goto out;
589                         }
590                         len = ret + copy_to_iter(data->in, len - ret, msg_iter);
591                 } else {
592                         len = copy_to_iter(data->in + masked_cons, len, msg_iter);
593                 }
594         }
595 out:
596         /* read data from the ring before increasing the index */
597         virt_mb();
598         if (!(flags & MSG_PEEK))
599                 intf->in_cons += len;
600
601         return len;
602 }
603
604 int pvcalls_front_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
605                      int flags)
606 {
607         struct pvcalls_bedata *bedata;
608         int ret;
609         struct sock_mapping *map;
610
611         if (flags & (MSG_CMSG_CLOEXEC|MSG_ERRQUEUE|MSG_OOB|MSG_TRUNC))
612                 return -EOPNOTSUPP;
613
614         map = pvcalls_enter_sock(sock);
615         if (IS_ERR(map))
616                 return PTR_ERR(map);
617         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
618
619         mutex_lock(&map->active.in_mutex);
620         if (len > XEN_FLEX_RING_SIZE(PVCALLS_RING_ORDER))
621                 len = XEN_FLEX_RING_SIZE(PVCALLS_RING_ORDER);
622
623         while (!(flags & MSG_DONTWAIT) && !pvcalls_front_read_todo(map)) {
624                 wait_event_interruptible(map->active.inflight_conn_req,
625                                          pvcalls_front_read_todo(map));
626         }
627         ret = __read_ring(map->active.ring, &map->active.data,
628                           &msg->msg_iter, len, flags);
629
630         if (ret > 0)
631                 notify_remote_via_irq(map->active.irq);
632         if (ret == 0)
633                 ret = (flags & MSG_DONTWAIT) ? -EAGAIN : 0;
634         if (ret == -ENOTCONN)
635                 ret = 0;
636
637         mutex_unlock(&map->active.in_mutex);
638         pvcalls_exit_sock(sock);
639         return ret;
640 }
641
642 int pvcalls_front_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
643 {
644         struct pvcalls_bedata *bedata;
645         struct sock_mapping *map = NULL;
646         struct xen_pvcalls_request *req;
647         int notify, req_id, ret;
648
649         if (addr->sa_family != AF_INET || sock->type != SOCK_STREAM)
650                 return -EOPNOTSUPP;
651
652         map = pvcalls_enter_sock(sock);
653         if (IS_ERR(map))
654                 return PTR_ERR(map);
655         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
656
657         spin_lock(&bedata->socket_lock);
658         ret = get_request(bedata, &req_id);
659         if (ret < 0) {
660                 spin_unlock(&bedata->socket_lock);
661                 pvcalls_exit_sock(sock);
662                 return ret;
663         }
664         req = RING_GET_REQUEST(&bedata->ring, req_id);
665         req->req_id = req_id;
666         map->sock = sock;
667         req->cmd = PVCALLS_BIND;
668         req->u.bind.id = (uintptr_t)map;
669         memcpy(req->u.bind.addr, addr, sizeof(*addr));
670         req->u.bind.len = addr_len;
671
672         init_waitqueue_head(&map->passive.inflight_accept_req);
673
674         map->active_socket = false;
675
676         bedata->ring.req_prod_pvt++;
677         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&bedata->ring, notify);
678         spin_unlock(&bedata->socket_lock);
679         if (notify)
680                 notify_remote_via_irq(bedata->irq);
681
682         wait_event(bedata->inflight_req,
683                    READ_ONCE(bedata->rsp[req_id].req_id) == req_id);
684
685         /* read req_id, then the content */
686         smp_rmb();
687         ret = bedata->rsp[req_id].ret;
688         bedata->rsp[req_id].req_id = PVCALLS_INVALID_ID;
689
690         map->passive.status = PVCALLS_STATUS_BIND;
691         pvcalls_exit_sock(sock);
692         return 0;
693 }
694
695 int pvcalls_front_listen(struct socket *sock, int backlog)
696 {
697         struct pvcalls_bedata *bedata;
698         struct sock_mapping *map;
699         struct xen_pvcalls_request *req;
700         int notify, req_id, ret;
701
702         map = pvcalls_enter_sock(sock);
703         if (IS_ERR(map))
704                 return PTR_ERR(map);
705         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
706
707         if (map->passive.status != PVCALLS_STATUS_BIND) {
708                 pvcalls_exit_sock(sock);
709                 return -EOPNOTSUPP;
710         }
711
712         spin_lock(&bedata->socket_lock);
713         ret = get_request(bedata, &req_id);
714         if (ret < 0) {
715                 spin_unlock(&bedata->socket_lock);
716                 pvcalls_exit_sock(sock);
717                 return ret;
718         }
719         req = RING_GET_REQUEST(&bedata->ring, req_id);
720         req->req_id = req_id;
721         req->cmd = PVCALLS_LISTEN;
722         req->u.listen.id = (uintptr_t) map;
723         req->u.listen.backlog = backlog;
724
725         bedata->ring.req_prod_pvt++;
726         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&bedata->ring, notify);
727         spin_unlock(&bedata->socket_lock);
728         if (notify)
729                 notify_remote_via_irq(bedata->irq);
730
731         wait_event(bedata->inflight_req,
732                    READ_ONCE(bedata->rsp[req_id].req_id) == req_id);
733
734         /* read req_id, then the content */
735         smp_rmb();
736         ret = bedata->rsp[req_id].ret;
737         bedata->rsp[req_id].req_id = PVCALLS_INVALID_ID;
738
739         map->passive.status = PVCALLS_STATUS_LISTEN;
740         pvcalls_exit_sock(sock);
741         return ret;
742 }
743
744 int pvcalls_front_accept(struct socket *sock, struct socket *newsock, int flags)
745 {
746         struct pvcalls_bedata *bedata;
747         struct sock_mapping *map;
748         struct sock_mapping *map2 = NULL;
749         struct xen_pvcalls_request *req;
750         int notify, req_id, ret, evtchn, nonblock;
751
752         map = pvcalls_enter_sock(sock);
753         if (IS_ERR(map))
754                 return PTR_ERR(map);
755         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
756
757         if (map->passive.status != PVCALLS_STATUS_LISTEN) {
758                 pvcalls_exit_sock(sock);
759                 return -EINVAL;
760         }
761
762         nonblock = flags & SOCK_NONBLOCK;
763         /*
764          * Backend only supports 1 inflight accept request, will return
765          * errors for the others
766          */
767         if (test_and_set_bit(PVCALLS_FLAG_ACCEPT_INFLIGHT,
768                              (void *)&map->passive.flags)) {
769                 req_id = READ_ONCE(map->passive.inflight_req_id);
770                 if (req_id != PVCALLS_INVALID_ID &&
771                     READ_ONCE(bedata->rsp[req_id].req_id) == req_id) {
772                         map2 = map->passive.accept_map;
773                         goto received;
774                 }
775                 if (nonblock) {
776                         pvcalls_exit_sock(sock);
777                         return -EAGAIN;
778                 }
779                 if (wait_event_interruptible(map->passive.inflight_accept_req,
780                         !test_and_set_bit(PVCALLS_FLAG_ACCEPT_INFLIGHT,
781                                           (void *)&map->passive.flags))) {
782                         pvcalls_exit_sock(sock);
783                         return -EINTR;
784                 }
785         }
786
787         spin_lock(&bedata->socket_lock);
788         ret = get_request(bedata, &req_id);
789         if (ret < 0) {
790                 clear_bit(PVCALLS_FLAG_ACCEPT_INFLIGHT,
791                           (void *)&map->passive.flags);
792                 spin_unlock(&bedata->socket_lock);
793                 pvcalls_exit_sock(sock);
794                 return ret;
795         }
796         map2 = kzalloc(sizeof(*map2), GFP_ATOMIC);
797         if (map2 == NULL) {
798                 clear_bit(PVCALLS_FLAG_ACCEPT_INFLIGHT,
799                           (void *)&map->passive.flags);
800                 spin_unlock(&bedata->socket_lock);
801                 pvcalls_exit_sock(sock);
802                 return -ENOMEM;
803         }
804         ret = create_active(map2, &evtchn);
805         if (ret < 0) {
806                 kfree(map2);
807                 clear_bit(PVCALLS_FLAG_ACCEPT_INFLIGHT,
808                           (void *)&map->passive.flags);
809                 spin_unlock(&bedata->socket_lock);
810                 pvcalls_exit_sock(sock);
811                 return ret;
812         }
813         list_add_tail(&map2->list, &bedata->socket_mappings);
814
815         req = RING_GET_REQUEST(&bedata->ring, req_id);
816         req->req_id = req_id;
817         req->cmd = PVCALLS_ACCEPT;
818         req->u.accept.id = (uintptr_t) map;
819         req->u.accept.ref = map2->active.ref;
820         req->u.accept.id_new = (uintptr_t) map2;
821         req->u.accept.evtchn = evtchn;
822         map->passive.accept_map = map2;
823
824         bedata->ring.req_prod_pvt++;
825         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&bedata->ring, notify);
826         spin_unlock(&bedata->socket_lock);
827         if (notify)
828                 notify_remote_via_irq(bedata->irq);
829         /* We could check if we have received a response before returning. */
830         if (nonblock) {
831                 WRITE_ONCE(map->passive.inflight_req_id, req_id);
832                 pvcalls_exit_sock(sock);
833                 return -EAGAIN;
834         }
835
836         if (wait_event_interruptible(bedata->inflight_req,
837                 READ_ONCE(bedata->rsp[req_id].req_id) == req_id)) {
838                 pvcalls_exit_sock(sock);
839                 return -EINTR;
840         }
841         /* read req_id, then the content */
842         smp_rmb();
843
844 received:
845         map2->sock = newsock;
846         newsock->sk = sk_alloc(sock_net(sock->sk), PF_INET, GFP_KERNEL, &pvcalls_proto, false);
847         if (!newsock->sk) {
848                 bedata->rsp[req_id].req_id = PVCALLS_INVALID_ID;
849                 map->passive.inflight_req_id = PVCALLS_INVALID_ID;
850                 clear_bit(PVCALLS_FLAG_ACCEPT_INFLIGHT,
851                           (void *)&map->passive.flags);
852                 pvcalls_front_free_map(bedata, map2);
853                 pvcalls_exit_sock(sock);
854                 return -ENOMEM;
855         }
856         newsock->sk->sk_send_head = (void *)map2;
857
858         ret = bedata->rsp[req_id].ret;
859         bedata->rsp[req_id].req_id = PVCALLS_INVALID_ID;
860         map->passive.inflight_req_id = PVCALLS_INVALID_ID;
861
862         clear_bit(PVCALLS_FLAG_ACCEPT_INFLIGHT, (void *)&map->passive.flags);
863         wake_up(&map->passive.inflight_accept_req);
864
865         pvcalls_exit_sock(sock);
866         return ret;
867 }
868
869 static __poll_t pvcalls_front_poll_passive(struct file *file,
870                                                struct pvcalls_bedata *bedata,
871                                                struct sock_mapping *map,
872                                                poll_table *wait)
873 {
874         int notify, req_id, ret;
875         struct xen_pvcalls_request *req;
876
877         if (test_bit(PVCALLS_FLAG_ACCEPT_INFLIGHT,
878                      (void *)&map->passive.flags)) {
879                 uint32_t req_id = READ_ONCE(map->passive.inflight_req_id);
880
881                 if (req_id != PVCALLS_INVALID_ID &&
882                     READ_ONCE(bedata->rsp[req_id].req_id) == req_id)
883                         return EPOLLIN | EPOLLRDNORM;
884
885                 poll_wait(file, &map->passive.inflight_accept_req, wait);
886                 return 0;
887         }
888
889         if (test_and_clear_bit(PVCALLS_FLAG_POLL_RET,
890                                (void *)&map->passive.flags))
891                 return EPOLLIN | EPOLLRDNORM;
892
893         /*
894          * First check RET, then INFLIGHT. No barriers necessary to
895          * ensure execution ordering because of the conditional
896          * instructions creating control dependencies.
897          */
898
899         if (test_and_set_bit(PVCALLS_FLAG_POLL_INFLIGHT,
900                              (void *)&map->passive.flags)) {
901                 poll_wait(file, &bedata->inflight_req, wait);
902                 return 0;
903         }
904
905         spin_lock(&bedata->socket_lock);
906         ret = get_request(bedata, &req_id);
907         if (ret < 0) {
908                 spin_unlock(&bedata->socket_lock);
909                 return ret;
910         }
911         req = RING_GET_REQUEST(&bedata->ring, req_id);
912         req->req_id = req_id;
913         req->cmd = PVCALLS_POLL;
914         req->u.poll.id = (uintptr_t) map;
915
916         bedata->ring.req_prod_pvt++;
917         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&bedata->ring, notify);
918         spin_unlock(&bedata->socket_lock);
919         if (notify)
920                 notify_remote_via_irq(bedata->irq);
921
922         poll_wait(file, &bedata->inflight_req, wait);
923         return 0;
924 }
925
926 static __poll_t pvcalls_front_poll_active(struct file *file,
927                                               struct pvcalls_bedata *bedata,
928                                               struct sock_mapping *map,
929                                               poll_table *wait)
930 {
931         __poll_t mask = 0;
932         int32_t in_error, out_error;
933         struct pvcalls_data_intf *intf = map->active.ring;
934
935         out_error = intf->out_error;
936         in_error = intf->in_error;
937
938         poll_wait(file, &map->active.inflight_conn_req, wait);
939         if (pvcalls_front_write_todo(map))
940                 mask |= EPOLLOUT | EPOLLWRNORM;
941         if (pvcalls_front_read_todo(map))
942                 mask |= EPOLLIN | EPOLLRDNORM;
943         if (in_error != 0 || out_error != 0)
944                 mask |= EPOLLERR;
945
946         return mask;
947 }
948
949 __poll_t pvcalls_front_poll(struct file *file, struct socket *sock,
950                                poll_table *wait)
951 {
952         struct pvcalls_bedata *bedata;
953         struct sock_mapping *map;
954         __poll_t ret;
955
956         map = pvcalls_enter_sock(sock);
957         if (IS_ERR(map))
958                 return EPOLLNVAL;
959         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
960
961         if (map->active_socket)
962                 ret = pvcalls_front_poll_active(file, bedata, map, wait);
963         else
964                 ret = pvcalls_front_poll_passive(file, bedata, map, wait);
965         pvcalls_exit_sock(sock);
966         return ret;
967 }
968
969 int pvcalls_front_release(struct socket *sock)
970 {
971         struct pvcalls_bedata *bedata;
972         struct sock_mapping *map;
973         int req_id, notify, ret;
974         struct xen_pvcalls_request *req;
975
976         if (sock->sk == NULL)
977                 return 0;
978
979         map = pvcalls_enter_sock(sock);
980         if (IS_ERR(map)) {
981                 if (PTR_ERR(map) == -ENOTCONN)
982                         return -EIO;
983                 else
984                         return 0;
985         }
986         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
987
988         spin_lock(&bedata->socket_lock);
989         ret = get_request(bedata, &req_id);
990         if (ret < 0) {
991                 spin_unlock(&bedata->socket_lock);
992                 pvcalls_exit_sock(sock);
993                 return ret;
994         }
995         sock->sk->sk_send_head = NULL;
996
997         req = RING_GET_REQUEST(&bedata->ring, req_id);
998         req->req_id = req_id;
999         req->cmd = PVCALLS_RELEASE;
1000         req->u.release.id = (uintptr_t)map;
1001
1002         bedata->ring.req_prod_pvt++;
1003         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&bedata->ring, notify);
1004         spin_unlock(&bedata->socket_lock);
1005         if (notify)
1006                 notify_remote_via_irq(bedata->irq);
1007
1008         wait_event(bedata->inflight_req,
1009                    READ_ONCE(bedata->rsp[req_id].req_id) == req_id);
1010
1011         if (map->active_socket) {
1012                 /*
1013                  * Set in_error and wake up inflight_conn_req to force
1014                  * recvmsg waiters to exit.
1015                  */
1016                 map->active.ring->in_error = -EBADF;
1017                 wake_up_interruptible(&map->active.inflight_conn_req);
1018
1019                 /*
1020                  * We need to make sure that sendmsg/recvmsg on this socket have
1021                  * not started before we've cleared sk_send_head here. The
1022                  * easiest way to guarantee this is to see that no pvcalls
1023                  * (other than us) is in progress on this socket.
1024                  */
1025                 while (atomic_read(&map->refcount) > 1)
1026                         cpu_relax();
1027
1028                 pvcalls_front_free_map(bedata, map);
1029         } else {
1030                 wake_up(&bedata->inflight_req);
1031                 wake_up(&map->passive.inflight_accept_req);
1032
1033                 while (atomic_read(&map->refcount) > 1)
1034                         cpu_relax();
1035
1036                 spin_lock(&bedata->socket_lock);
1037                 list_del(&map->list);
1038                 spin_unlock(&bedata->socket_lock);
1039                 if (READ_ONCE(map->passive.inflight_req_id) != PVCALLS_INVALID_ID &&
1040                         READ_ONCE(map->passive.inflight_req_id) != 0) {
1041                         pvcalls_front_free_map(bedata,
1042                                                map->passive.accept_map);
1043                 }
1044                 kfree(map);
1045         }
1046         WRITE_ONCE(bedata->rsp[req_id].req_id, PVCALLS_INVALID_ID);
1047
1048         pvcalls_exit();
1049         return 0;
1050 }
1051
1052 static const struct xenbus_device_id pvcalls_front_ids[] = {
1053         { "pvcalls" },
1054         { "" }
1055 };
1056
1057 static int pvcalls_front_remove(struct xenbus_device *dev)
1058 {
1059         struct pvcalls_bedata *bedata;
1060         struct sock_mapping *map = NULL, *n;
1061
1062         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
1063         dev_set_drvdata(&dev->dev, NULL);
1064         pvcalls_front_dev = NULL;
1065         if (bedata->irq >= 0)
1066                 unbind_from_irqhandler(bedata->irq, dev);
1067
1068         list_for_each_entry_safe(map, n, &bedata->socket_mappings, list) {
1069                 map->sock->sk->sk_send_head = NULL;
1070                 if (map->active_socket) {
1071                         map->active.ring->in_error = -EBADF;
1072                         wake_up_interruptible(&map->active.inflight_conn_req);
1073                 }
1074         }
1075
1076         smp_mb();
1077         while (atomic_read(&pvcalls_refcount) > 0)
1078                 cpu_relax();
1079         list_for_each_entry_safe(map, n, &bedata->socket_mappings, list) {
1080                 if (map->active_socket) {
1081                         /* No need to lock, refcount is 0 */
1082                         pvcalls_front_free_map(bedata, map);
1083                 } else {
1084                         list_del(&map->list);
1085                         kfree(map);
1086                 }
1087         }
1088         if (bedata->ref != -1)
1089                 gnttab_end_foreign_access(bedata->ref, 0, 0);
1090         kfree(bedata->ring.sring);
1091         kfree(bedata);
1092         xenbus_switch_state(dev, XenbusStateClosed);
1093         return 0;
1094 }
1095
1096 static int pvcalls_front_probe(struct xenbus_device *dev,
1097                           const struct xenbus_device_id *id)
1098 {
1099         int ret = -ENOMEM, evtchn, i;
1100         unsigned int max_page_order, function_calls, len;
1101         char *versions;
1102         grant_ref_t gref_head = 0;
1103         struct xenbus_transaction xbt;
1104         struct pvcalls_bedata *bedata = NULL;
1105         struct xen_pvcalls_sring *sring;
1106
1107         if (pvcalls_front_dev != NULL) {
1108                 dev_err(&dev->dev, "only one PV Calls connection supported\n");
1109                 return -EINVAL;
1110         }
1111
1112         versions = xenbus_read(XBT_NIL, dev->otherend, "versions", &len);
1113         if (IS_ERR(versions))
1114                 return PTR_ERR(versions);
1115         if (!len)
1116                 return -EINVAL;
1117         if (strcmp(versions, "1")) {
1118                 kfree(versions);
1119                 return -EINVAL;
1120         }
1121         kfree(versions);
1122         max_page_order = xenbus_read_unsigned(dev->otherend,
1123                                               "max-page-order", 0);
1124         if (max_page_order < PVCALLS_RING_ORDER)
1125                 return -ENODEV;
1126         function_calls = xenbus_read_unsigned(dev->otherend,
1127                                               "function-calls", 0);
1128         /* See XENBUS_FUNCTIONS_CALLS in pvcalls.h */
1129         if (function_calls != 1)
1130                 return -ENODEV;
1131         pr_info("%s max-page-order is %u\n", __func__, max_page_order);
1132
1133         bedata = kzalloc(sizeof(struct pvcalls_bedata), GFP_KERNEL);
1134         if (!bedata)
1135                 return -ENOMEM;
1136
1137         dev_set_drvdata(&dev->dev, bedata);
1138         pvcalls_front_dev = dev;
1139         init_waitqueue_head(&bedata->inflight_req);
1140         INIT_LIST_HEAD(&bedata->socket_mappings);
1141         spin_lock_init(&bedata->socket_lock);
1142         bedata->irq = -1;
1143         bedata->ref = -1;
1144
1145         for (i = 0; i < PVCALLS_NR_RSP_PER_RING; i++)
1146                 bedata->rsp[i].req_id = PVCALLS_INVALID_ID;
1147
1148         sring = (struct xen_pvcalls_sring *) __get_free_page(GFP_KERNEL |
1149                                                              __GFP_ZERO);
1150         if (!sring)
1151                 goto error;
1152         SHARED_RING_INIT(sring);
1153         FRONT_RING_INIT(&bedata->ring, sring, XEN_PAGE_SIZE);
1154
1155         ret = xenbus_alloc_evtchn(dev, &evtchn);
1156         if (ret)
1157                 goto error;
1158
1159         bedata->irq = bind_evtchn_to_irqhandler(evtchn,
1160                                                 pvcalls_front_event_handler,
1161                                                 0, "pvcalls-frontend", dev);
1162         if (bedata->irq < 0) {
1163                 ret = bedata->irq;
1164                 goto error;
1165         }
1166
1167         ret = gnttab_alloc_grant_references(1, &gref_head);
1168         if (ret < 0)
1169                 goto error;
1170         ret = gnttab_claim_grant_reference(&gref_head);
1171         if (ret < 0)
1172                 goto error;
1173         bedata->ref = ret;
1174         gnttab_grant_foreign_access_ref(bedata->ref, dev->otherend_id,
1175                                         virt_to_gfn((void *)sring), 0);
1176
1177  again:
1178         ret = xenbus_transaction_start(&xbt);
1179         if (ret) {
1180                 xenbus_dev_fatal(dev, ret, "starting transaction");
1181                 goto error;
1182         }
1183         ret = xenbus_printf(xbt, dev->nodename, "version", "%u", 1);
1184         if (ret)
1185                 goto error_xenbus;
1186         ret = xenbus_printf(xbt, dev->nodename, "ring-ref", "%d", bedata->ref);
1187         if (ret)
1188                 goto error_xenbus;
1189         ret = xenbus_printf(xbt, dev->nodename, "port", "%u",
1190                             evtchn);
1191         if (ret)
1192                 goto error_xenbus;
1193         ret = xenbus_transaction_end(xbt, 0);
1194         if (ret) {
1195                 if (ret == -EAGAIN)
1196                         goto again;
1197                 xenbus_dev_fatal(dev, ret, "completing transaction");
1198                 goto error;
1199         }
1200         xenbus_switch_state(dev, XenbusStateInitialised);
1201
1202         return 0;
1203
1204  error_xenbus:
1205         xenbus_transaction_end(xbt, 1);
1206         xenbus_dev_fatal(dev, ret, "writing xenstore");
1207  error:
1208         pvcalls_front_remove(dev);
1209         return ret;
1210 }
1211
1212 static void pvcalls_front_changed(struct xenbus_device *dev,
1213                             enum xenbus_state backend_state)
1214 {
1215         switch (backend_state) {
1216         case XenbusStateReconfiguring:
1217         case XenbusStateReconfigured:
1218         case XenbusStateInitialising:
1219         case XenbusStateInitialised:
1220         case XenbusStateUnknown:
1221                 break;
1222
1223         case XenbusStateInitWait:
1224                 break;
1225
1226         case XenbusStateConnected:
1227                 xenbus_switch_state(dev, XenbusStateConnected);
1228                 break;
1229
1230         case XenbusStateClosed:
1231                 if (dev->state == XenbusStateClosed)
1232                         break;
1233                 /* Missed the backend's CLOSING state */
1234                 /* fall through */
1235         case XenbusStateClosing:
1236                 xenbus_frontend_closed(dev);
1237                 break;
1238         }
1239 }
1240
1241 static struct xenbus_driver pvcalls_front_driver = {
1242         .ids = pvcalls_front_ids,
1243         .probe = pvcalls_front_probe,
1244         .remove = pvcalls_front_remove,
1245         .otherend_changed = pvcalls_front_changed,
1246 };
1247
1248 static int __init pvcalls_frontend_init(void)
1249 {
1250         if (!xen_domain())
1251                 return -ENODEV;
1252
1253         pr_info("Initialising Xen pvcalls frontend driver\n");
1254
1255         return xenbus_register_frontend(&pvcalls_front_driver);
1256 }
1257
1258 module_init(pvcalls_frontend_init);
1259
1260 MODULE_DESCRIPTION("Xen PV Calls frontend driver");
1261 MODULE_AUTHOR("Stefano Stabellini <sstabellini@kernel.org>");
1262 MODULE_LICENSE("GPL");