1 /******************************************************************************
4 * This is the kernel equivalent of the "xs" library. We don't need everything
5 * and we use xenbus_comms for communication.
7 * Copyright (C) 2005 Rusty Russell, IBM Corporation
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License version 2
11 * as published by the Free Software Foundation; or, when distributed
12 * separately from the Linux kernel or incorporated into other
13 * software packages, subject to the following license:
15 * Permission is hereby granted, free of charge, to any person obtaining a copy
16 * of this source file (the "Software"), to deal in the Software without
17 * restriction, including without limitation the rights to use, copy, modify,
18 * merge, publish, distribute, sublicense, and/or sell copies of the Software,
19 * and to permit persons to whom the Software is furnished to do so, subject to
20 * the following conditions:
22 * The above copyright notice and this permission notice shall be included in
23 * all copies or substantial portions of the Software.
25 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
30 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
34 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
36 #include <linux/unistd.h>
37 #include <linux/errno.h>
38 #include <linux/types.h>
39 #include <linux/uio.h>
40 #include <linux/kernel.h>
41 #include <linux/string.h>
42 #include <linux/err.h>
43 #include <linux/slab.h>
44 #include <linux/fcntl.h>
45 #include <linux/kthread.h>
46 #include <linux/rwsem.h>
47 #include <linux/mutex.h>
48 #include <asm/xen/hypervisor.h>
49 #include <xen/xenbus.h>
53 struct xs_stored_msg {
54 struct list_head list;
56 struct xsd_sockmsg hdr;
64 /* Queued watch events. */
66 struct xenbus_watch *handle;
74 /* A list of replies. Currently only one will ever be outstanding. */
75 struct list_head reply_list;
76 spinlock_t reply_lock;
77 wait_queue_head_t reply_waitq;
80 * Mutex ordering: transaction_mutex -> watch_mutex -> request_mutex.
81 * response_mutex is never taken simultaneously with the other three.
83 * transaction_mutex must be held before incrementing
84 * transaction_count. The mutex is held when a suspend is in
85 * progress to prevent new transactions starting.
87 * When decrementing transaction_count to zero the wait queue
88 * should be woken up, the suspend code waits for count to
92 /* One request at a time. */
93 struct mutex request_mutex;
95 /* Protect xenbus reader thread against save/restore. */
96 struct mutex response_mutex;
98 /* Protect transactions against save/restore. */
99 struct mutex transaction_mutex;
100 atomic_t transaction_count;
101 wait_queue_head_t transaction_wq;
103 /* Protect watch (de)register against save/restore. */
104 struct rw_semaphore watch_mutex;
107 static struct xs_handle xs_state;
109 /* List of registered watches, and a lock to protect it. */
110 static LIST_HEAD(watches);
111 static DEFINE_SPINLOCK(watches_lock);
113 /* List of pending watch callback events, and a lock to protect it. */
114 static LIST_HEAD(watch_events);
115 static DEFINE_SPINLOCK(watch_events_lock);
118 * Details of the xenwatch callback kernel thread. The thread waits on the
119 * watch_events_waitq for work to do (queued on watch_events list). When it
120 * wakes up it acquires the xenwatch_mutex before reading the list and
123 static pid_t xenwatch_pid;
124 static DEFINE_MUTEX(xenwatch_mutex);
125 static DECLARE_WAIT_QUEUE_HEAD(watch_events_waitq);
127 static int get_error(const char *errorstring)
131 for (i = 0; strcmp(errorstring, xsd_errors[i].errstring) != 0; i++) {
132 if (i == ARRAY_SIZE(xsd_errors) - 1) {
133 pr_warn("xen store gave: unknown error %s\n",
138 return xsd_errors[i].errnum;
141 static bool xenbus_ok(void)
143 switch (xen_store_domain_type) {
145 switch (system_state) {
146 case SYSTEM_POWER_OFF:
156 /* FIXME: Could check that the remote domain is alive,
157 * but it is normally initial domain. */
164 static void *read_reply(enum xsd_sockmsg_type *type, unsigned int *len)
166 struct xs_stored_msg *msg;
169 spin_lock(&xs_state.reply_lock);
171 while (list_empty(&xs_state.reply_list)) {
172 spin_unlock(&xs_state.reply_lock);
174 /* XXX FIXME: Avoid synchronous wait for response here. */
175 wait_event_timeout(xs_state.reply_waitq,
176 !list_empty(&xs_state.reply_list),
177 msecs_to_jiffies(500));
180 * If we are in the process of being shut-down there is
181 * no point of trying to contact XenBus - it is either
182 * killed (xenstored application) or the other domain
183 * has been killed or is unreachable.
185 return ERR_PTR(-EIO);
187 spin_lock(&xs_state.reply_lock);
190 msg = list_entry(xs_state.reply_list.next,
191 struct xs_stored_msg, list);
192 list_del(&msg->list);
194 spin_unlock(&xs_state.reply_lock);
196 *type = msg->hdr.type;
199 body = msg->u.reply.body;
206 static void transaction_start(void)
208 mutex_lock(&xs_state.transaction_mutex);
209 atomic_inc(&xs_state.transaction_count);
210 mutex_unlock(&xs_state.transaction_mutex);
213 static void transaction_end(void)
215 if (atomic_dec_and_test(&xs_state.transaction_count))
216 wake_up(&xs_state.transaction_wq);
219 static void transaction_suspend(void)
221 mutex_lock(&xs_state.transaction_mutex);
222 wait_event(xs_state.transaction_wq,
223 atomic_read(&xs_state.transaction_count) == 0);
226 static void transaction_resume(void)
228 mutex_unlock(&xs_state.transaction_mutex);
231 void *xenbus_dev_request_and_reply(struct xsd_sockmsg *msg)
234 enum xsd_sockmsg_type type = msg->type;
237 if (type == XS_TRANSACTION_START)
240 mutex_lock(&xs_state.request_mutex);
242 err = xb_write(msg, sizeof(*msg) + msg->len);
244 msg->type = XS_ERROR;
247 ret = read_reply(&msg->type, &msg->len);
249 mutex_unlock(&xs_state.request_mutex);
251 if ((msg->type == XS_TRANSACTION_END) ||
252 ((type == XS_TRANSACTION_START) && (msg->type == XS_ERROR)))
257 EXPORT_SYMBOL(xenbus_dev_request_and_reply);
259 /* Send message to xs, get kmalloc'ed reply. ERR_PTR() on error. */
260 static void *xs_talkv(struct xenbus_transaction t,
261 enum xsd_sockmsg_type type,
262 const struct kvec *iovec,
263 unsigned int num_vecs,
266 struct xsd_sockmsg msg;
275 for (i = 0; i < num_vecs; i++)
276 msg.len += iovec[i].iov_len;
278 mutex_lock(&xs_state.request_mutex);
280 err = xb_write(&msg, sizeof(msg));
282 mutex_unlock(&xs_state.request_mutex);
286 for (i = 0; i < num_vecs; i++) {
287 err = xb_write(iovec[i].iov_base, iovec[i].iov_len);
289 mutex_unlock(&xs_state.request_mutex);
294 ret = read_reply(&msg.type, len);
296 mutex_unlock(&xs_state.request_mutex);
301 if (msg.type == XS_ERROR) {
302 err = get_error(ret);
304 return ERR_PTR(-err);
307 if (msg.type != type) {
308 pr_warn_ratelimited("unexpected type [%d], expected [%d]\n",
311 return ERR_PTR(-EINVAL);
316 /* Simplified version of xs_talkv: single message. */
317 static void *xs_single(struct xenbus_transaction t,
318 enum xsd_sockmsg_type type,
324 iovec.iov_base = (void *)string;
325 iovec.iov_len = strlen(string) + 1;
326 return xs_talkv(t, type, &iovec, 1, len);
329 /* Many commands only need an ack, don't care what it says. */
330 static int xs_error(char *reply)
333 return PTR_ERR(reply);
338 static unsigned int count_strings(const char *strings, unsigned int len)
343 for (p = strings, num = 0; p < strings + len; p += strlen(p) + 1)
349 /* Return the path to dir with /name appended. Buffer must be kfree()'ed. */
350 static char *join(const char *dir, const char *name)
354 if (strlen(name) == 0)
355 buffer = kasprintf(GFP_NOIO | __GFP_HIGH, "%s", dir);
357 buffer = kasprintf(GFP_NOIO | __GFP_HIGH, "%s/%s", dir, name);
358 return (!buffer) ? ERR_PTR(-ENOMEM) : buffer;
361 static char **split(char *strings, unsigned int len, unsigned int *num)
365 /* Count the strings. */
366 *num = count_strings(strings, len);
368 /* Transfer to one big alloc for easy freeing. */
369 ret = kmalloc(*num * sizeof(char *) + len, GFP_NOIO | __GFP_HIGH);
372 return ERR_PTR(-ENOMEM);
374 memcpy(&ret[*num], strings, len);
377 strings = (char *)&ret[*num];
378 for (p = strings, *num = 0; p < strings + len; p += strlen(p) + 1)
384 char **xenbus_directory(struct xenbus_transaction t,
385 const char *dir, const char *node, unsigned int *num)
387 char *strings, *path;
390 path = join(dir, node);
392 return (char **)path;
394 strings = xs_single(t, XS_DIRECTORY, path, &len);
397 return (char **)strings;
399 return split(strings, len, num);
401 EXPORT_SYMBOL_GPL(xenbus_directory);
403 /* Check if a path exists. Return 1 if it does. */
404 int xenbus_exists(struct xenbus_transaction t,
405 const char *dir, const char *node)
410 d = xenbus_directory(t, dir, node, &dir_n);
416 EXPORT_SYMBOL_GPL(xenbus_exists);
418 /* Get the value of a single file.
419 * Returns a kmalloced value: call free() on it after use.
420 * len indicates length in bytes.
422 void *xenbus_read(struct xenbus_transaction t,
423 const char *dir, const char *node, unsigned int *len)
428 path = join(dir, node);
432 ret = xs_single(t, XS_READ, path, len);
436 EXPORT_SYMBOL_GPL(xenbus_read);
438 /* Write the value of a single file.
439 * Returns -err on failure.
441 int xenbus_write(struct xenbus_transaction t,
442 const char *dir, const char *node, const char *string)
445 struct kvec iovec[2];
448 path = join(dir, node);
450 return PTR_ERR(path);
452 iovec[0].iov_base = (void *)path;
453 iovec[0].iov_len = strlen(path) + 1;
454 iovec[1].iov_base = (void *)string;
455 iovec[1].iov_len = strlen(string);
457 ret = xs_error(xs_talkv(t, XS_WRITE, iovec, ARRAY_SIZE(iovec), NULL));
461 EXPORT_SYMBOL_GPL(xenbus_write);
463 /* Create a new directory. */
464 int xenbus_mkdir(struct xenbus_transaction t,
465 const char *dir, const char *node)
470 path = join(dir, node);
472 return PTR_ERR(path);
474 ret = xs_error(xs_single(t, XS_MKDIR, path, NULL));
478 EXPORT_SYMBOL_GPL(xenbus_mkdir);
480 /* Destroy a file or directory (directories must be empty). */
481 int xenbus_rm(struct xenbus_transaction t, const char *dir, const char *node)
486 path = join(dir, node);
488 return PTR_ERR(path);
490 ret = xs_error(xs_single(t, XS_RM, path, NULL));
494 EXPORT_SYMBOL_GPL(xenbus_rm);
496 /* Start a transaction: changes by others will not be seen during this
497 * transaction, and changes will not be visible to others until end.
499 int xenbus_transaction_start(struct xenbus_transaction *t)
505 id_str = xs_single(XBT_NIL, XS_TRANSACTION_START, "", NULL);
506 if (IS_ERR(id_str)) {
508 return PTR_ERR(id_str);
511 t->id = simple_strtoul(id_str, NULL, 0);
515 EXPORT_SYMBOL_GPL(xenbus_transaction_start);
517 /* End a transaction.
518 * If abandon is true, transaction is discarded instead of committed.
520 int xenbus_transaction_end(struct xenbus_transaction t, int abort)
526 strcpy(abortstr, "F");
528 strcpy(abortstr, "T");
530 err = xs_error(xs_single(t, XS_TRANSACTION_END, abortstr, NULL));
536 EXPORT_SYMBOL_GPL(xenbus_transaction_end);
538 /* Single read and scanf: returns -errno or num scanned. */
539 int xenbus_scanf(struct xenbus_transaction t,
540 const char *dir, const char *node, const char *fmt, ...)
546 val = xenbus_read(t, dir, node, NULL);
551 ret = vsscanf(val, fmt, ap);
554 /* Distinctive errno. */
559 EXPORT_SYMBOL_GPL(xenbus_scanf);
561 /* Read an (optional) unsigned value. */
562 unsigned int xenbus_read_unsigned(const char *dir, const char *node,
563 unsigned int default_val)
568 ret = xenbus_scanf(XBT_NIL, dir, node, "%u", &val);
574 EXPORT_SYMBOL_GPL(xenbus_read_unsigned);
576 /* Single printf and write: returns -errno or 0. */
577 int xenbus_printf(struct xenbus_transaction t,
578 const char *dir, const char *node, const char *fmt, ...)
585 buf = kvasprintf(GFP_NOIO | __GFP_HIGH, fmt, ap);
591 ret = xenbus_write(t, dir, node, buf);
597 EXPORT_SYMBOL_GPL(xenbus_printf);
599 /* Takes tuples of names, scanf-style args, and void **, NULL terminated. */
600 int xenbus_gather(struct xenbus_transaction t, const char *dir, ...)
607 while (ret == 0 && (name = va_arg(ap, char *)) != NULL) {
608 const char *fmt = va_arg(ap, char *);
609 void *result = va_arg(ap, void *);
612 p = xenbus_read(t, dir, name, NULL);
618 if (sscanf(p, fmt, result) == 0)
622 *(char **)result = p;
627 EXPORT_SYMBOL_GPL(xenbus_gather);
629 static int xs_watch(const char *path, const char *token)
633 iov[0].iov_base = (void *)path;
634 iov[0].iov_len = strlen(path) + 1;
635 iov[1].iov_base = (void *)token;
636 iov[1].iov_len = strlen(token) + 1;
638 return xs_error(xs_talkv(XBT_NIL, XS_WATCH, iov,
639 ARRAY_SIZE(iov), NULL));
642 static int xs_unwatch(const char *path, const char *token)
646 iov[0].iov_base = (char *)path;
647 iov[0].iov_len = strlen(path) + 1;
648 iov[1].iov_base = (char *)token;
649 iov[1].iov_len = strlen(token) + 1;
651 return xs_error(xs_talkv(XBT_NIL, XS_UNWATCH, iov,
652 ARRAY_SIZE(iov), NULL));
655 static struct xenbus_watch *find_watch(const char *token)
657 struct xenbus_watch *i, *cmp;
659 cmp = (void *)simple_strtoul(token, NULL, 16);
661 list_for_each_entry(i, &watches, list)
668 * Certain older XenBus toolstack cannot handle reading values that are
669 * not populated. Some Xen 3.4 installation are incapable of doing this
670 * so if we are running on anything older than 4 do not attempt to read
671 * control/platform-feature-xs_reset_watches.
673 static bool xen_strict_xenbus_quirk(void)
676 uint32_t eax, ebx, ecx, edx, base;
678 base = xen_cpuid_base();
679 cpuid(base + 1, &eax, &ebx, &ecx, &edx);
687 static void xs_reset_watches(void)
691 if (!xen_hvm_domain() || xen_initial_domain())
694 if (xen_strict_xenbus_quirk())
697 if (!xenbus_read_unsigned("control",
698 "platform-feature-xs_reset_watches", 0))
701 err = xs_error(xs_single(XBT_NIL, XS_RESET_WATCHES, "", NULL));
702 if (err && err != -EEXIST)
703 pr_warn("xs_reset_watches failed: %d\n", err);
706 /* Register callback to watch this node. */
707 int register_xenbus_watch(struct xenbus_watch *watch)
709 /* Pointer in ascii is the token. */
710 char token[sizeof(watch) * 2 + 1];
713 sprintf(token, "%lX", (long)watch);
715 down_read(&xs_state.watch_mutex);
717 spin_lock(&watches_lock);
718 BUG_ON(find_watch(token));
719 list_add(&watch->list, &watches);
720 spin_unlock(&watches_lock);
722 err = xs_watch(watch->node, token);
725 spin_lock(&watches_lock);
726 list_del(&watch->list);
727 spin_unlock(&watches_lock);
730 up_read(&xs_state.watch_mutex);
734 EXPORT_SYMBOL_GPL(register_xenbus_watch);
736 void unregister_xenbus_watch(struct xenbus_watch *watch)
738 struct xs_stored_msg *msg, *tmp;
739 char token[sizeof(watch) * 2 + 1];
742 sprintf(token, "%lX", (long)watch);
744 down_read(&xs_state.watch_mutex);
746 spin_lock(&watches_lock);
747 BUG_ON(!find_watch(token));
748 list_del(&watch->list);
749 spin_unlock(&watches_lock);
751 err = xs_unwatch(watch->node, token);
753 pr_warn("Failed to release watch %s: %i\n", watch->node, err);
755 up_read(&xs_state.watch_mutex);
757 /* Make sure there are no callbacks running currently (unless
759 if (current->pid != xenwatch_pid)
760 mutex_lock(&xenwatch_mutex);
762 /* Cancel pending watch events. */
763 spin_lock(&watch_events_lock);
764 list_for_each_entry_safe(msg, tmp, &watch_events, list) {
765 if (msg->u.watch.handle != watch)
767 list_del(&msg->list);
768 kfree(msg->u.watch.path);
771 spin_unlock(&watch_events_lock);
773 if (current->pid != xenwatch_pid)
774 mutex_unlock(&xenwatch_mutex);
776 EXPORT_SYMBOL_GPL(unregister_xenbus_watch);
778 void xs_suspend(void)
780 transaction_suspend();
781 down_write(&xs_state.watch_mutex);
782 mutex_lock(&xs_state.request_mutex);
783 mutex_lock(&xs_state.response_mutex);
788 struct xenbus_watch *watch;
789 char token[sizeof(watch) * 2 + 1];
793 mutex_unlock(&xs_state.response_mutex);
794 mutex_unlock(&xs_state.request_mutex);
795 transaction_resume();
797 /* No need for watches_lock: the watch_mutex is sufficient. */
798 list_for_each_entry(watch, &watches, list) {
799 sprintf(token, "%lX", (long)watch);
800 xs_watch(watch->node, token);
803 up_write(&xs_state.watch_mutex);
806 void xs_suspend_cancel(void)
808 mutex_unlock(&xs_state.response_mutex);
809 mutex_unlock(&xs_state.request_mutex);
810 up_write(&xs_state.watch_mutex);
811 mutex_unlock(&xs_state.transaction_mutex);
814 static int xenwatch_thread(void *unused)
816 struct list_head *ent;
817 struct xs_stored_msg *msg;
820 wait_event_interruptible(watch_events_waitq,
821 !list_empty(&watch_events));
823 if (kthread_should_stop())
826 mutex_lock(&xenwatch_mutex);
828 spin_lock(&watch_events_lock);
829 ent = watch_events.next;
830 if (ent != &watch_events)
832 spin_unlock(&watch_events_lock);
834 if (ent != &watch_events) {
835 msg = list_entry(ent, struct xs_stored_msg, list);
836 msg->u.watch.handle->callback(msg->u.watch.handle,
839 kfree(msg->u.watch.path);
843 mutex_unlock(&xenwatch_mutex);
849 static int process_msg(void)
851 struct xs_stored_msg *msg;
856 * We must disallow save/restore while reading a xenstore message.
857 * A partial read across s/r leaves us out of sync with xenstored.
860 err = xb_wait_for_data_to_read();
863 mutex_lock(&xs_state.response_mutex);
864 if (xb_data_to_read())
866 /* We raced with save/restore: pending data 'disappeared'. */
867 mutex_unlock(&xs_state.response_mutex);
871 msg = kmalloc(sizeof(*msg), GFP_NOIO | __GFP_HIGH);
877 err = xb_read(&msg->hdr, sizeof(msg->hdr));
883 if (msg->hdr.len > XENSTORE_PAYLOAD_MAX) {
889 body = kmalloc(msg->hdr.len + 1, GFP_NOIO | __GFP_HIGH);
896 err = xb_read(body, msg->hdr.len);
902 body[msg->hdr.len] = '\0';
904 if (msg->hdr.type == XS_WATCH_EVENT) {
905 if (count_strings(body, msg->hdr.len) != 2) {
911 msg->u.watch.path = (const char *)body;
912 msg->u.watch.token = (const char *)strchr(body, '\0') + 1;
914 spin_lock(&watches_lock);
915 msg->u.watch.handle = find_watch(msg->u.watch.token);
916 if (msg->u.watch.handle != NULL) {
917 spin_lock(&watch_events_lock);
918 list_add_tail(&msg->list, &watch_events);
919 wake_up(&watch_events_waitq);
920 spin_unlock(&watch_events_lock);
925 spin_unlock(&watches_lock);
927 msg->u.reply.body = body;
928 spin_lock(&xs_state.reply_lock);
929 list_add_tail(&msg->list, &xs_state.reply_list);
930 spin_unlock(&xs_state.reply_lock);
931 wake_up(&xs_state.reply_waitq);
935 mutex_unlock(&xs_state.response_mutex);
939 static int xenbus_thread(void *unused)
946 pr_warn("error %d while reading message\n", err);
947 if (kthread_should_stop())
957 struct task_struct *task;
959 INIT_LIST_HEAD(&xs_state.reply_list);
960 spin_lock_init(&xs_state.reply_lock);
961 init_waitqueue_head(&xs_state.reply_waitq);
963 mutex_init(&xs_state.request_mutex);
964 mutex_init(&xs_state.response_mutex);
965 mutex_init(&xs_state.transaction_mutex);
966 init_rwsem(&xs_state.watch_mutex);
967 atomic_set(&xs_state.transaction_count, 0);
968 init_waitqueue_head(&xs_state.transaction_wq);
970 /* Initialize the shared memory rings to talk to xenstored */
971 err = xb_init_comms();
975 task = kthread_run(xenwatch_thread, NULL, "xenwatch");
977 return PTR_ERR(task);
978 xenwatch_pid = task->pid;
980 task = kthread_run(xenbus_thread, NULL, "xenbus");
982 return PTR_ERR(task);
984 /* shutdown watches for kexec boot */