2 * Copyright (C) 2013-2015 David Herrmann <dh.herrmann@gmail.com>
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.
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.
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.
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.
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.
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.
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.
63 #include <linux/memfd.h>
73 #include <sys/signalfd.h>
74 #include <sys/syscall.h>
79 #include "kdbus-api.h"
81 /* FORWARD DECLARATIONS */
83 #define POOL_SIZE (16 * 1024 * 1024)
84 #define MAX_PRIMES (2UL << 24)
85 #define WORKER_COUNT (16)
86 #define PRIME_STEPS (65536 * 4)
88 static const char *arg_busname = "example-workers";
89 static const char *arg_modname = "kdbus";
90 static const char *arg_master = "org.freedesktop.master";
92 static int err_assert(int r_errno, const char *msg, const char *func, int line,
95 r_errno = (r_errno != 0) ? -abs(r_errno) : -EFAULT;
98 fprintf(stderr, "ERR: %s: %m (%s:%d in %s)\n",
99 msg, func, line, file);
104 #define err_r(_r, _msg) err_assert((_r), (_msg), __func__, __LINE__, __FILE__)
105 #define err(_msg) err_r(errno, (_msg))
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);
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);
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);
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);
172 /* END OF FORWARD DECLARATIONS */
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
180 int main(int argc, char **argv)
182 struct master *m = NULL;
194 prime_print(m->prime);
198 if (r < 0 && r != -EINTR)
199 fprintf(stderr, "failed\n");
201 fprintf(stderr, "done\n");
202 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
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).
211 static int master_new(struct master **out)
217 m = calloc(1, sizeof(*m));
219 return err("cannot allocate master");
221 m->max_workers = WORKER_COUNT;
225 /* Block SIGINT and SIGCHLD signals */
227 sigaddset(&smask, SIGINT);
228 sigaddset(&smask, SIGCHLD);
229 sigprocmask(SIG_BLOCK, &smask, NULL);
231 m->signal_fd = signalfd(-1, &smask, SFD_CLOEXEC);
232 if (m->signal_fd < 0) {
233 r = err("cannot create signalfd");
237 r = prime_new(&m->prime);
241 m->control_fd = bus_make(getuid(), arg_busname);
242 if (m->control_fd < 0) {
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
253 r = bus_open_connection(&m->bus, getuid(),
254 arg_busname, KDBUS_ATTACH_PIDS);
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
263 r = bus_acquire_name(m->bus, arg_master);
275 /* pretty straightforward destructor of a master object */
276 static void master_free(struct master *m)
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)
290 static int master_run(struct master *m)
294 while (!prime_done(m->prime)) {
295 while (m->n_workers < m->max_workers) {
307 bus_close_connection(m->bus);
311 while (m->n_workers > 0) {
312 res = master_poll(m);
315 bus_close_connection(m->bus);
322 return r == -EINTR ? 0 : r;
325 static int master_poll(struct master *m)
327 struct pollfd fds[3] = {};
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().
335 fds[n].fd = STDIN_FILENO;
336 fds[n++].events = POLLIN;
337 fds[n].fd = m->signal_fd;
338 fds[n++].events = POLLIN;
340 fds[n].fd = m->bus->fd;
341 fds[n++].events = POLLIN;
344 r = poll(fds, n, -1);
346 return err("poll() failed");
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");
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");
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");
370 static int master_handle_stdin(struct master *m)
376 l = read(STDIN_FILENO, buf, sizeof(buf));
378 return err("cannot read stdin");
380 return err_r(-EINVAL, "EOF on stdin");
394 fprintf(stderr, "invalid input '%c'\n", buf[l]);
396 fprintf(stderr, "invalid input 0x%x\n", buf[l]);
404 static int master_handle_signal(struct master *m)
406 struct signalfd_siginfo val;
409 l = read(m->signal_fd, &val, sizeof(val));
411 return err("cannot read signalfd");
412 if (l != sizeof(val))
413 return err_r(-EINVAL, "invalid data from signalfd");
415 switch (val.ssi_signo) {
417 return master_waitpid(m);
419 return err_r(-EINTR, "interrupted");
421 return err_r(-EINVAL, "caught invalid signal");
425 static int master_handle_bus(struct master *m)
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;
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).
439 r = kdbus_cmd_recv(m->bus->fd, &recv);
441 * EAGAIN is returned when there is no message waiting on this
442 * connection. This is not an error - simply bail out.
447 return err_r(r, "cannot receive message");
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).
456 msg = (void *)(m->bus->pool + recv.msg.offset);
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.
464 KDBUS_FOREACH(item, msg->items,
465 msg->size - offsetof(struct kdbus_msg, items)) {
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
475 if (item->type == KDBUS_ITEM_PAYLOAD_OFF) {
478 "message with multiple vecs");
482 if (vec->size != 1) {
483 r = err_r(-EINVAL, "invalid message size");
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
498 } else if (item->type == KDBUS_ITEM_PAYLOAD_MEMFD) {
499 r = err_r(-EINVAL, "message with memfd");
506 r = err_r(-EINVAL, "empty message");
510 switch (*((const uint8_t *)msg + vec->offset)) {
512 r = master_reply(m, msg);
516 r = err_r(-EINVAL, "invalid message type");
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).
526 bus_poool_free_slice(m->bus, recv.msg.offset);
530 static int master_reply(struct master *m, const struct kdbus_msg *msg)
532 struct kdbus_cmd_send cmd;
533 struct kdbus_item *item;
534 struct kdbus_msg *reply;
535 size_t size, status, p[2];
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).
544 p[0] = m->prime->done;
545 p[1] = prime_done(m->prime) ? 0 : PRIME_STEPS;
547 size = sizeof(*reply);
548 size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
550 /* Prepare the message to send */
551 reply = alloca(size);
552 memset(reply, 0, size);
555 /* Each message has a cookie that can be used to send replies */
558 /* The payload_type is arbitrary, but it must be non-zero */
559 reply->payload_type = 0xdeadbeef;
562 * We are sending a reply. Let the kernel know the cookie of the
563 * message we are replying to.
565 reply->cookie_reply = msg->cookie;
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
576 reply->dst_id = msg->src_id;
578 /* Our message has exactly one item to store its payload */
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);
586 * Now prepare the command struct, and reference the message we want
589 memset(&cmd, 0, sizeof(cmd));
590 cmd.size = sizeof(cmd);
591 cmd.msg_address = (uintptr_t)reply;
594 * Finally, employ the command on the connection owner
597 r = kdbus_cmd_send(m->bus->fd, &cmd);
599 return err_r(r, "cannot send reply");
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);
614 static int master_waitpid(struct master *m)
619 while ((pid = waitpid(-1, &r, WNOHANG)) > 0) {
620 if (m->n_workers > 0)
623 r = err_r(-EINVAL, "child died unexpectedly");
624 else if (WEXITSTATUS(r) != 0)
625 r = err_r(-WEXITSTATUS(r), "child failed");
631 static int master_spawn(struct master *m)
633 struct child *c = NULL;
634 struct prime *p = NULL;
638 /* Spawn off one child and call child_run() inside it */
642 return err("cannot fork");
655 r = child_new(&c, p);
666 static int child_new(struct child **out, struct prime *p)
671 c = calloc(1, sizeof(*c));
673 return err("cannot allocate child");
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.
683 r = bus_open_connection(&c->bus, getuid(),
684 arg_busname, KDBUS_ATTACH_NAMES);
689 * Install a kdbus match so the child's connection gets notified when
690 * the master loses its well-known name.
692 r = bus_install_name_loss_match(c->bus, arg_master);
704 static void child_free(struct child *c)
709 bus_close_connection(c->bus);
710 prime_free(c->prime);
714 static int child_run(struct child *c)
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;
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).
731 size += KDBUS_ITEM_SIZE(strlen(arg_master) + 1);
732 size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
735 memset(msg, 0, size);
739 * Tell the kernel that we expect a reply to this message. This means
742 * a) The remote peer will gain temporary permission to talk to us
743 * even if it would not be allowed to normally.
745 * b) A timeout value is required.
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.
751 * For synchronous send commands (which this example does), the
752 * ioctl will block until a reply is received or the timeout is
755 msg->flags = KDBUS_MSG_EXPECT_REPLY;
757 /* Set our cookie. Replies must use this cookie to send their reply. */
760 /* The payload_type is arbitrary, but it must be non-zero */
761 msg->payload_type = 0xdeadbeef;
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.
767 msg->dst_id = KDBUS_DST_ID_NAME;
770 * Set the reply timeout to 5 seconds. Timeouts are always set in
771 * absolute timestamps, based con CLOCK_MONOTONIC. See kdbus.message(7).
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;
778 * Fill the appended items. First, set the well-known name of the
779 * destination we want to talk to.
782 item->type = KDBUS_ITEM_DST_NAME;
783 item->size = KDBUS_ITEM_HEADER_SIZE + strlen(arg_master) + 1;
784 strcpy(item->str, arg_master);
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.
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";
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;
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.
810 cmd.flags = KDBUS_SEND_SYNC_REPLY;
813 * Finally, employ the command on the connection owner
816 r = kdbus_cmd_send(c->bus->fd, &cmd);
817 if (r == -ESRCH || r == -EPIPE || r == -ECONNRESET)
820 return err_r(r, "cannot send request to master");
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.
830 msg = (void *)(c->bus->pool + cmd.reply.offset);
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.
838 KDBUS_FOREACH(item, msg->items,
839 msg->size - offsetof(struct kdbus_msg, items)) {
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
849 if (item->type == KDBUS_ITEM_PAYLOAD_OFF) {
852 "message with multiple vecs");
856 if (vec->size != 2 * sizeof(size_t)) {
857 r = err_r(-EINVAL, "invalid message size");
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
871 } else if (item->type == KDBUS_ITEM_PAYLOAD_MEMFD) {
872 r = err_r(-EINVAL, "message with memfd");
879 r = err_r(-EINVAL, "empty message");
883 n = ((size_t *)((const uint8_t *)msg + vec->offset))[0];
884 steps = ((size_t *)((const uint8_t *)msg + vec->offset))[1];
886 while (steps-- > 0) {
888 r = prime_run(c->prime, c->bus, n);
891 r = bus_poll(c->bus);
893 r = r < 0 ? r : -EINTR;
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).
904 bus_poool_free_slice(c->bus, cmd.reply.offset);
913 static int prime_new(struct prime **out)
918 p = calloc(1, sizeof(*p));
920 return err("cannot allocate prime memory");
923 p->area = MAP_FAILED;
927 * Prepare and map a memfd to store the bit-fields for the number
928 * ranges we want to perform the prime detection on.
930 p->fd = syscall(__NR_memfd_create, "prime-area", MFD_CLOEXEC);
932 r = err("cannot create memfd");
936 r = ftruncate(p->fd, p->max / 8 + 1);
938 r = err("cannot ftruncate area");
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");
957 static void prime_free(struct prime *p)
962 if (p->area != MAP_FAILED)
963 munmap(p->area, p->max / 8 + 1);
969 static bool prime_done(struct prime *p)
971 return p->done >= p->max;
974 static void prime_consume(struct prime *p, size_t amount)
979 static int prime_run(struct prime *p, struct bus *cancel, size_t number)
984 if (number < 2 || number > 65535)
987 for (i = number * number;
988 i < p->max && i > number;
990 p->area[i / 8] |= 1 << (i % 8);
992 if (!(++n % (1 << 20))) {
993 r = bus_poll(cancel);
995 return r < 0 ? r : -EINTR;
1002 static void prime_print(struct prime *p)
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);
1011 fprintf(stderr, "\nEND\n");
1014 static int bus_open_connection(struct bus **out, uid_t uid, const char *name,
1015 uint64_t recv_flags)
1017 struct kdbus_cmd_hello hello;
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
1028 b = calloc(1, sizeof(*b));
1030 return err("cannot allocate bus memory");
1033 b->pool = MAP_FAILED;
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);
1040 r = err("cannot open bus");
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'.
1048 memset(&hello, 0, sizeof(hello));
1049 hello.size = sizeof(hello);
1052 * Specify a mask of metadata attach flags, describing metadata items
1053 * that this new connection allows to be sent.
1055 hello.attach_flags_send = _KDBUS_ATTACH_ALL;
1058 * Specify a mask of metadata attach flags, describing metadata items
1059 * that this new connection wants to be receive along with each message.
1061 hello.attach_flags_recv = recv_flags;
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).
1068 hello.pool_size = POOL_SIZE;
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.
1076 r = kdbus_cmd_hello(b->fd, &hello);
1078 err_r(r, "HELLO failed");
1082 bus_poool_free_slice(b, hello.offset);
1085 * Map the pool of the connection. Its size has been set in the
1086 * command struct above. See kdbus.pool(7).
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");
1098 bus_close_connection(b);
1102 static void bus_close_connection(struct bus *b)
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).
1113 if (b->pool != MAP_FAILED)
1114 munmap(b->pool, POOL_SIZE);
1120 static void bus_poool_free_slice(struct bus *b, uint64_t offset)
1122 struct kdbus_cmd_free cmd = {
1123 .size = sizeof(cmd),
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),
1136 r = kdbus_cmd_free(b->fd, &cmd);
1138 err_r(r, "cannot free pool slice");
1141 static int bus_acquire_name(struct bus *b, const char *name)
1143 struct kdbus_item *item;
1144 struct kdbus_cmd *cmd;
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).
1153 size = sizeof(*cmd);
1154 size += KDBUS_ITEM_SIZE(strlen(name) + 1);
1157 memset(cmd, 0, size);
1161 * The command requires an item of type KDBUS_ITEM_NAME, and its
1162 * content must be a valid bus name.
1165 item->type = KDBUS_ITEM_NAME;
1166 item->size = KDBUS_ITEM_HEADER_SIZE + strlen(name) + 1;
1167 strcpy(item->str, name);
1170 * Employ the command on the connection owner file descriptor.
1172 r = kdbus_cmd_name_acquire(b->fd, cmd);
1174 return err_r(r, "cannot acquire name");
1179 static int bus_install_name_loss_match(struct bus *b, const char *name)
1181 struct kdbus_cmd_match *match;
1182 struct kdbus_item *item;
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).
1191 size = sizeof(*match);
1192 size += KDBUS_ITEM_SIZE(sizeof(item->name_change) + strlen(name) + 1);
1194 match = alloca(size);
1195 memset(match, 0, size);
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.
1203 item = match->items;
1206 * In this case, we're interested in notifications that inform us
1207 * about a well-known name being removed from the bus.
1209 item->type = KDBUS_ITEM_NAME_REMOVE;
1210 item->size = KDBUS_ITEM_HEADER_SIZE +
1211 sizeof(item->name_change) + strlen(name) + 1;
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.
1218 item->name_change.old_id.id = KDBUS_MATCH_ID_ANY;
1219 item->name_change.new_id.id = KDBUS_MATCH_ID_ANY;
1221 /* Copy in the well-known name we're interested in */
1222 strcpy(item->name_change.name, name);
1225 * Add the match through the KDBUS_CMD_MATCH_ADD ioctl, employed on
1226 * the connection owner fd.
1228 r = kdbus_cmd_match_add(b->fd, match);
1230 return err_r(r, "cannot add match");
1235 static int bus_poll(struct bus *b)
1237 struct pollfd fds[1] = {};
1241 * A connection endpoint supports poll() and will wake-up the
1242 * task with POLLIN set once a message has arrived.
1245 fds[0].events = POLLIN;
1246 r = poll(fds, sizeof(fds) / sizeof(*fds), 0);
1248 return err("cannot poll bus");
1249 return !!(fds[0].revents & POLLIN);
1252 static int bus_make(uid_t uid, const char *name)
1254 struct kdbus_item *item;
1255 struct kdbus_cmd *make;
1256 char path[128], busname[128];
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).
1266 snprintf(path, sizeof(path), "/sys/fs/%s/control", arg_modname);
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).
1273 snprintf(busname, sizeof(busname), "%lu-%s", (unsigned long)uid, name);
1275 fd = open(path, O_RDWR | O_CLOEXEC);
1277 return err("cannot open control file");
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.
1286 size = sizeof(*make);
1287 size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_bloom_parameter));
1288 size += KDBUS_ITEM_SIZE(strlen(busname) + 1);
1290 make = alloca(size);
1291 memset(make, 0, size);
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.
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;
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);
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).
1318 r = kdbus_cmd_bus_make(fd, make);
1320 err_r(r, "cannot make bus");