usb: gadget: f_fs: Prevent panic due to failure of huge size buffer allocation
[platform/kernel/linux-rpi.git] / samples / kdbus / kdbus-workers.c
1 /*
2  * Copyright (C) 2013-2015 David Herrmann <dh.herrmann@gmail.com>
3  *
4  * kdbus is free software; you can redistribute it and/or modify it under
5  * the terms of the GNU Lesser General Public License as published by the
6  * Free Software Foundation; either version 2.1 of the License, or (at
7  * your option) any later version.
8  */
9
10 /*
11  * Example: Workers
12  * This program computes prime-numbers based on the sieve of Eratosthenes. The
13  * master sets up a shared memory region and spawns workers which clear out the
14  * non-primes. The master reacts to keyboard input and to client-requests to
15  * control what each worker does. Note that this is in no way meant as efficient
16  * way to compute primes. It should only serve as example how a master/worker
17  * concept can be implemented with kdbus used as control messages.
18  *
19  * The main process is called the 'master'. It creates a new, private bus which
20  * will be used between the master and its workers to communicate. The master
21  * then spawns a fixed number of workers. Whenever a worker dies (detected via
22  * SIGCHLD), the master spawns a new worker. When done, the master waits for all
23  * workers to exit, prints a status report and exits itself.
24  *
25  * The master process does *not* keep track of its workers. Instead, this
26  * example implements a PULL model. That is, the master acquires a well-known
27  * name on the bus which each worker uses to request tasks from the master. If
28  * there are no more tasks, the master will return an empty task-list, which
29  * casues a worker to exit immediately.
30  *
31  * As tasks can be computationally expensive, we support cancellation. Whenever
32  * the master process is interrupted, it will drop its well-known name on the
33  * bus. This causes kdbus to broadcast a name-change notification. The workers
34  * check for broadcast messages regularly and will exit if they receive one.
35  *
36  * This example exists of 4 objects:
37  *  * master: The master object contains the context of the master process. This
38  *            process manages the prime-context, spawns workers and assigns
39  *            prime-ranges to each worker to compute.
40  *            The master itself does not do any prime-computations itself.
41  *  * child:  The child object contains the context of a worker. It inherits the
42  *            prime context from its parent (the master) and then creates a new
43  *            bus context to request prime-ranges to compute.
44  *  * prime:  The "prime" object is used to abstract how we compute primes. When
45  *            allocated, it prepares a memory region to hold 1 bit for each
46  *            natural number up to a fixed maximum ('MAX_PRIMES').
47  *            The memory region is backed by a memfd which we share between
48  *            processes. Each worker now gets assigned a range of natural
49  *            numbers which it clears multiples of off the memory region. The
50  *            master process is responsible of distributing all natural numbers
51  *            up to the fixed maximum to its workers.
52  *  * bus:    The bus object is an abstraction of the kdbus API. It is pretty
53  *            straightfoward and only manages the connection-fd plus the
54  *            memory-mapped pool in a single object.
55  *
56  * This example is in reversed order, which should make it easier to read
57  * top-down, but requires some forward-declarations. Just ignore those.
58  */
59
60 #include <ctype.h>
61 #include <errno.h>
62 #include <fcntl.h>
63 #include <linux/memfd.h>
64 #include <signal.h>
65 #include <stdbool.h>
66 #include <stddef.h>
67 #include <stdint.h>
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <sys/mman.h>
72 #include <sys/poll.h>
73 #include <sys/signalfd.h>
74 #include <sys/syscall.h>
75 #include <sys/time.h>
76 #include <sys/wait.h>
77 #include <time.h>
78 #include <unistd.h>
79 #include "kdbus-api.h"
80
81 /* FORWARD DECLARATIONS */
82
83 #define POOL_SIZE (16 * 1024 * 1024)
84 #define MAX_PRIMES (2UL << 24)
85 #define WORKER_COUNT (16)
86 #define PRIME_STEPS (65536 * 4)
87
88 static const char *arg_busname = "example-workers";
89 static const char *arg_modname = "kdbus";
90 static const char *arg_master = "org.freedesktop.master";
91
92 static int err_assert(int r_errno, const char *msg, const char *func, int line,
93                       const char *file)
94 {
95         r_errno = (r_errno != 0) ? -abs(r_errno) : -EFAULT;
96         if (r_errno < 0) {
97                 errno = -r_errno;
98                 fprintf(stderr, "ERR: %s: %m (%s:%d in %s)\n",
99                         msg, func, line, file);
100         }
101         return r_errno;
102 }
103
104 #define err_r(_r, _msg) err_assert((_r), (_msg), __func__, __LINE__, __FILE__)
105 #define err(_msg) err_r(errno, (_msg))
106
107 struct prime;
108 struct bus;
109 struct master;
110 struct child;
111
112 struct prime {
113         int fd;
114         uint8_t *area;
115         size_t max;
116         size_t done;
117         size_t status;
118 };
119
120 static int prime_new(struct prime **out);
121 static void prime_free(struct prime *p);
122 static bool prime_done(struct prime *p);
123 static void prime_consume(struct prime *p, size_t amount);
124 static int prime_run(struct prime *p, struct bus *cancel, size_t number);
125 static void prime_print(struct prime *p);
126
127 struct bus {
128         int fd;
129         uint8_t *pool;
130 };
131
132 static int bus_open_connection(struct bus **out, uid_t uid, const char *name,
133                                uint64_t recv_flags);
134 static void bus_close_connection(struct bus *b);
135 static void bus_poool_free_slice(struct bus *b, uint64_t offset);
136 static int bus_acquire_name(struct bus *b, const char *name);
137 static int bus_install_name_loss_match(struct bus *b, const char *name);
138 static int bus_poll(struct bus *b);
139 static int bus_make(uid_t uid, const char *name);
140
141 struct master {
142         size_t n_workers;
143         size_t max_workers;
144
145         int signal_fd;
146         int control_fd;
147
148         struct prime *prime;
149         struct bus *bus;
150 };
151
152 static int master_new(struct master **out);
153 static void master_free(struct master *m);
154 static int master_run(struct master *m);
155 static int master_poll(struct master *m);
156 static int master_handle_stdin(struct master *m);
157 static int master_handle_signal(struct master *m);
158 static int master_handle_bus(struct master *m);
159 static int master_reply(struct master *m, const struct kdbus_msg *msg);
160 static int master_waitpid(struct master *m);
161 static int master_spawn(struct master *m);
162
163 struct child {
164         struct bus *bus;
165         struct prime *prime;
166 };
167
168 static int child_new(struct child **out, struct prime *p);
169 static void child_free(struct child *c);
170 static int child_run(struct child *c);
171
172 /* END OF FORWARD DECLARATIONS */
173
174 /*
175  * This is the main entrypoint of this example. It is pretty straightforward. We
176  * create a master object, run the computation, print a status report and then
177  * exit. Nothing particularly interesting here, so lets look into the master
178  * object...
179  */
180 int main(int argc, char **argv)
181 {
182         struct master *m = NULL;
183         int r;
184
185         r = master_new(&m);
186         if (r < 0)
187                 goto out;
188
189         r = master_run(m);
190         if (r < 0)
191                 goto out;
192
193         if (0)
194                 prime_print(m->prime);
195
196 out:
197         master_free(m);
198         if (r < 0 && r != -EINTR)
199                 fprintf(stderr, "failed\n");
200         else
201                 fprintf(stderr, "done\n");
202         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
203 }
204
205 /*
206  * ...this will allocate a new master context. It keeps track of the current
207  * number of children/workers that are running, manages a signalfd to track
208  * SIGCHLD, and creates a private kdbus bus. Afterwards, it opens its connection
209  * to the bus and acquires a well known-name (arg_master).
210  */
211 static int master_new(struct master **out)
212 {
213         struct master *m;
214         sigset_t smask;
215         int r;
216
217         m = calloc(1, sizeof(*m));
218         if (!m)
219                 return err("cannot allocate master");
220
221         m->max_workers = WORKER_COUNT;
222         m->signal_fd = -1;
223         m->control_fd = -1;
224
225         /* Block SIGINT and SIGCHLD signals */
226         sigemptyset(&smask);
227         sigaddset(&smask, SIGINT);
228         sigaddset(&smask, SIGCHLD);
229         sigprocmask(SIG_BLOCK, &smask, NULL);
230
231         m->signal_fd = signalfd(-1, &smask, SFD_CLOEXEC);
232         if (m->signal_fd < 0) {
233                 r = err("cannot create signalfd");
234                 goto error;
235         }
236
237         r = prime_new(&m->prime);
238         if (r < 0)
239                 goto error;
240
241         m->control_fd = bus_make(getuid(), arg_busname);
242         if (m->control_fd < 0) {
243                 r = m->control_fd;
244                 goto error;
245         }
246
247         /*
248          * Open a bus connection for the master, and require each received
249          * message to have a metadata item of type KDBUS_ITEM_PIDS attached.
250          * The current UID is needed to compute the name of the bus node to
251          * connect to.
252          */
253         r = bus_open_connection(&m->bus, getuid(),
254                                 arg_busname, KDBUS_ATTACH_PIDS);
255         if (r < 0)
256                 goto error;
257
258         /*
259          * Acquire a well-known name on the bus, so children can address
260          * messages to the master using KDBUS_DST_ID_NAME as destination-ID
261          * of messages.
262          */
263         r = bus_acquire_name(m->bus, arg_master);
264         if (r < 0)
265                 goto error;
266
267         *out = m;
268         return 0;
269
270 error:
271         master_free(m);
272         return r;
273 }
274
275 /* pretty straightforward destructor of a master object */
276 static void master_free(struct master *m)
277 {
278         if (!m)
279                 return;
280
281         bus_close_connection(m->bus);
282         if (m->control_fd >= 0)
283                 close(m->control_fd);
284         prime_free(m->prime);
285         if (m->signal_fd >= 0)
286                 close(m->signal_fd);
287         free(m);
288 }
289
290 static int master_run(struct master *m)
291 {
292         int res, r = 0;
293
294         while (!prime_done(m->prime)) {
295                 while (m->n_workers < m->max_workers) {
296                         r = master_spawn(m);
297                         if (r < 0)
298                                 break;
299                 }
300
301                 r = master_poll(m);
302                 if (r < 0)
303                         break;
304         }
305
306         if (r < 0) {
307                 bus_close_connection(m->bus);
308                 m->bus = NULL;
309         }
310
311         while (m->n_workers > 0) {
312                 res = master_poll(m);
313                 if (res < 0) {
314                         if (m->bus) {
315                                 bus_close_connection(m->bus);
316                                 m->bus = NULL;
317                         }
318                         r = res;
319                 }
320         }
321
322         return r == -EINTR ? 0 : r;
323 }
324
325 static int master_poll(struct master *m)
326 {
327         struct pollfd fds[3] = {};
328         int r = 0, n = 0;
329
330         /*
331          * Add stdin, the eventfd and the connection owner file descriptor to
332          * the pollfd table, and handle incoming traffic on the latter in
333          * master_handle_bus().
334          */
335         fds[n].fd = STDIN_FILENO;
336         fds[n++].events = POLLIN;
337         fds[n].fd = m->signal_fd;
338         fds[n++].events = POLLIN;
339         if (m->bus) {
340                 fds[n].fd = m->bus->fd;
341                 fds[n++].events = POLLIN;
342         }
343
344         r = poll(fds, n, -1);
345         if (r < 0)
346                 return err("poll() failed");
347
348         if (fds[0].revents & POLLIN)
349                 r = master_handle_stdin(m);
350         else if (fds[0].revents)
351                 r = err("ERR/HUP on stdin");
352         if (r < 0)
353                 return r;
354
355         if (fds[1].revents & POLLIN)
356                 r = master_handle_signal(m);
357         else if (fds[1].revents)
358                 r = err("ERR/HUP on signalfd");
359         if (r < 0)
360                 return r;
361
362         if (fds[2].revents & POLLIN)
363                 r = master_handle_bus(m);
364         else if (fds[2].revents)
365                 r = err("ERR/HUP on bus");
366
367         return r;
368 }
369
370 static int master_handle_stdin(struct master *m)
371 {
372         char buf[128];
373         ssize_t l;
374         int r = 0;
375
376         l = read(STDIN_FILENO, buf, sizeof(buf));
377         if (l < 0)
378                 return err("cannot read stdin");
379         if (l == 0)
380                 return err_r(-EINVAL, "EOF on stdin");
381
382         while (l-- > 0) {
383                 switch (buf[l]) {
384                 case 'q':
385                         /* quit */
386                         r = -EINTR;
387                         break;
388                 case '\n':
389                 case ' ':
390                         /* ignore */
391                         break;
392                 default:
393                         if (isgraph(buf[l]))
394                                 fprintf(stderr, "invalid input '%c'\n", buf[l]);
395                         else
396                                 fprintf(stderr, "invalid input 0x%x\n", buf[l]);
397                         break;
398                 }
399         }
400
401         return r;
402 }
403
404 static int master_handle_signal(struct master *m)
405 {
406         struct signalfd_siginfo val;
407         ssize_t l;
408
409         l = read(m->signal_fd, &val, sizeof(val));
410         if (l < 0)
411                 return err("cannot read signalfd");
412         if (l != sizeof(val))
413                 return err_r(-EINVAL, "invalid data from signalfd");
414
415         switch (val.ssi_signo) {
416         case SIGCHLD:
417                 return master_waitpid(m);
418         case SIGINT:
419                 return err_r(-EINTR, "interrupted");
420         default:
421                 return err_r(-EINVAL, "caught invalid signal");
422         }
423 }
424
425 static int master_handle_bus(struct master *m)
426 {
427         struct kdbus_cmd_recv recv = { .size = sizeof(recv) };
428         const struct kdbus_msg *msg = NULL;
429         const struct kdbus_item *item;
430         const struct kdbus_vec *vec = NULL;
431         int r = 0;
432
433         /*
434          * To receive a message, the KDBUS_CMD_RECV ioctl is used.
435          * It takes an argument of type 'struct kdbus_cmd_recv', which
436          * will contain information on the received message when the call
437          * returns. See kdbus.message(7).
438          */
439         r = kdbus_cmd_recv(m->bus->fd, &recv);
440         /*
441          * EAGAIN is returned when there is no message waiting on this
442          * connection. This is not an error - simply bail out.
443          */
444         if (r == -EAGAIN)
445                 return 0;
446         if (r < 0)
447                 return err_r(r, "cannot receive message");
448
449         /*
450          * Messages received by a connection are stored inside the connection's
451          * pool, at an offset that has been returned in the 'recv' command
452          * struct above. The value describes the relative offset from the
453          * start address of the pool. A message is described with
454          * 'struct kdbus_msg'. See kdbus.message(7).
455          */
456         msg = (void *)(m->bus->pool + recv.msg.offset);
457
458         /*
459          * A messages describes its actual payload in an array of items.
460          * KDBUS_FOREACH() is a simple iterator that walks such an array.
461          * struct kdbus_msg has a field to denote its total size, which is
462          * needed to determine the number of items in the array.
463          */
464         KDBUS_FOREACH(item, msg->items,
465                       msg->size - offsetof(struct kdbus_msg, items)) {
466                 /*
467                  * An item of type PAYLOAD_OFF describes in-line memory
468                  * stored in the pool at a described offset. That offset is
469                  * relative to the start address of the message header.
470                  * This example program only expects one single item of that
471                  * type, remembers the struct kdbus_vec member of the item
472                  * when it sees it, and bails out if there is more than one
473                  * of them.
474                  */
475                 if (item->type == KDBUS_ITEM_PAYLOAD_OFF) {
476                         if (vec) {
477                                 r = err_r(-EEXIST,
478                                           "message with multiple vecs");
479                                 break;
480                         }
481                         vec = &item->vec;
482                         if (vec->size != 1) {
483                                 r = err_r(-EINVAL, "invalid message size");
484                                 break;
485                         }
486
487                 /*
488                  * MEMFDs are transported as items of type PAYLOAD_MEMFD.
489                  * If such an item is attached, a new file descriptor was
490                  * installed into the task when KDBUS_CMD_RECV was called, and
491                  * its number is stored in item->memfd.fd.
492                  * Implementers *must* handle this item type and close the
493                  * file descriptor when no longer needed in order to prevent
494                  * file descriptor exhaustion. This example program just bails
495                  * out with an error in this case, as memfds are not expected
496                  * in this context.
497                  */
498                 } else if (item->type == KDBUS_ITEM_PAYLOAD_MEMFD) {
499                         r = err_r(-EINVAL, "message with memfd");
500                         break;
501                 }
502         }
503         if (r < 0)
504                 goto exit;
505         if (!vec) {
506                 r = err_r(-EINVAL, "empty message");
507                 goto exit;
508         }
509
510         switch (*((const uint8_t *)msg + vec->offset)) {
511         case 'r': {
512                 r = master_reply(m, msg);
513                 break;
514         }
515         default:
516                 r = err_r(-EINVAL, "invalid message type");
517                 break;
518         }
519
520 exit:
521         /*
522          * We are done with the memory slice that was given to us through
523          * recv.msg.offset. Tell the kernel it can use it for other content
524          * in the future. See kdbus.pool(7).
525          */
526         bus_poool_free_slice(m->bus, recv.msg.offset);
527         return r;
528 }
529
530 static int master_reply(struct master *m, const struct kdbus_msg *msg)
531 {
532         struct kdbus_cmd_send cmd;
533         struct kdbus_item *item;
534         struct kdbus_msg *reply;
535         size_t size, status, p[2];
536         int r;
537
538         /*
539          * This functions sends a message over kdbus. To do this, it uses the
540          * KDBUS_CMD_SEND ioctl, which takes a command struct argument of type
541          * 'struct kdbus_cmd_send'. This struct stores a pointer to the actual
542          * message to send. See kdbus.message(7).
543          */
544         p[0] = m->prime->done;
545         p[1] = prime_done(m->prime) ? 0 : PRIME_STEPS;
546
547         size = sizeof(*reply);
548         size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
549
550         /* Prepare the message to send */
551         reply = alloca(size);
552         memset(reply, 0, size);
553         reply->size = size;
554
555         /* Each message has a cookie that can be used to send replies */
556         reply->cookie = 1;
557
558         /* The payload_type is arbitrary, but it must be non-zero */
559         reply->payload_type = 0xdeadbeef;
560
561         /*
562          * We are sending a reply. Let the kernel know the cookie of the
563          * message we are replying to.
564          */
565         reply->cookie_reply = msg->cookie;
566
567         /*
568          * Messages can either be directed to a well-known name (stored as
569          * string) or to a unique name (stored as number). This example does
570          * the latter. If the message would be directed to a well-known name
571          * instead, the message's dst_id field would be set to
572          * KDBUS_DST_ID_NAME, and the name would be attaches in an item of type
573          * KDBUS_ITEM_DST_NAME. See below for an example, and also refer to
574          * kdbus.message(7).
575          */
576         reply->dst_id = msg->src_id;
577
578         /* Our message has exactly one item to store its payload */
579         item = reply->items;
580         item->type = KDBUS_ITEM_PAYLOAD_VEC;
581         item->size = KDBUS_ITEM_HEADER_SIZE + sizeof(struct kdbus_vec);
582         item->vec.address = (uintptr_t)p;
583         item->vec.size = sizeof(p);
584
585         /*
586          * Now prepare the command struct, and reference the message we want
587          * to send.
588          */
589         memset(&cmd, 0, sizeof(cmd));
590         cmd.size = sizeof(cmd);
591         cmd.msg_address = (uintptr_t)reply;
592
593         /*
594          * Finally, employ the command on the connection owner
595          * file descriptor.
596          */
597         r = kdbus_cmd_send(m->bus->fd, &cmd);
598         if (r < 0)
599                 return err_r(r, "cannot send reply");
600
601         if (p[1]) {
602                 prime_consume(m->prime, p[1]);
603                 status = m->prime->done * 10000 / m->prime->max;
604                 if (status != m->prime->status) {
605                         m->prime->status = status;
606                         fprintf(stderr, "status: %7.3lf%%\n",
607                                 (double)status / 100);
608                 }
609         }
610
611         return 0;
612 }
613
614 static int master_waitpid(struct master *m)
615 {
616         pid_t pid;
617         int r;
618
619         while ((pid = waitpid(-1, &r, WNOHANG)) > 0) {
620                 if (m->n_workers > 0)
621                         --m->n_workers;
622                 if (!WIFEXITED(r))
623                         r = err_r(-EINVAL, "child died unexpectedly");
624                 else if (WEXITSTATUS(r) != 0)
625                         r = err_r(-WEXITSTATUS(r), "child failed");
626         }
627
628         return r;
629 }
630
631 static int master_spawn(struct master *m)
632 {
633         struct child *c = NULL;
634         struct prime *p = NULL;
635         pid_t pid;
636         int r;
637
638         /* Spawn off one child and call child_run() inside it */
639
640         pid = fork();
641         if (pid < 0)
642                 return err("cannot fork");
643         if (pid > 0) {
644                 /* parent */
645                 ++m->n_workers;
646                 return 0;
647         }
648
649         /* child */
650
651         p = m->prime;
652         m->prime = NULL;
653         master_free(m);
654
655         r = child_new(&c, p);
656         if (r < 0)
657                 goto exit;
658
659         r = child_run(c);
660
661 exit:
662         child_free(c);
663         exit(abs(r));
664 }
665
666 static int child_new(struct child **out, struct prime *p)
667 {
668         struct child *c;
669         int r;
670
671         c = calloc(1, sizeof(*c));
672         if (!c)
673                 return err("cannot allocate child");
674
675         c->prime = p;
676
677         /*
678          * Open a connection to the bus and require each received message to
679          * carry a list of the well-known names the sendind connection currently
680          * owns. The current UID is needed in order to determine the name of the
681          * bus node to connect to.
682          */
683         r = bus_open_connection(&c->bus, getuid(),
684                                 arg_busname, KDBUS_ATTACH_NAMES);
685         if (r < 0)
686                 goto error;
687
688         /*
689          * Install a kdbus match so the child's connection gets notified when
690          * the master loses its well-known name.
691          */
692         r = bus_install_name_loss_match(c->bus, arg_master);
693         if (r < 0)
694                 goto error;
695
696         *out = c;
697         return 0;
698
699 error:
700         child_free(c);
701         return r;
702 }
703
704 static void child_free(struct child *c)
705 {
706         if (!c)
707                 return;
708
709         bus_close_connection(c->bus);
710         prime_free(c->prime);
711         free(c);
712 }
713
714 static int child_run(struct child *c)
715 {
716         struct kdbus_cmd_send cmd;
717         struct kdbus_item *item;
718         struct kdbus_vec *vec = NULL;
719         struct kdbus_msg *msg;
720         struct timespec spec;
721         size_t n, steps, size;
722         int r = 0;
723
724         /*
725          * Let's send a message to the master and ask for work. To do this,
726          * we use the KDBUS_CMD_SEND ioctl, which takes an argument of type
727          * 'struct kdbus_cmd_send'. This struct stores a pointer to the actual
728          * message to send. See kdbus.message(7).
729          */
730         size = sizeof(*msg);
731         size += KDBUS_ITEM_SIZE(strlen(arg_master) + 1);
732         size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
733
734         msg = alloca(size);
735         memset(msg, 0, size);
736         msg->size = size;
737
738         /*
739          * Tell the kernel that we expect a reply to this message. This means
740          * that
741          *
742          * a) The remote peer will gain temporary permission to talk to us
743          *    even if it would not be allowed to normally.
744          *
745          * b) A timeout value is required.
746          *
747          *    For asynchronous send commands, if no reply is received, we will
748          *    get a kernel notification with an item of type
749          *    KDBUS_ITEM_REPLY_TIMEOUT attached.
750          *
751          *    For synchronous send commands (which this example does), the
752          *    ioctl will block until a reply is received or the timeout is
753          *    exceeded.
754          */
755         msg->flags = KDBUS_MSG_EXPECT_REPLY;
756
757         /* Set our cookie. Replies must use this cookie to send their reply. */
758         msg->cookie = 1;
759
760         /* The payload_type is arbitrary, but it must be non-zero */
761         msg->payload_type = 0xdeadbeef;
762
763         /*
764          * We are sending our message to the current owner of a well-known
765          * name. This makes an item of type KDBUS_ITEM_DST_NAME mandatory.
766          */
767         msg->dst_id = KDBUS_DST_ID_NAME;
768
769         /*
770          * Set the reply timeout to 5 seconds. Timeouts are always set in
771          * absolute timestamps, based con CLOCK_MONOTONIC. See kdbus.message(7).
772          */
773         clock_gettime(CLOCK_MONOTONIC_COARSE, &spec);
774         msg->timeout_ns += (5 + spec.tv_sec) * 1000ULL * 1000ULL * 1000ULL;
775         msg->timeout_ns += spec.tv_nsec;
776
777         /*
778          * Fill the appended items. First, set the well-known name of the
779          * destination we want to talk to.
780          */
781         item = msg->items;
782         item->type = KDBUS_ITEM_DST_NAME;
783         item->size = KDBUS_ITEM_HEADER_SIZE + strlen(arg_master) + 1;
784         strcpy(item->str, arg_master);
785
786         /*
787          * The 2nd item contains a vector to memory we want to send. It
788          * can be content of any type. In our case, we're sending a one-byte
789          * string only. The memory referenced by this item will be copied into
790          * the pool of the receiver connection, and does not need to be valid
791          * after the command is employed.
792          */
793         item = KDBUS_ITEM_NEXT(item);
794         item->type = KDBUS_ITEM_PAYLOAD_VEC;
795         item->size = KDBUS_ITEM_HEADER_SIZE + sizeof(struct kdbus_vec);
796         item->vec.address = (uintptr_t)"r";
797         item->vec.size = 1;
798
799         /* Set up the command struct and reference the message we prepared */
800         memset(&cmd, 0, sizeof(cmd));
801         cmd.size = sizeof(cmd);
802         cmd.msg_address = (uintptr_t)msg;
803
804         /*
805          * The send commands knows a mode in which it will block until a
806          * reply to a message is received. This example uses that mode.
807          * The pool offset to the received reply will be stored in the command
808          * struct after the send command returned. See below.
809          */
810         cmd.flags = KDBUS_SEND_SYNC_REPLY;
811
812         /*
813          * Finally, employ the command on the connection owner
814          * file descriptor.
815          */
816         r = kdbus_cmd_send(c->bus->fd, &cmd);
817         if (r == -ESRCH || r == -EPIPE || r == -ECONNRESET)
818                 return 0;
819         if (r < 0)
820                 return err_r(r, "cannot send request to master");
821
822         /*
823          * The command was sent with the KDBUS_SEND_SYNC_REPLY flag set,
824          * and returned successfully, which means that cmd.reply.offset now
825          * points to a message inside our connection's pool where the reply
826          * is found. This is equivalent to receiving the reply with
827          * KDBUS_CMD_RECV, but it doesn't require waiting for the reply with
828          * poll() and also saves the ioctl to receive the message.
829          */
830         msg = (void *)(c->bus->pool + cmd.reply.offset);
831
832         /*
833          * A messages describes its actual payload in an array of items.
834          * KDBUS_FOREACH() is a simple iterator that walks such an array.
835          * struct kdbus_msg has a field to denote its total size, which is
836          * needed to determine the number of items in the array.
837          */
838         KDBUS_FOREACH(item, msg->items,
839                       msg->size - offsetof(struct kdbus_msg, items)) {
840                 /*
841                  * An item of type PAYLOAD_OFF describes in-line memory
842                  * stored in the pool at a described offset. That offset is
843                  * relative to the start address of the message header.
844                  * This example program only expects one single item of that
845                  * type, remembers the struct kdbus_vec member of the item
846                  * when it sees it, and bails out if there is more than one
847                  * of them.
848                  */
849                 if (item->type == KDBUS_ITEM_PAYLOAD_OFF) {
850                         if (vec) {
851                                 r = err_r(-EEXIST,
852                                           "message with multiple vecs");
853                                 break;
854                         }
855                         vec = &item->vec;
856                         if (vec->size != 2 * sizeof(size_t)) {
857                                 r = err_r(-EINVAL, "invalid message size");
858                                 break;
859                         }
860                 /*
861                  * MEMFDs are transported as items of type PAYLOAD_MEMFD.
862                  * If such an item is attached, a new file descriptor was
863                  * installed into the task when KDBUS_CMD_RECV was called, and
864                  * its number is stored in item->memfd.fd.
865                  * Implementers *must* handle this item type close the
866                  * file descriptor when no longer needed in order to prevent
867                  * file descriptor exhaustion. This example program just bails
868                  * out with an error in this case, as memfds are not expected
869                  * in this context.
870                  */
871                 } else if (item->type == KDBUS_ITEM_PAYLOAD_MEMFD) {
872                         r = err_r(-EINVAL, "message with memfd");
873                         break;
874                 }
875         }
876         if (r < 0)
877                 goto exit;
878         if (!vec) {
879                 r = err_r(-EINVAL, "empty message");
880                 goto exit;
881         }
882
883         n = ((size_t *)((const uint8_t *)msg + vec->offset))[0];
884         steps = ((size_t *)((const uint8_t *)msg + vec->offset))[1];
885
886         while (steps-- > 0) {
887                 ++n;
888                 r = prime_run(c->prime, c->bus, n);
889                 if (r < 0)
890                         break;
891                 r = bus_poll(c->bus);
892                 if (r != 0) {
893                         r = r < 0 ? r : -EINTR;
894                         break;
895                 }
896         }
897
898 exit:
899         /*
900          * We are done with the memory slice that was given to us through
901          * cmd.reply.offset. Tell the kernel it can use it for other content
902          * in the future. See kdbus.pool(7).
903          */
904         bus_poool_free_slice(c->bus, cmd.reply.offset);
905         return r;
906 }
907
908 /*
909  * Prime Computation
910  *
911  */
912
913 static int prime_new(struct prime **out)
914 {
915         struct prime *p;
916         int r;
917
918         p = calloc(1, sizeof(*p));
919         if (!p)
920                 return err("cannot allocate prime memory");
921
922         p->fd = -1;
923         p->area = MAP_FAILED;
924         p->max = MAX_PRIMES;
925
926         /*
927          * Prepare and map a memfd to store the bit-fields for the number
928          * ranges we want to perform the prime detection on.
929          */
930         p->fd = syscall(__NR_memfd_create, "prime-area", MFD_CLOEXEC);
931         if (p->fd < 0) {
932                 r = err("cannot create memfd");
933                 goto error;
934         }
935
936         r = ftruncate(p->fd, p->max / 8 + 1);
937         if (r < 0) {
938                 r = err("cannot ftruncate area");
939                 goto error;
940         }
941
942         p->area = mmap(NULL, p->max / 8 + 1, PROT_READ | PROT_WRITE,
943                        MAP_SHARED, p->fd, 0);
944         if (p->area == MAP_FAILED) {
945                 r = err("cannot mmap memfd");
946                 goto error;
947         }
948
949         *out = p;
950         return 0;
951
952 error:
953         prime_free(p);
954         return r;
955 }
956
957 static void prime_free(struct prime *p)
958 {
959         if (!p)
960                 return;
961
962         if (p->area != MAP_FAILED)
963                 munmap(p->area, p->max / 8 + 1);
964         if (p->fd >= 0)
965                 close(p->fd);
966         free(p);
967 }
968
969 static bool prime_done(struct prime *p)
970 {
971         return p->done >= p->max;
972 }
973
974 static void prime_consume(struct prime *p, size_t amount)
975 {
976         p->done += amount;
977 }
978
979 static int prime_run(struct prime *p, struct bus *cancel, size_t number)
980 {
981         size_t i, n = 0;
982         int r;
983
984         if (number < 2 || number > 65535)
985                 return 0;
986
987         for (i = number * number;
988              i < p->max && i > number;
989              i += number) {
990                 p->area[i / 8] |= 1 << (i % 8);
991
992                 if (!(++n % (1 << 20))) {
993                         r = bus_poll(cancel);
994                         if (r != 0)
995                                 return r < 0 ? r : -EINTR;
996                 }
997         }
998
999         return 0;
1000 }
1001
1002 static void prime_print(struct prime *p)
1003 {
1004         size_t i, l = 0;
1005
1006         fprintf(stderr, "PRIMES:");
1007         for (i = 0; i < p->max; ++i) {
1008                 if (!(p->area[i / 8] & (1 << (i % 8))))
1009                         fprintf(stderr, "%c%7zu", !(l++ % 16) ? '\n' : ' ', i);
1010         }
1011         fprintf(stderr, "\nEND\n");
1012 }
1013
1014 static int bus_open_connection(struct bus **out, uid_t uid, const char *name,
1015                                uint64_t recv_flags)
1016 {
1017         struct kdbus_cmd_hello hello;
1018         char path[128];
1019         struct bus *b;
1020         int r;
1021
1022         /*
1023          * The 'bus' object is our representation of a kdbus connection which
1024          * stores two details: the connection owner file descriptor, and the
1025          * mmap()ed memory of its associated pool. See kdbus.connection(7) and
1026          * kdbus.pool(7).
1027          */
1028         b = calloc(1, sizeof(*b));
1029         if (!b)
1030                 return err("cannot allocate bus memory");
1031
1032         b->fd = -1;
1033         b->pool = MAP_FAILED;
1034
1035         /* Compute the name of the bus node to connect to. */
1036         snprintf(path, sizeof(path), "/sys/fs/%s/%lu-%s/bus",
1037                  arg_modname, (unsigned long)uid, name);
1038         b->fd = open(path, O_RDWR | O_CLOEXEC);
1039         if (b->fd < 0) {
1040                 r = err("cannot open bus");
1041                 goto error;
1042         }
1043
1044         /*
1045          * To make a connection to the bus, the KDBUS_CMD_HELLO ioctl is used.
1046          * It takes an argument of type 'struct kdbus_cmd_hello'.
1047          */
1048         memset(&hello, 0, sizeof(hello));
1049         hello.size = sizeof(hello);
1050
1051         /*
1052          * Specify a mask of metadata attach flags, describing metadata items
1053          * that this new connection allows to be sent.
1054          */
1055         hello.attach_flags_send = _KDBUS_ATTACH_ALL;
1056
1057         /*
1058          * Specify a mask of metadata attach flags, describing metadata items
1059          * that this new connection wants to be receive along with each message.
1060          */
1061         hello.attach_flags_recv = recv_flags;
1062
1063         /*
1064          * A connection may choose the size of its pool, but the number has to
1065          * comply with two rules: a) it must be greater than 0, and b) it must
1066          * be a mulitple of PAGE_SIZE. See kdbus.pool(7).
1067          */
1068         hello.pool_size = POOL_SIZE;
1069
1070         /*
1071          * Now employ the command on the file descriptor opened above.
1072          * This command will turn the file descriptor into a connection-owner
1073          * file descriptor that controls the life-time of the connection; once
1074          * it's closed, the connection is shut down.
1075          */
1076         r = kdbus_cmd_hello(b->fd, &hello);
1077         if (r < 0) {
1078                 err_r(r, "HELLO failed");
1079                 goto error;
1080         }
1081
1082         bus_poool_free_slice(b, hello.offset);
1083
1084         /*
1085          * Map the pool of the connection. Its size has been set in the
1086          * command struct above. See kdbus.pool(7).
1087          */
1088         b->pool = mmap(NULL, POOL_SIZE, PROT_READ, MAP_SHARED, b->fd, 0);
1089         if (b->pool == MAP_FAILED) {
1090                 r = err("cannot mmap pool");
1091                 goto error;
1092         }
1093
1094         *out = b;
1095         return 0;
1096
1097 error:
1098         bus_close_connection(b);
1099         return r;
1100 }
1101
1102 static void bus_close_connection(struct bus *b)
1103 {
1104         if (!b)
1105                 return;
1106
1107         /*
1108          * A bus connection is closed by simply calling close() on the
1109          * connection owner file descriptor. The unique name and all owned
1110          * well-known names of the conneciton will disappear.
1111          * See kdbus.connection(7).
1112          */
1113         if (b->pool != MAP_FAILED)
1114                 munmap(b->pool, POOL_SIZE);
1115         if (b->fd >= 0)
1116                 close(b->fd);
1117         free(b);
1118 }
1119
1120 static void bus_poool_free_slice(struct bus *b, uint64_t offset)
1121 {
1122         struct kdbus_cmd_free cmd = {
1123                 .size = sizeof(cmd),
1124                 .offset = offset,
1125         };
1126         int r;
1127
1128         /*
1129          * Once we're done with a piece of pool memory that was returned
1130          * by a command, we have to call the KDBUS_CMD_FREE ioctl on it so it
1131          * can be reused. The command takes an argument of type
1132          * 'struct kdbus_cmd_free', in which the pool offset of the slice to
1133          * free is stored. The ioctl is employed on the connection owner
1134          * file descriptor. See kdbus.pool(7),
1135          */
1136         r = kdbus_cmd_free(b->fd, &cmd);
1137         if (r < 0)
1138                 err_r(r, "cannot free pool slice");
1139 }
1140
1141 static int bus_acquire_name(struct bus *b, const char *name)
1142 {
1143         struct kdbus_item *item;
1144         struct kdbus_cmd *cmd;
1145         size_t size;
1146         int r;
1147
1148         /*
1149          * This function acquires a well-known name on the bus through the
1150          * KDBUS_CMD_NAME_ACQUIRE ioctl. This ioctl takes an argument of type
1151          * 'struct kdbus_cmd', which is assembled below. See kdbus.name(7).
1152          */
1153         size = sizeof(*cmd);
1154         size += KDBUS_ITEM_SIZE(strlen(name) + 1);
1155
1156         cmd = alloca(size);
1157         memset(cmd, 0, size);
1158         cmd->size = size;
1159
1160         /*
1161          * The command requires an item of type KDBUS_ITEM_NAME, and its
1162          * content must be a valid bus name.
1163          */
1164         item = cmd->items;
1165         item->type = KDBUS_ITEM_NAME;
1166         item->size = KDBUS_ITEM_HEADER_SIZE + strlen(name) + 1;
1167         strcpy(item->str, name);
1168
1169         /*
1170          * Employ the command on the connection owner file descriptor.
1171          */
1172         r = kdbus_cmd_name_acquire(b->fd, cmd);
1173         if (r < 0)
1174                 return err_r(r, "cannot acquire name");
1175
1176         return 0;
1177 }
1178
1179 static int bus_install_name_loss_match(struct bus *b, const char *name)
1180 {
1181         struct kdbus_cmd_match *match;
1182         struct kdbus_item *item;
1183         size_t size;
1184         int r;
1185
1186         /*
1187          * In order to install a match for signal messages, we have to
1188          * assemble a 'struct kdbus_cmd_match' and use it along with the
1189          * KDBUS_CMD_MATCH_ADD ioctl. See kdbus.match(7).
1190          */
1191         size = sizeof(*match);
1192         size += KDBUS_ITEM_SIZE(sizeof(item->name_change) + strlen(name) + 1);
1193
1194         match = alloca(size);
1195         memset(match, 0, size);
1196         match->size = size;
1197
1198         /*
1199          * A match is comprised of many 'rules', each of which describes a
1200          * mandatory detail of the message. All rules of a match must be
1201          * satified in order to make a message pass.
1202          */
1203         item = match->items;
1204
1205         /*
1206          * In this case, we're interested in notifications that inform us
1207          * about a well-known name being removed from the bus.
1208          */
1209         item->type = KDBUS_ITEM_NAME_REMOVE;
1210         item->size = KDBUS_ITEM_HEADER_SIZE +
1211                         sizeof(item->name_change) + strlen(name) + 1;
1212
1213         /*
1214          * We could limit the match further and require a specific unique-ID
1215          * to be the new or the old owner of the name. In this case, however,
1216          * we don't, and allow 'any' id.
1217          */
1218         item->name_change.old_id.id = KDBUS_MATCH_ID_ANY;
1219         item->name_change.new_id.id = KDBUS_MATCH_ID_ANY;
1220
1221         /* Copy in the well-known name we're interested in */
1222         strcpy(item->name_change.name, name);
1223
1224         /*
1225          * Add the match through the KDBUS_CMD_MATCH_ADD ioctl, employed on
1226          * the connection owner fd.
1227          */
1228         r = kdbus_cmd_match_add(b->fd, match);
1229         if (r < 0)
1230                 return err_r(r, "cannot add match");
1231
1232         return 0;
1233 }
1234
1235 static int bus_poll(struct bus *b)
1236 {
1237         struct pollfd fds[1] = {};
1238         int r;
1239
1240         /*
1241          * A connection endpoint supports poll() and will wake-up the
1242          * task with POLLIN set once a message has arrived.
1243          */
1244         fds[0].fd = b->fd;
1245         fds[0].events = POLLIN;
1246         r = poll(fds, sizeof(fds) / sizeof(*fds), 0);
1247         if (r < 0)
1248                 return err("cannot poll bus");
1249         return !!(fds[0].revents & POLLIN);
1250 }
1251
1252 static int bus_make(uid_t uid, const char *name)
1253 {
1254         struct kdbus_item *item;
1255         struct kdbus_cmd *make;
1256         char path[128], busname[128];
1257         size_t size;
1258         int r, fd;
1259
1260         /*
1261          * Compute the full path to the 'control' node. 'arg_modname' may be
1262          * set to a different value than 'kdbus' for development purposes.
1263          * The 'control' node is the primary entry point to kdbus that must be
1264          * used in order to create a bus. See kdbus(7) and kdbus.bus(7).
1265          */
1266         snprintf(path, sizeof(path), "/sys/fs/%s/control", arg_modname);
1267
1268         /*
1269          * Compute the bus name. A valid bus name must always be prefixed with
1270          * the EUID of the currently running process in order to avoid name
1271          * conflicts. See kdbus.bus(7).
1272          */
1273         snprintf(busname, sizeof(busname), "%lu-%s", (unsigned long)uid, name);
1274
1275         fd = open(path, O_RDWR | O_CLOEXEC);
1276         if (fd < 0)
1277                 return err("cannot open control file");
1278
1279         /*
1280          * The KDBUS_CMD_BUS_MAKE ioctl takes an argument of type
1281          * 'struct kdbus_cmd', and expects at least two items attached to
1282          * it: one to decribe the bloom parameters to be propagated to
1283          * connections of the bus, and the name of the bus that was computed
1284          * above. Assemble this struct now, and fill it with values.
1285          */
1286         size = sizeof(*make);
1287         size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_bloom_parameter));
1288         size += KDBUS_ITEM_SIZE(strlen(busname) + 1);
1289
1290         make = alloca(size);
1291         memset(make, 0, size);
1292         make->size = size;
1293
1294         /*
1295          * Each item has a 'type' and 'size' field, and must be stored at an
1296          * 8-byte aligned address. The KDBUS_ITEM_NEXT macro is used to advance
1297          * the pointer. See kdbus.item(7) for more details.
1298          */
1299         item = make->items;
1300         item->type = KDBUS_ITEM_BLOOM_PARAMETER;
1301         item->size = KDBUS_ITEM_HEADER_SIZE + sizeof(item->bloom_parameter);
1302         item->bloom_parameter.size = 8;
1303         item->bloom_parameter.n_hash = 1;
1304
1305         /* The name of the new bus is stored in the next item. */
1306         item = KDBUS_ITEM_NEXT(item);
1307         item->type = KDBUS_ITEM_MAKE_NAME;
1308         item->size = KDBUS_ITEM_HEADER_SIZE + strlen(busname) + 1;
1309         strcpy(item->str, busname);
1310
1311         /*
1312          * Now create the bus via the KDBUS_CMD_BUS_MAKE ioctl and return the
1313          * fd that was used back to the caller of this function. This fd is now
1314          * called a 'bus owner file descriptor', and it controls the life-time
1315          * of the newly created bus; once the file descriptor is closed, the
1316          * bus goes away, and all connections are shut down. See kdbus.bus(7).
1317          */
1318         r = kdbus_cmd_bus_make(fd, make);
1319         if (r < 0) {
1320                 err_r(r, "cannot make bus");
1321                 close(fd);
1322                 return r;
1323         }
1324
1325         return fd;
1326 }