Merge branch 'x86-urgent-for-linus' of git://git.kernel.org/pub/scm/linux/kernel...
[sfrench/cifs-2.6.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 void free_active_ring(struct sock_mapping *map)
345 {
346         if (!map->active.ring)
347                 return;
348
349         free_pages((unsigned long)map->active.data.in,
350                         map->active.ring->ring_order);
351         free_page((unsigned long)map->active.ring);
352 }
353
354 static int alloc_active_ring(struct sock_mapping *map)
355 {
356         void *bytes;
357
358         map->active.ring = (struct pvcalls_data_intf *)
359                 get_zeroed_page(GFP_KERNEL);
360         if (!map->active.ring)
361                 goto out;
362
363         map->active.ring->ring_order = PVCALLS_RING_ORDER;
364         bytes = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
365                                         PVCALLS_RING_ORDER);
366         if (!bytes)
367                 goto out;
368
369         map->active.data.in = bytes;
370         map->active.data.out = bytes +
371                 XEN_FLEX_RING_SIZE(PVCALLS_RING_ORDER);
372
373         return 0;
374
375 out:
376         free_active_ring(map);
377         return -ENOMEM;
378 }
379
380 static int create_active(struct sock_mapping *map, int *evtchn)
381 {
382         void *bytes;
383         int ret = -ENOMEM, irq = -1, i;
384
385         *evtchn = -1;
386         init_waitqueue_head(&map->active.inflight_conn_req);
387
388         bytes = map->active.data.in;
389         for (i = 0; i < (1 << PVCALLS_RING_ORDER); i++)
390                 map->active.ring->ref[i] = gnttab_grant_foreign_access(
391                         pvcalls_front_dev->otherend_id,
392                         pfn_to_gfn(virt_to_pfn(bytes) + i), 0);
393
394         map->active.ref = gnttab_grant_foreign_access(
395                 pvcalls_front_dev->otherend_id,
396                 pfn_to_gfn(virt_to_pfn((void *)map->active.ring)), 0);
397
398         ret = xenbus_alloc_evtchn(pvcalls_front_dev, evtchn);
399         if (ret)
400                 goto out_error;
401         irq = bind_evtchn_to_irqhandler(*evtchn, pvcalls_front_conn_handler,
402                                         0, "pvcalls-frontend", map);
403         if (irq < 0) {
404                 ret = irq;
405                 goto out_error;
406         }
407
408         map->active.irq = irq;
409         map->active_socket = true;
410         mutex_init(&map->active.in_mutex);
411         mutex_init(&map->active.out_mutex);
412
413         return 0;
414
415 out_error:
416         if (*evtchn >= 0)
417                 xenbus_free_evtchn(pvcalls_front_dev, *evtchn);
418         return ret;
419 }
420
421 int pvcalls_front_connect(struct socket *sock, struct sockaddr *addr,
422                                 int addr_len, int flags)
423 {
424         struct pvcalls_bedata *bedata;
425         struct sock_mapping *map = NULL;
426         struct xen_pvcalls_request *req;
427         int notify, req_id, ret, evtchn;
428
429         if (addr->sa_family != AF_INET || sock->type != SOCK_STREAM)
430                 return -EOPNOTSUPP;
431
432         map = pvcalls_enter_sock(sock);
433         if (IS_ERR(map))
434                 return PTR_ERR(map);
435
436         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
437         ret = alloc_active_ring(map);
438         if (ret < 0) {
439                 pvcalls_exit_sock(sock);
440                 return ret;
441         }
442
443         spin_lock(&bedata->socket_lock);
444         ret = get_request(bedata, &req_id);
445         if (ret < 0) {
446                 spin_unlock(&bedata->socket_lock);
447                 free_active_ring(map);
448                 pvcalls_exit_sock(sock);
449                 return ret;
450         }
451         ret = create_active(map, &evtchn);
452         if (ret < 0) {
453                 spin_unlock(&bedata->socket_lock);
454                 free_active_ring(map);
455                 pvcalls_exit_sock(sock);
456                 return ret;
457         }
458
459         req = RING_GET_REQUEST(&bedata->ring, req_id);
460         req->req_id = req_id;
461         req->cmd = PVCALLS_CONNECT;
462         req->u.connect.id = (uintptr_t)map;
463         req->u.connect.len = addr_len;
464         req->u.connect.flags = flags;
465         req->u.connect.ref = map->active.ref;
466         req->u.connect.evtchn = evtchn;
467         memcpy(req->u.connect.addr, addr, sizeof(*addr));
468
469         map->sock = sock;
470
471         bedata->ring.req_prod_pvt++;
472         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&bedata->ring, notify);
473         spin_unlock(&bedata->socket_lock);
474
475         if (notify)
476                 notify_remote_via_irq(bedata->irq);
477
478         wait_event(bedata->inflight_req,
479                    READ_ONCE(bedata->rsp[req_id].req_id) == req_id);
480
481         /* read req_id, then the content */
482         smp_rmb();
483         ret = bedata->rsp[req_id].ret;
484         bedata->rsp[req_id].req_id = PVCALLS_INVALID_ID;
485         pvcalls_exit_sock(sock);
486         return ret;
487 }
488
489 static int __write_ring(struct pvcalls_data_intf *intf,
490                         struct pvcalls_data *data,
491                         struct iov_iter *msg_iter,
492                         int len)
493 {
494         RING_IDX cons, prod, size, masked_prod, masked_cons;
495         RING_IDX array_size = XEN_FLEX_RING_SIZE(PVCALLS_RING_ORDER);
496         int32_t error;
497
498         error = intf->out_error;
499         if (error < 0)
500                 return error;
501         cons = intf->out_cons;
502         prod = intf->out_prod;
503         /* read indexes before continuing */
504         virt_mb();
505
506         size = pvcalls_queued(prod, cons, array_size);
507         if (size > array_size)
508                 return -EINVAL;
509         if (size == array_size)
510                 return 0;
511         if (len > array_size - size)
512                 len = array_size - size;
513
514         masked_prod = pvcalls_mask(prod, array_size);
515         masked_cons = pvcalls_mask(cons, array_size);
516
517         if (masked_prod < masked_cons) {
518                 len = copy_from_iter(data->out + masked_prod, len, msg_iter);
519         } else {
520                 if (len > array_size - masked_prod) {
521                         int ret = copy_from_iter(data->out + masked_prod,
522                                        array_size - masked_prod, msg_iter);
523                         if (ret != array_size - masked_prod) {
524                                 len = ret;
525                                 goto out;
526                         }
527                         len = ret + copy_from_iter(data->out, len - ret, msg_iter);
528                 } else {
529                         len = copy_from_iter(data->out + masked_prod, len, msg_iter);
530                 }
531         }
532 out:
533         /* write to ring before updating pointer */
534         virt_wmb();
535         intf->out_prod += len;
536
537         return len;
538 }
539
540 int pvcalls_front_sendmsg(struct socket *sock, struct msghdr *msg,
541                           size_t len)
542 {
543         struct pvcalls_bedata *bedata;
544         struct sock_mapping *map;
545         int sent, tot_sent = 0;
546         int count = 0, flags;
547
548         flags = msg->msg_flags;
549         if (flags & (MSG_CONFIRM|MSG_DONTROUTE|MSG_EOR|MSG_OOB))
550                 return -EOPNOTSUPP;
551
552         map = pvcalls_enter_sock(sock);
553         if (IS_ERR(map))
554                 return PTR_ERR(map);
555         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
556
557         mutex_lock(&map->active.out_mutex);
558         if ((flags & MSG_DONTWAIT) && !pvcalls_front_write_todo(map)) {
559                 mutex_unlock(&map->active.out_mutex);
560                 pvcalls_exit_sock(sock);
561                 return -EAGAIN;
562         }
563         if (len > INT_MAX)
564                 len = INT_MAX;
565
566 again:
567         count++;
568         sent = __write_ring(map->active.ring,
569                             &map->active.data, &msg->msg_iter,
570                             len);
571         if (sent > 0) {
572                 len -= sent;
573                 tot_sent += sent;
574                 notify_remote_via_irq(map->active.irq);
575         }
576         if (sent >= 0 && len > 0 && count < PVCALLS_FRONT_MAX_SPIN)
577                 goto again;
578         if (sent < 0)
579                 tot_sent = sent;
580
581         mutex_unlock(&map->active.out_mutex);
582         pvcalls_exit_sock(sock);
583         return tot_sent;
584 }
585
586 static int __read_ring(struct pvcalls_data_intf *intf,
587                        struct pvcalls_data *data,
588                        struct iov_iter *msg_iter,
589                        size_t len, int flags)
590 {
591         RING_IDX cons, prod, size, masked_prod, masked_cons;
592         RING_IDX array_size = XEN_FLEX_RING_SIZE(PVCALLS_RING_ORDER);
593         int32_t error;
594
595         cons = intf->in_cons;
596         prod = intf->in_prod;
597         error = intf->in_error;
598         /* get pointers before reading from the ring */
599         virt_rmb();
600
601         size = pvcalls_queued(prod, cons, array_size);
602         masked_prod = pvcalls_mask(prod, array_size);
603         masked_cons = pvcalls_mask(cons, array_size);
604
605         if (size == 0)
606                 return error ?: size;
607
608         if (len > size)
609                 len = size;
610
611         if (masked_prod > masked_cons) {
612                 len = copy_to_iter(data->in + masked_cons, len, msg_iter);
613         } else {
614                 if (len > (array_size - masked_cons)) {
615                         int ret = copy_to_iter(data->in + masked_cons,
616                                      array_size - masked_cons, msg_iter);
617                         if (ret != array_size - masked_cons) {
618                                 len = ret;
619                                 goto out;
620                         }
621                         len = ret + copy_to_iter(data->in, len - ret, msg_iter);
622                 } else {
623                         len = copy_to_iter(data->in + masked_cons, len, msg_iter);
624                 }
625         }
626 out:
627         /* read data from the ring before increasing the index */
628         virt_mb();
629         if (!(flags & MSG_PEEK))
630                 intf->in_cons += len;
631
632         return len;
633 }
634
635 int pvcalls_front_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
636                      int flags)
637 {
638         struct pvcalls_bedata *bedata;
639         int ret;
640         struct sock_mapping *map;
641
642         if (flags & (MSG_CMSG_CLOEXEC|MSG_ERRQUEUE|MSG_OOB|MSG_TRUNC))
643                 return -EOPNOTSUPP;
644
645         map = pvcalls_enter_sock(sock);
646         if (IS_ERR(map))
647                 return PTR_ERR(map);
648         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
649
650         mutex_lock(&map->active.in_mutex);
651         if (len > XEN_FLEX_RING_SIZE(PVCALLS_RING_ORDER))
652                 len = XEN_FLEX_RING_SIZE(PVCALLS_RING_ORDER);
653
654         while (!(flags & MSG_DONTWAIT) && !pvcalls_front_read_todo(map)) {
655                 wait_event_interruptible(map->active.inflight_conn_req,
656                                          pvcalls_front_read_todo(map));
657         }
658         ret = __read_ring(map->active.ring, &map->active.data,
659                           &msg->msg_iter, len, flags);
660
661         if (ret > 0)
662                 notify_remote_via_irq(map->active.irq);
663         if (ret == 0)
664                 ret = (flags & MSG_DONTWAIT) ? -EAGAIN : 0;
665         if (ret == -ENOTCONN)
666                 ret = 0;
667
668         mutex_unlock(&map->active.in_mutex);
669         pvcalls_exit_sock(sock);
670         return ret;
671 }
672
673 int pvcalls_front_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
674 {
675         struct pvcalls_bedata *bedata;
676         struct sock_mapping *map = NULL;
677         struct xen_pvcalls_request *req;
678         int notify, req_id, ret;
679
680         if (addr->sa_family != AF_INET || sock->type != SOCK_STREAM)
681                 return -EOPNOTSUPP;
682
683         map = pvcalls_enter_sock(sock);
684         if (IS_ERR(map))
685                 return PTR_ERR(map);
686         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
687
688         spin_lock(&bedata->socket_lock);
689         ret = get_request(bedata, &req_id);
690         if (ret < 0) {
691                 spin_unlock(&bedata->socket_lock);
692                 pvcalls_exit_sock(sock);
693                 return ret;
694         }
695         req = RING_GET_REQUEST(&bedata->ring, req_id);
696         req->req_id = req_id;
697         map->sock = sock;
698         req->cmd = PVCALLS_BIND;
699         req->u.bind.id = (uintptr_t)map;
700         memcpy(req->u.bind.addr, addr, sizeof(*addr));
701         req->u.bind.len = addr_len;
702
703         init_waitqueue_head(&map->passive.inflight_accept_req);
704
705         map->active_socket = false;
706
707         bedata->ring.req_prod_pvt++;
708         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&bedata->ring, notify);
709         spin_unlock(&bedata->socket_lock);
710         if (notify)
711                 notify_remote_via_irq(bedata->irq);
712
713         wait_event(bedata->inflight_req,
714                    READ_ONCE(bedata->rsp[req_id].req_id) == req_id);
715
716         /* read req_id, then the content */
717         smp_rmb();
718         ret = bedata->rsp[req_id].ret;
719         bedata->rsp[req_id].req_id = PVCALLS_INVALID_ID;
720
721         map->passive.status = PVCALLS_STATUS_BIND;
722         pvcalls_exit_sock(sock);
723         return 0;
724 }
725
726 int pvcalls_front_listen(struct socket *sock, int backlog)
727 {
728         struct pvcalls_bedata *bedata;
729         struct sock_mapping *map;
730         struct xen_pvcalls_request *req;
731         int notify, req_id, ret;
732
733         map = pvcalls_enter_sock(sock);
734         if (IS_ERR(map))
735                 return PTR_ERR(map);
736         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
737
738         if (map->passive.status != PVCALLS_STATUS_BIND) {
739                 pvcalls_exit_sock(sock);
740                 return -EOPNOTSUPP;
741         }
742
743         spin_lock(&bedata->socket_lock);
744         ret = get_request(bedata, &req_id);
745         if (ret < 0) {
746                 spin_unlock(&bedata->socket_lock);
747                 pvcalls_exit_sock(sock);
748                 return ret;
749         }
750         req = RING_GET_REQUEST(&bedata->ring, req_id);
751         req->req_id = req_id;
752         req->cmd = PVCALLS_LISTEN;
753         req->u.listen.id = (uintptr_t) map;
754         req->u.listen.backlog = backlog;
755
756         bedata->ring.req_prod_pvt++;
757         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&bedata->ring, notify);
758         spin_unlock(&bedata->socket_lock);
759         if (notify)
760                 notify_remote_via_irq(bedata->irq);
761
762         wait_event(bedata->inflight_req,
763                    READ_ONCE(bedata->rsp[req_id].req_id) == req_id);
764
765         /* read req_id, then the content */
766         smp_rmb();
767         ret = bedata->rsp[req_id].ret;
768         bedata->rsp[req_id].req_id = PVCALLS_INVALID_ID;
769
770         map->passive.status = PVCALLS_STATUS_LISTEN;
771         pvcalls_exit_sock(sock);
772         return ret;
773 }
774
775 int pvcalls_front_accept(struct socket *sock, struct socket *newsock, int flags)
776 {
777         struct pvcalls_bedata *bedata;
778         struct sock_mapping *map;
779         struct sock_mapping *map2 = NULL;
780         struct xen_pvcalls_request *req;
781         int notify, req_id, ret, evtchn, nonblock;
782
783         map = pvcalls_enter_sock(sock);
784         if (IS_ERR(map))
785                 return PTR_ERR(map);
786         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
787
788         if (map->passive.status != PVCALLS_STATUS_LISTEN) {
789                 pvcalls_exit_sock(sock);
790                 return -EINVAL;
791         }
792
793         nonblock = flags & SOCK_NONBLOCK;
794         /*
795          * Backend only supports 1 inflight accept request, will return
796          * errors for the others
797          */
798         if (test_and_set_bit(PVCALLS_FLAG_ACCEPT_INFLIGHT,
799                              (void *)&map->passive.flags)) {
800                 req_id = READ_ONCE(map->passive.inflight_req_id);
801                 if (req_id != PVCALLS_INVALID_ID &&
802                     READ_ONCE(bedata->rsp[req_id].req_id) == req_id) {
803                         map2 = map->passive.accept_map;
804                         goto received;
805                 }
806                 if (nonblock) {
807                         pvcalls_exit_sock(sock);
808                         return -EAGAIN;
809                 }
810                 if (wait_event_interruptible(map->passive.inflight_accept_req,
811                         !test_and_set_bit(PVCALLS_FLAG_ACCEPT_INFLIGHT,
812                                           (void *)&map->passive.flags))) {
813                         pvcalls_exit_sock(sock);
814                         return -EINTR;
815                 }
816         }
817
818         map2 = kzalloc(sizeof(*map2), GFP_KERNEL);
819         if (map2 == NULL) {
820                 clear_bit(PVCALLS_FLAG_ACCEPT_INFLIGHT,
821                           (void *)&map->passive.flags);
822                 pvcalls_exit_sock(sock);
823                 return -ENOMEM;
824         }
825         ret = alloc_active_ring(map2);
826         if (ret < 0) {
827                 clear_bit(PVCALLS_FLAG_ACCEPT_INFLIGHT,
828                                 (void *)&map->passive.flags);
829                 kfree(map2);
830                 pvcalls_exit_sock(sock);
831                 return ret;
832         }
833         spin_lock(&bedata->socket_lock);
834         ret = get_request(bedata, &req_id);
835         if (ret < 0) {
836                 clear_bit(PVCALLS_FLAG_ACCEPT_INFLIGHT,
837                           (void *)&map->passive.flags);
838                 spin_unlock(&bedata->socket_lock);
839                 free_active_ring(map2);
840                 kfree(map2);
841                 pvcalls_exit_sock(sock);
842                 return ret;
843         }
844
845         ret = create_active(map2, &evtchn);
846         if (ret < 0) {
847                 free_active_ring(map2);
848                 kfree(map2);
849                 clear_bit(PVCALLS_FLAG_ACCEPT_INFLIGHT,
850                           (void *)&map->passive.flags);
851                 spin_unlock(&bedata->socket_lock);
852                 pvcalls_exit_sock(sock);
853                 return ret;
854         }
855         list_add_tail(&map2->list, &bedata->socket_mappings);
856
857         req = RING_GET_REQUEST(&bedata->ring, req_id);
858         req->req_id = req_id;
859         req->cmd = PVCALLS_ACCEPT;
860         req->u.accept.id = (uintptr_t) map;
861         req->u.accept.ref = map2->active.ref;
862         req->u.accept.id_new = (uintptr_t) map2;
863         req->u.accept.evtchn = evtchn;
864         map->passive.accept_map = map2;
865
866         bedata->ring.req_prod_pvt++;
867         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&bedata->ring, notify);
868         spin_unlock(&bedata->socket_lock);
869         if (notify)
870                 notify_remote_via_irq(bedata->irq);
871         /* We could check if we have received a response before returning. */
872         if (nonblock) {
873                 WRITE_ONCE(map->passive.inflight_req_id, req_id);
874                 pvcalls_exit_sock(sock);
875                 return -EAGAIN;
876         }
877
878         if (wait_event_interruptible(bedata->inflight_req,
879                 READ_ONCE(bedata->rsp[req_id].req_id) == req_id)) {
880                 pvcalls_exit_sock(sock);
881                 return -EINTR;
882         }
883         /* read req_id, then the content */
884         smp_rmb();
885
886 received:
887         map2->sock = newsock;
888         newsock->sk = sk_alloc(sock_net(sock->sk), PF_INET, GFP_KERNEL, &pvcalls_proto, false);
889         if (!newsock->sk) {
890                 bedata->rsp[req_id].req_id = PVCALLS_INVALID_ID;
891                 map->passive.inflight_req_id = PVCALLS_INVALID_ID;
892                 clear_bit(PVCALLS_FLAG_ACCEPT_INFLIGHT,
893                           (void *)&map->passive.flags);
894                 pvcalls_front_free_map(bedata, map2);
895                 pvcalls_exit_sock(sock);
896                 return -ENOMEM;
897         }
898         newsock->sk->sk_send_head = (void *)map2;
899
900         ret = bedata->rsp[req_id].ret;
901         bedata->rsp[req_id].req_id = PVCALLS_INVALID_ID;
902         map->passive.inflight_req_id = PVCALLS_INVALID_ID;
903
904         clear_bit(PVCALLS_FLAG_ACCEPT_INFLIGHT, (void *)&map->passive.flags);
905         wake_up(&map->passive.inflight_accept_req);
906
907         pvcalls_exit_sock(sock);
908         return ret;
909 }
910
911 static __poll_t pvcalls_front_poll_passive(struct file *file,
912                                                struct pvcalls_bedata *bedata,
913                                                struct sock_mapping *map,
914                                                poll_table *wait)
915 {
916         int notify, req_id, ret;
917         struct xen_pvcalls_request *req;
918
919         if (test_bit(PVCALLS_FLAG_ACCEPT_INFLIGHT,
920                      (void *)&map->passive.flags)) {
921                 uint32_t req_id = READ_ONCE(map->passive.inflight_req_id);
922
923                 if (req_id != PVCALLS_INVALID_ID &&
924                     READ_ONCE(bedata->rsp[req_id].req_id) == req_id)
925                         return EPOLLIN | EPOLLRDNORM;
926
927                 poll_wait(file, &map->passive.inflight_accept_req, wait);
928                 return 0;
929         }
930
931         if (test_and_clear_bit(PVCALLS_FLAG_POLL_RET,
932                                (void *)&map->passive.flags))
933                 return EPOLLIN | EPOLLRDNORM;
934
935         /*
936          * First check RET, then INFLIGHT. No barriers necessary to
937          * ensure execution ordering because of the conditional
938          * instructions creating control dependencies.
939          */
940
941         if (test_and_set_bit(PVCALLS_FLAG_POLL_INFLIGHT,
942                              (void *)&map->passive.flags)) {
943                 poll_wait(file, &bedata->inflight_req, wait);
944                 return 0;
945         }
946
947         spin_lock(&bedata->socket_lock);
948         ret = get_request(bedata, &req_id);
949         if (ret < 0) {
950                 spin_unlock(&bedata->socket_lock);
951                 return ret;
952         }
953         req = RING_GET_REQUEST(&bedata->ring, req_id);
954         req->req_id = req_id;
955         req->cmd = PVCALLS_POLL;
956         req->u.poll.id = (uintptr_t) map;
957
958         bedata->ring.req_prod_pvt++;
959         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&bedata->ring, notify);
960         spin_unlock(&bedata->socket_lock);
961         if (notify)
962                 notify_remote_via_irq(bedata->irq);
963
964         poll_wait(file, &bedata->inflight_req, wait);
965         return 0;
966 }
967
968 static __poll_t pvcalls_front_poll_active(struct file *file,
969                                               struct pvcalls_bedata *bedata,
970                                               struct sock_mapping *map,
971                                               poll_table *wait)
972 {
973         __poll_t mask = 0;
974         int32_t in_error, out_error;
975         struct pvcalls_data_intf *intf = map->active.ring;
976
977         out_error = intf->out_error;
978         in_error = intf->in_error;
979
980         poll_wait(file, &map->active.inflight_conn_req, wait);
981         if (pvcalls_front_write_todo(map))
982                 mask |= EPOLLOUT | EPOLLWRNORM;
983         if (pvcalls_front_read_todo(map))
984                 mask |= EPOLLIN | EPOLLRDNORM;
985         if (in_error != 0 || out_error != 0)
986                 mask |= EPOLLERR;
987
988         return mask;
989 }
990
991 __poll_t pvcalls_front_poll(struct file *file, struct socket *sock,
992                                poll_table *wait)
993 {
994         struct pvcalls_bedata *bedata;
995         struct sock_mapping *map;
996         __poll_t ret;
997
998         map = pvcalls_enter_sock(sock);
999         if (IS_ERR(map))
1000                 return EPOLLNVAL;
1001         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
1002
1003         if (map->active_socket)
1004                 ret = pvcalls_front_poll_active(file, bedata, map, wait);
1005         else
1006                 ret = pvcalls_front_poll_passive(file, bedata, map, wait);
1007         pvcalls_exit_sock(sock);
1008         return ret;
1009 }
1010
1011 int pvcalls_front_release(struct socket *sock)
1012 {
1013         struct pvcalls_bedata *bedata;
1014         struct sock_mapping *map;
1015         int req_id, notify, ret;
1016         struct xen_pvcalls_request *req;
1017
1018         if (sock->sk == NULL)
1019                 return 0;
1020
1021         map = pvcalls_enter_sock(sock);
1022         if (IS_ERR(map)) {
1023                 if (PTR_ERR(map) == -ENOTCONN)
1024                         return -EIO;
1025                 else
1026                         return 0;
1027         }
1028         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
1029
1030         spin_lock(&bedata->socket_lock);
1031         ret = get_request(bedata, &req_id);
1032         if (ret < 0) {
1033                 spin_unlock(&bedata->socket_lock);
1034                 pvcalls_exit_sock(sock);
1035                 return ret;
1036         }
1037         sock->sk->sk_send_head = NULL;
1038
1039         req = RING_GET_REQUEST(&bedata->ring, req_id);
1040         req->req_id = req_id;
1041         req->cmd = PVCALLS_RELEASE;
1042         req->u.release.id = (uintptr_t)map;
1043
1044         bedata->ring.req_prod_pvt++;
1045         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&bedata->ring, notify);
1046         spin_unlock(&bedata->socket_lock);
1047         if (notify)
1048                 notify_remote_via_irq(bedata->irq);
1049
1050         wait_event(bedata->inflight_req,
1051                    READ_ONCE(bedata->rsp[req_id].req_id) == req_id);
1052
1053         if (map->active_socket) {
1054                 /*
1055                  * Set in_error and wake up inflight_conn_req to force
1056                  * recvmsg waiters to exit.
1057                  */
1058                 map->active.ring->in_error = -EBADF;
1059                 wake_up_interruptible(&map->active.inflight_conn_req);
1060
1061                 /*
1062                  * We need to make sure that sendmsg/recvmsg on this socket have
1063                  * not started before we've cleared sk_send_head here. The
1064                  * easiest way to guarantee this is to see that no pvcalls
1065                  * (other than us) is in progress on this socket.
1066                  */
1067                 while (atomic_read(&map->refcount) > 1)
1068                         cpu_relax();
1069
1070                 pvcalls_front_free_map(bedata, map);
1071         } else {
1072                 wake_up(&bedata->inflight_req);
1073                 wake_up(&map->passive.inflight_accept_req);
1074
1075                 while (atomic_read(&map->refcount) > 1)
1076                         cpu_relax();
1077
1078                 spin_lock(&bedata->socket_lock);
1079                 list_del(&map->list);
1080                 spin_unlock(&bedata->socket_lock);
1081                 if (READ_ONCE(map->passive.inflight_req_id) != PVCALLS_INVALID_ID &&
1082                         READ_ONCE(map->passive.inflight_req_id) != 0) {
1083                         pvcalls_front_free_map(bedata,
1084                                                map->passive.accept_map);
1085                 }
1086                 kfree(map);
1087         }
1088         WRITE_ONCE(bedata->rsp[req_id].req_id, PVCALLS_INVALID_ID);
1089
1090         pvcalls_exit();
1091         return 0;
1092 }
1093
1094 static const struct xenbus_device_id pvcalls_front_ids[] = {
1095         { "pvcalls" },
1096         { "" }
1097 };
1098
1099 static int pvcalls_front_remove(struct xenbus_device *dev)
1100 {
1101         struct pvcalls_bedata *bedata;
1102         struct sock_mapping *map = NULL, *n;
1103
1104         bedata = dev_get_drvdata(&pvcalls_front_dev->dev);
1105         dev_set_drvdata(&dev->dev, NULL);
1106         pvcalls_front_dev = NULL;
1107         if (bedata->irq >= 0)
1108                 unbind_from_irqhandler(bedata->irq, dev);
1109
1110         list_for_each_entry_safe(map, n, &bedata->socket_mappings, list) {
1111                 map->sock->sk->sk_send_head = NULL;
1112                 if (map->active_socket) {
1113                         map->active.ring->in_error = -EBADF;
1114                         wake_up_interruptible(&map->active.inflight_conn_req);
1115                 }
1116         }
1117
1118         smp_mb();
1119         while (atomic_read(&pvcalls_refcount) > 0)
1120                 cpu_relax();
1121         list_for_each_entry_safe(map, n, &bedata->socket_mappings, list) {
1122                 if (map->active_socket) {
1123                         /* No need to lock, refcount is 0 */
1124                         pvcalls_front_free_map(bedata, map);
1125                 } else {
1126                         list_del(&map->list);
1127                         kfree(map);
1128                 }
1129         }
1130         if (bedata->ref != -1)
1131                 gnttab_end_foreign_access(bedata->ref, 0, 0);
1132         kfree(bedata->ring.sring);
1133         kfree(bedata);
1134         xenbus_switch_state(dev, XenbusStateClosed);
1135         return 0;
1136 }
1137
1138 static int pvcalls_front_probe(struct xenbus_device *dev,
1139                           const struct xenbus_device_id *id)
1140 {
1141         int ret = -ENOMEM, evtchn, i;
1142         unsigned int max_page_order, function_calls, len;
1143         char *versions;
1144         grant_ref_t gref_head = 0;
1145         struct xenbus_transaction xbt;
1146         struct pvcalls_bedata *bedata = NULL;
1147         struct xen_pvcalls_sring *sring;
1148
1149         if (pvcalls_front_dev != NULL) {
1150                 dev_err(&dev->dev, "only one PV Calls connection supported\n");
1151                 return -EINVAL;
1152         }
1153
1154         versions = xenbus_read(XBT_NIL, dev->otherend, "versions", &len);
1155         if (IS_ERR(versions))
1156                 return PTR_ERR(versions);
1157         if (!len)
1158                 return -EINVAL;
1159         if (strcmp(versions, "1")) {
1160                 kfree(versions);
1161                 return -EINVAL;
1162         }
1163         kfree(versions);
1164         max_page_order = xenbus_read_unsigned(dev->otherend,
1165                                               "max-page-order", 0);
1166         if (max_page_order < PVCALLS_RING_ORDER)
1167                 return -ENODEV;
1168         function_calls = xenbus_read_unsigned(dev->otherend,
1169                                               "function-calls", 0);
1170         /* See XENBUS_FUNCTIONS_CALLS in pvcalls.h */
1171         if (function_calls != 1)
1172                 return -ENODEV;
1173         pr_info("%s max-page-order is %u\n", __func__, max_page_order);
1174
1175         bedata = kzalloc(sizeof(struct pvcalls_bedata), GFP_KERNEL);
1176         if (!bedata)
1177                 return -ENOMEM;
1178
1179         dev_set_drvdata(&dev->dev, bedata);
1180         pvcalls_front_dev = dev;
1181         init_waitqueue_head(&bedata->inflight_req);
1182         INIT_LIST_HEAD(&bedata->socket_mappings);
1183         spin_lock_init(&bedata->socket_lock);
1184         bedata->irq = -1;
1185         bedata->ref = -1;
1186
1187         for (i = 0; i < PVCALLS_NR_RSP_PER_RING; i++)
1188                 bedata->rsp[i].req_id = PVCALLS_INVALID_ID;
1189
1190         sring = (struct xen_pvcalls_sring *) __get_free_page(GFP_KERNEL |
1191                                                              __GFP_ZERO);
1192         if (!sring)
1193                 goto error;
1194         SHARED_RING_INIT(sring);
1195         FRONT_RING_INIT(&bedata->ring, sring, XEN_PAGE_SIZE);
1196
1197         ret = xenbus_alloc_evtchn(dev, &evtchn);
1198         if (ret)
1199                 goto error;
1200
1201         bedata->irq = bind_evtchn_to_irqhandler(evtchn,
1202                                                 pvcalls_front_event_handler,
1203                                                 0, "pvcalls-frontend", dev);
1204         if (bedata->irq < 0) {
1205                 ret = bedata->irq;
1206                 goto error;
1207         }
1208
1209         ret = gnttab_alloc_grant_references(1, &gref_head);
1210         if (ret < 0)
1211                 goto error;
1212         ret = gnttab_claim_grant_reference(&gref_head);
1213         if (ret < 0)
1214                 goto error;
1215         bedata->ref = ret;
1216         gnttab_grant_foreign_access_ref(bedata->ref, dev->otherend_id,
1217                                         virt_to_gfn((void *)sring), 0);
1218
1219  again:
1220         ret = xenbus_transaction_start(&xbt);
1221         if (ret) {
1222                 xenbus_dev_fatal(dev, ret, "starting transaction");
1223                 goto error;
1224         }
1225         ret = xenbus_printf(xbt, dev->nodename, "version", "%u", 1);
1226         if (ret)
1227                 goto error_xenbus;
1228         ret = xenbus_printf(xbt, dev->nodename, "ring-ref", "%d", bedata->ref);
1229         if (ret)
1230                 goto error_xenbus;
1231         ret = xenbus_printf(xbt, dev->nodename, "port", "%u",
1232                             evtchn);
1233         if (ret)
1234                 goto error_xenbus;
1235         ret = xenbus_transaction_end(xbt, 0);
1236         if (ret) {
1237                 if (ret == -EAGAIN)
1238                         goto again;
1239                 xenbus_dev_fatal(dev, ret, "completing transaction");
1240                 goto error;
1241         }
1242         xenbus_switch_state(dev, XenbusStateInitialised);
1243
1244         return 0;
1245
1246  error_xenbus:
1247         xenbus_transaction_end(xbt, 1);
1248         xenbus_dev_fatal(dev, ret, "writing xenstore");
1249  error:
1250         pvcalls_front_remove(dev);
1251         return ret;
1252 }
1253
1254 static void pvcalls_front_changed(struct xenbus_device *dev,
1255                             enum xenbus_state backend_state)
1256 {
1257         switch (backend_state) {
1258         case XenbusStateReconfiguring:
1259         case XenbusStateReconfigured:
1260         case XenbusStateInitialising:
1261         case XenbusStateInitialised:
1262         case XenbusStateUnknown:
1263                 break;
1264
1265         case XenbusStateInitWait:
1266                 break;
1267
1268         case XenbusStateConnected:
1269                 xenbus_switch_state(dev, XenbusStateConnected);
1270                 break;
1271
1272         case XenbusStateClosed:
1273                 if (dev->state == XenbusStateClosed)
1274                         break;
1275                 /* Missed the backend's CLOSING state */
1276                 /* fall through */
1277         case XenbusStateClosing:
1278                 xenbus_frontend_closed(dev);
1279                 break;
1280         }
1281 }
1282
1283 static struct xenbus_driver pvcalls_front_driver = {
1284         .ids = pvcalls_front_ids,
1285         .probe = pvcalls_front_probe,
1286         .remove = pvcalls_front_remove,
1287         .otherend_changed = pvcalls_front_changed,
1288 };
1289
1290 static int __init pvcalls_frontend_init(void)
1291 {
1292         if (!xen_domain())
1293                 return -ENODEV;
1294
1295         pr_info("Initialising Xen pvcalls frontend driver\n");
1296
1297         return xenbus_register_frontend(&pvcalls_front_driver);
1298 }
1299
1300 module_init(pvcalls_frontend_init);
1301
1302 MODULE_DESCRIPTION("Xen PV Calls frontend driver");
1303 MODULE_AUTHOR("Stefano Stabellini <sstabellini@kernel.org>");
1304 MODULE_LICENSE("GPL");