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 #include <linux/unistd.h>
35 #include <linux/errno.h>
36 #include <linux/types.h>
37 #include <linux/uio.h>
38 #include <linux/kernel.h>
39 #include <linux/string.h>
40 #include <linux/err.h>
41 #include <linux/slab.h>
42 #include <linux/fcntl.h>
43 #include <linux/kthread.h>
44 #include <linux/rwsem.h>
45 #include <linux/module.h>
46 #include <linux/mutex.h>
47 #include <xen/xenbus.h>
49 #include "xenbus_comms.h"
51 #ifdef HAVE_XEN_PLATFORM_COMPAT_H
52 #include <xen/platform-compat.h>
55 #ifndef PF_NOFREEZE /* Old kernel (pre-2.6.6). */
59 struct xs_stored_msg {
60 struct list_head list;
62 struct xsd_sockmsg hdr;
70 /* Queued watch events. */
72 struct xenbus_watch *handle;
74 unsigned int vec_size;
80 /* A list of replies. Currently only one will ever be outstanding. */
81 struct list_head reply_list;
82 spinlock_t reply_lock;
83 wait_queue_head_t reply_waitq;
86 * Mutex ordering: transaction_mutex -> watch_mutex -> request_mutex.
87 * response_mutex is never taken simultaneously with the other three.
89 * transaction_mutex must be held before incrementing
90 * transaction_count. The mutex is held when a suspend is in
91 * progress to prevent new transactions starting.
93 * When decrementing transaction_count to zero the wait queue
94 * should be woken up, the suspend code waits for count to
98 /* One request at a time. */
99 struct mutex request_mutex;
101 /* Protect xenbus reader thread against save/restore. */
102 struct mutex response_mutex;
104 /* Protect transactions against save/restore. */
105 struct mutex transaction_mutex;
106 atomic_t transaction_count;
107 wait_queue_head_t transaction_wq;
109 /* Protect watch (de)register against save/restore. */
110 struct rw_semaphore watch_mutex;
113 static struct xs_handle xs_state;
115 /* List of registered watches, and a lock to protect it. */
116 static LIST_HEAD(watches);
117 static DEFINE_SPINLOCK(watches_lock);
119 /* List of pending watch callback events, and a lock to protect it. */
120 static LIST_HEAD(watch_events);
121 static DEFINE_SPINLOCK(watch_events_lock);
124 * Details of the xenwatch callback kernel thread. The thread waits on the
125 * watch_events_waitq for work to do (queued on watch_events list). When it
126 * wakes up it acquires the xenwatch_mutex before reading the list and
129 static pid_t xenwatch_pid;
130 /* static */ DEFINE_MUTEX(xenwatch_mutex);
131 static DECLARE_WAIT_QUEUE_HEAD(watch_events_waitq);
133 static int get_error(const char *errorstring)
137 for (i = 0; strcmp(errorstring, xsd_errors[i].errstring) != 0; i++) {
138 if (i == ARRAY_SIZE(xsd_errors) - 1) {
139 pr_warning("XENBUS xen store gave: unknown error %s",
144 return xsd_errors[i].errnum;
147 static void *read_reply(enum xsd_sockmsg_type *type, unsigned int *len)
149 struct xs_stored_msg *msg;
152 spin_lock(&xs_state.reply_lock);
154 while (list_empty(&xs_state.reply_list)) {
155 spin_unlock(&xs_state.reply_lock);
156 /* XXX FIXME: Avoid synchronous wait for response here. */
157 wait_event(xs_state.reply_waitq,
158 !list_empty(&xs_state.reply_list));
159 spin_lock(&xs_state.reply_lock);
162 msg = list_entry(xs_state.reply_list.next,
163 struct xs_stored_msg, list);
164 list_del(&msg->list);
166 spin_unlock(&xs_state.reply_lock);
168 *type = msg->hdr.type;
171 body = msg->u.reply.body;
178 static void transaction_start(void)
180 mutex_lock(&xs_state.transaction_mutex);
181 atomic_inc(&xs_state.transaction_count);
182 mutex_unlock(&xs_state.transaction_mutex);
185 static void transaction_end(void)
187 if (atomic_dec_and_test(&xs_state.transaction_count))
188 wake_up(&xs_state.transaction_wq);
191 static void transaction_suspend(void)
193 mutex_lock(&xs_state.transaction_mutex);
194 wait_event(xs_state.transaction_wq,
195 atomic_read(&xs_state.transaction_count) == 0);
198 static void transaction_resume(void)
200 mutex_unlock(&xs_state.transaction_mutex);
203 void *xenbus_dev_request_and_reply(struct xsd_sockmsg *msg)
206 enum xsd_sockmsg_type type = msg->type;
209 if (type == XS_TRANSACTION_START)
212 mutex_lock(&xs_state.request_mutex);
214 err = xb_write(msg, sizeof(*msg) + msg->len);
216 msg->type = XS_ERROR;
219 ret = read_reply(&msg->type, &msg->len);
221 mutex_unlock(&xs_state.request_mutex);
223 if ((type == XS_TRANSACTION_END) ||
224 ((type == XS_TRANSACTION_START) && (msg->type == XS_ERROR)))
229 #if !defined(CONFIG_XEN) && !defined(MODULE)
230 EXPORT_SYMBOL(xenbus_dev_request_and_reply);
233 /* Send message to xs, get kmalloc'ed reply. ERR_PTR() on error. */
234 static void *xs_talkv(struct xenbus_transaction t,
235 enum xsd_sockmsg_type type,
236 const struct kvec *iovec,
237 unsigned int num_vecs,
240 struct xsd_sockmsg msg;
249 for (i = 0; i < num_vecs; i++)
250 msg.len += iovec[i].iov_len;
252 mutex_lock(&xs_state.request_mutex);
254 err = xb_write(&msg, sizeof(msg));
256 mutex_unlock(&xs_state.request_mutex);
260 for (i = 0; i < num_vecs; i++) {
261 err = xb_write(iovec[i].iov_base, iovec[i].iov_len);
263 mutex_unlock(&xs_state.request_mutex);
268 ret = read_reply(&msg.type, len);
270 mutex_unlock(&xs_state.request_mutex);
275 if (msg.type == XS_ERROR) {
276 err = get_error(ret);
278 return ERR_PTR(-err);
281 if (msg.type != type) {
282 if (printk_ratelimit())
283 pr_warning("XENBUS unexpected type [%d],"
287 return ERR_PTR(-EINVAL);
292 /* Simplified version of xs_talkv: single message. */
293 static void *xs_single(struct xenbus_transaction t,
294 enum xsd_sockmsg_type type,
300 iovec.iov_base = (void *)string;
301 iovec.iov_len = strlen(string) + 1;
302 return xs_talkv(t, type, &iovec, 1, len);
305 /* Many commands only need an ack, don't care what it says. */
306 static int xs_error(char *reply)
309 return PTR_ERR(reply);
314 static unsigned int count_strings(const char *strings, unsigned int len)
319 for (p = strings, num = 0; p < strings + len; p += strlen(p) + 1)
325 /* Return the path to dir with /name appended. Buffer must be kfree()'ed. */
326 static char *join(const char *dir, const char *name)
330 if (strlen(name) == 0)
331 buffer = kasprintf(GFP_NOIO | __GFP_HIGH, "%s", dir);
333 buffer = kasprintf(GFP_NOIO | __GFP_HIGH, "%s/%s", dir, name);
334 return (!buffer) ? ERR_PTR(-ENOMEM) : buffer;
337 static char **split(char *strings, unsigned int len, unsigned int *num)
341 /* Count the strings. */
342 *num = count_strings(strings, len) + 1;
344 /* Transfer to one big alloc for easy freeing. */
345 ret = kmalloc(*num * sizeof(char *) + len, GFP_NOIO | __GFP_HIGH);
348 return ERR_PTR(-ENOMEM);
350 memcpy(&ret[*num], strings, len);
353 strings = (char *)&ret[*num];
354 for (p = strings, *num = 0; p < strings + len; p += strlen(p) + 1)
356 ret[*num] = strings + len;
361 char **xenbus_directory(struct xenbus_transaction t,
362 const char *dir, const char *node, unsigned int *num)
364 char *strings, *path;
367 path = join(dir, node);
369 return (char **)path;
371 strings = xs_single(t, XS_DIRECTORY, path, &len);
374 return (char **)strings;
376 return split(strings, len, num);
378 EXPORT_SYMBOL_GPL(xenbus_directory);
380 /* Check if a path exists. Return 1 if it does. */
381 int xenbus_exists(struct xenbus_transaction t,
382 const char *dir, const char *node)
387 d = xenbus_directory(t, dir, node, &dir_n);
393 EXPORT_SYMBOL_GPL(xenbus_exists);
395 /* Get the value of a single file.
396 * Returns a kmalloced value: call free() on it after use.
397 * len indicates length in bytes.
399 void *xenbus_read(struct xenbus_transaction t,
400 const char *dir, const char *node, unsigned int *len)
405 path = join(dir, node);
409 ret = xs_single(t, XS_READ, path, len);
413 EXPORT_SYMBOL_GPL(xenbus_read);
415 /* Write the value of a single file.
416 * Returns -err on failure.
418 int xenbus_write(struct xenbus_transaction t,
419 const char *dir, const char *node, const char *string)
422 struct kvec iovec[2];
425 path = join(dir, node);
427 return PTR_ERR(path);
429 iovec[0].iov_base = (void *)path;
430 iovec[0].iov_len = strlen(path) + 1;
431 iovec[1].iov_base = (void *)string;
432 iovec[1].iov_len = strlen(string);
434 ret = xs_error(xs_talkv(t, XS_WRITE, iovec, ARRAY_SIZE(iovec), NULL));
438 EXPORT_SYMBOL_GPL(xenbus_write);
440 /* Create a new directory. */
441 int xenbus_mkdir(struct xenbus_transaction t,
442 const char *dir, const char *node)
447 path = join(dir, node);
449 return PTR_ERR(path);
451 ret = xs_error(xs_single(t, XS_MKDIR, path, NULL));
455 EXPORT_SYMBOL_GPL(xenbus_mkdir);
457 /* Destroy a file or directory (directories must be empty). */
458 int xenbus_rm(struct xenbus_transaction t, const char *dir, const char *node)
463 path = join(dir, node);
465 return PTR_ERR(path);
467 ret = xs_error(xs_single(t, XS_RM, path, NULL));
471 EXPORT_SYMBOL_GPL(xenbus_rm);
473 /* Start a transaction: changes by others will not be seen during this
474 * transaction, and changes will not be visible to others until end.
476 int xenbus_transaction_start(struct xenbus_transaction *t)
482 id_str = xs_single(XBT_NIL, XS_TRANSACTION_START, "", NULL);
483 if (IS_ERR(id_str)) {
485 return PTR_ERR(id_str);
488 t->id = simple_strtoul(id_str, NULL, 0);
492 EXPORT_SYMBOL_GPL(xenbus_transaction_start);
494 /* End a transaction.
495 * If abandon is true, transaction is discarded instead of committed.
497 int xenbus_transaction_end(struct xenbus_transaction t, int abort)
503 strcpy(abortstr, "F");
505 strcpy(abortstr, "T");
507 err = xs_error(xs_single(t, XS_TRANSACTION_END, abortstr, NULL));
513 EXPORT_SYMBOL_GPL(xenbus_transaction_end);
515 /* Single read and scanf: returns -errno or num scanned. */
516 int xenbus_scanf(struct xenbus_transaction t,
517 const char *dir, const char *node, const char *fmt, ...)
523 val = xenbus_read(t, dir, node, NULL);
528 ret = vsscanf(val, fmt, ap);
531 /* Distinctive errno. */
536 EXPORT_SYMBOL_GPL(xenbus_scanf);
538 /* Single printf and write: returns -errno or 0. */
539 int xenbus_printf(struct xenbus_transaction t,
540 const char *dir, const char *node, const char *fmt, ...)
547 printf_buffer = kvasprintf(GFP_NOIO | __GFP_HIGH, fmt, ap);
553 ret = xenbus_write(t, dir, node, printf_buffer);
555 kfree(printf_buffer);
559 EXPORT_SYMBOL_GPL(xenbus_printf);
561 /* Takes tuples of names, scanf-style args, and void **, NULL terminated. */
562 int xenbus_gather(struct xenbus_transaction t, const char *dir, ...)
569 while (ret == 0 && (name = va_arg(ap, char *)) != NULL) {
570 const char *fmt = va_arg(ap, char *);
571 void *result = va_arg(ap, void *);
574 p = xenbus_read(t, dir, name, NULL);
580 if (sscanf(p, fmt, result) == 0)
584 *(char **)result = p;
589 EXPORT_SYMBOL_GPL(xenbus_gather);
591 static int xs_watch(const char *path, const char *token)
595 iov[0].iov_base = (void *)path;
596 iov[0].iov_len = strlen(path) + 1;
597 iov[1].iov_base = (void *)token;
598 iov[1].iov_len = strlen(token) + 1;
600 return xs_error(xs_talkv(XBT_NIL, XS_WATCH, iov,
601 ARRAY_SIZE(iov), NULL));
604 static int xs_unwatch(const char *path, const char *token)
608 iov[0].iov_base = (char *)path;
609 iov[0].iov_len = strlen(path) + 1;
610 iov[1].iov_base = (char *)token;
611 iov[1].iov_len = strlen(token) + 1;
613 return xs_error(xs_talkv(XBT_NIL, XS_UNWATCH, iov,
614 ARRAY_SIZE(iov), NULL));
617 static struct xenbus_watch *find_watch(const char *token)
619 struct xenbus_watch *i, *cmp;
621 cmp = (void *)simple_strtoul(token, NULL, 16);
623 list_for_each_entry(i, &watches, list)
630 static void xs_reset_watches(void)
633 int err, supported = 0;
635 err = xenbus_scanf(XBT_NIL, "control",
636 "platform-feature-xs_reset_watches", "%d",
638 if (err != 1 || !supported)
641 err = xs_error(xs_single(XBT_NIL, XS_RESET_WATCHES, "", NULL));
642 if (err && err != -EEXIST)
643 printk(KERN_WARNING "xs_reset_watches failed: %d\n", err);
647 /* Register callback to watch this node. */
648 int register_xenbus_watch(struct xenbus_watch *watch)
650 /* Pointer in ascii is the token. */
651 char token[sizeof(watch) * 2 + 1];
654 sprintf(token, "%lX", (long)watch);
656 down_read(&xs_state.watch_mutex);
658 spin_lock(&watches_lock);
659 BUG_ON(find_watch(token));
660 list_add(&watch->list, &watches);
661 spin_unlock(&watches_lock);
663 err = xs_watch(watch->node, token);
666 spin_lock(&watches_lock);
667 list_del(&watch->list);
668 spin_unlock(&watches_lock);
671 up_read(&xs_state.watch_mutex);
675 EXPORT_SYMBOL_GPL(register_xenbus_watch);
677 void unregister_xenbus_watch(struct xenbus_watch *watch)
679 struct xs_stored_msg *msg, *tmp;
680 char token[sizeof(watch) * 2 + 1];
683 #if defined(CONFIG_XEN) || defined(MODULE)
684 BUG_ON(watch->flags & XBWF_new_thread);
687 sprintf(token, "%lX", (long)watch);
689 down_read(&xs_state.watch_mutex);
691 spin_lock(&watches_lock);
692 BUG_ON(!find_watch(token));
693 list_del(&watch->list);
694 spin_unlock(&watches_lock);
696 err = xs_unwatch(watch->node, token);
698 pr_warning("XENBUS Failed to release watch %s: %i\n",
701 up_read(&xs_state.watch_mutex);
703 /* Make sure there are no callbacks running currently (unless
705 if (current->pid != xenwatch_pid)
706 mutex_lock(&xenwatch_mutex);
708 /* Cancel pending watch events. */
709 spin_lock(&watch_events_lock);
710 list_for_each_entry_safe(msg, tmp, &watch_events, list) {
711 if (msg->u.watch.handle != watch)
713 list_del(&msg->list);
714 kfree(msg->u.watch.vec);
717 spin_unlock(&watch_events_lock);
719 if (current->pid != xenwatch_pid)
720 mutex_unlock(&xenwatch_mutex);
722 EXPORT_SYMBOL_GPL(unregister_xenbus_watch);
724 void xs_suspend(void)
726 transaction_suspend();
727 down_write(&xs_state.watch_mutex);
728 mutex_lock(&xs_state.request_mutex);
729 mutex_lock(&xs_state.response_mutex);
734 struct xenbus_watch *watch;
735 char token[sizeof(watch) * 2 + 1];
737 #if !defined(CONFIG_XEN) && !defined(MODULE)
741 mutex_unlock(&xs_state.response_mutex);
742 mutex_unlock(&xs_state.request_mutex);
743 transaction_resume();
745 /* No need for watches_lock: the watch_mutex is sufficient. */
746 list_for_each_entry(watch, &watches, list) {
747 sprintf(token, "%lX", (long)watch);
748 xs_watch(watch->node, token);
751 up_write(&xs_state.watch_mutex);
754 void xs_suspend_cancel(void)
756 mutex_unlock(&xs_state.response_mutex);
757 mutex_unlock(&xs_state.request_mutex);
758 up_write(&xs_state.watch_mutex);
759 mutex_unlock(&xs_state.transaction_mutex);
762 #if defined(CONFIG_XEN) || defined(MODULE)
763 static int xenwatch_handle_callback(void *data)
765 struct xs_stored_msg *msg = data;
767 msg->u.watch.handle->callback(msg->u.watch.handle,
768 (const char **)msg->u.watch.vec,
769 msg->u.watch.vec_size);
771 kfree(msg->u.watch.vec);
774 /* Kill this kthread if we were spawned just for this callback. */
775 if (current->pid != xenwatch_pid)
782 static int xenwatch_thread(void *unused)
784 struct list_head *ent;
785 struct xs_stored_msg *msg;
787 current->flags |= PF_NOFREEZE;
789 wait_event_interruptible(watch_events_waitq,
790 !list_empty(&watch_events));
792 if (kthread_should_stop())
795 mutex_lock(&xenwatch_mutex);
797 spin_lock(&watch_events_lock);
798 ent = watch_events.next;
799 if (ent != &watch_events)
801 spin_unlock(&watch_events_lock);
803 if (ent == &watch_events) {
804 mutex_unlock(&xenwatch_mutex);
808 msg = list_entry(ent, struct xs_stored_msg, list);
810 #if defined(CONFIG_XEN) || defined(MODULE)
812 * Unlock the mutex before running an XBWF_new_thread
813 * handler. kthread_run can block which can deadlock
814 * against unregister_xenbus_watch() if we need to
815 * unregister other watches in order to make
816 * progress. This can occur on resume before the swap
817 * device is attached.
819 if (msg->u.watch.handle->flags & XBWF_new_thread) {
820 mutex_unlock(&xenwatch_mutex);
821 kthread_run(xenwatch_handle_callback,
824 xenwatch_handle_callback(msg);
825 mutex_unlock(&xenwatch_mutex);
828 msg->u.watch.handle->callback(
830 (const char **)msg->u.watch.vec,
831 msg->u.watch.vec_size);
832 mutex_unlock(&xenwatch_mutex);
833 kfree(msg->u.watch.vec);
841 static int process_msg(void)
843 struct xs_stored_msg *msg;
848 * We must disallow save/restore while reading a xenstore message.
849 * A partial read across s/r leaves us out of sync with xenstored.
852 err = xb_wait_for_data_to_read();
855 mutex_lock(&xs_state.response_mutex);
856 if (xb_data_to_read())
858 /* We raced with save/restore: pending data 'disappeared'. */
859 mutex_unlock(&xs_state.response_mutex);
863 msg = kmalloc(sizeof(*msg), GFP_NOIO | __GFP_HIGH);
869 err = xb_read(&msg->hdr, sizeof(msg->hdr));
875 if (msg->hdr.len > XENSTORE_PAYLOAD_MAX) {
881 body = kmalloc(msg->hdr.len + 1, GFP_NOIO | __GFP_HIGH);
888 err = xb_read(body, msg->hdr.len);
894 body[msg->hdr.len] = '\0';
896 if (msg->hdr.type == XS_WATCH_EVENT) {
897 msg->u.watch.vec = split(body, msg->hdr.len,
898 &msg->u.watch.vec_size);
899 if (IS_ERR(msg->u.watch.vec)) {
900 err = PTR_ERR(msg->u.watch.vec);
905 spin_lock(&watches_lock);
906 msg->u.watch.handle = find_watch(
907 msg->u.watch.vec[XS_WATCH_TOKEN]);
908 if (msg->u.watch.handle != NULL) {
909 spin_lock(&watch_events_lock);
910 list_add_tail(&msg->list, &watch_events);
911 wake_up(&watch_events_waitq);
912 spin_unlock(&watch_events_lock);
914 kfree(msg->u.watch.vec);
917 spin_unlock(&watches_lock);
919 msg->u.reply.body = body;
920 spin_lock(&xs_state.reply_lock);
921 list_add_tail(&msg->list, &xs_state.reply_list);
922 spin_unlock(&xs_state.reply_lock);
923 wake_up(&xs_state.reply_waitq);
927 mutex_unlock(&xs_state.response_mutex);
931 static int xenbus_thread(void *unused)
935 current->flags |= PF_NOFREEZE;
939 pr_warning("XENBUS error %d while reading "
941 if (kthread_should_stop())
950 struct task_struct *task;
952 INIT_LIST_HEAD(&xs_state.reply_list);
953 spin_lock_init(&xs_state.reply_lock);
954 init_waitqueue_head(&xs_state.reply_waitq);
956 mutex_init(&xs_state.request_mutex);
957 mutex_init(&xs_state.response_mutex);
958 mutex_init(&xs_state.transaction_mutex);
959 init_rwsem(&xs_state.watch_mutex);
960 atomic_set(&xs_state.transaction_count, 0);
961 init_waitqueue_head(&xs_state.transaction_wq);
963 task = kthread_run(xenwatch_thread, NULL, "xenwatch");
965 return PTR_ERR(task);
966 xenwatch_pid = task->pid;
968 task = kthread_run(xenbus_thread, NULL, "xenbus");
970 return PTR_ERR(task);
972 /* shutdown watches for kexec boot */