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