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 <xen/xenbus.h>
46 #include "xenbus_comms.h"
49 extern char *kasprintf(const char *fmt, ...);
51 struct xs_stored_msg {
52 struct list_head list;
54 struct xsd_sockmsg hdr;
62 /* Queued watch events. */
64 struct xenbus_watch *handle;
66 unsigned int vec_size;
72 /* A list of replies. Currently only one will ever be outstanding. */
73 struct list_head reply_list;
74 spinlock_t reply_lock;
75 wait_queue_head_t reply_waitq;
77 /* One request at a time. */
78 struct mutex request_mutex;
80 /* Protect transactions against save/restore. */
81 struct rw_semaphore suspend_mutex;
84 static struct xs_handle xs_state;
86 /* List of registered watches, and a lock to protect it. */
87 static LIST_HEAD(watches);
88 static DEFINE_SPINLOCK(watches_lock);
90 /* List of pending watch callback events, and a lock to protect it. */
91 static LIST_HEAD(watch_events);
92 static DEFINE_SPINLOCK(watch_events_lock);
95 * Details of the xenwatch callback kernel thread. The thread waits on the
96 * watch_events_waitq for work to do (queued on watch_events list). When it
97 * wakes up it acquires the xenwatch_mutex before reading the list and
100 static pid_t xenwatch_pid;
101 /* static */ DEFINE_MUTEX(xenwatch_mutex);
102 static DECLARE_WAIT_QUEUE_HEAD(watch_events_waitq);
104 static int get_error(const char *errorstring)
108 for (i = 0; strcmp(errorstring, xsd_errors[i].errstring) != 0; i++) {
109 if (i == ARRAY_SIZE(xsd_errors) - 1) {
111 "XENBUS xen store gave: unknown error %s",
116 return xsd_errors[i].errnum;
119 static void *read_reply(enum xsd_sockmsg_type *type, unsigned int *len)
121 struct xs_stored_msg *msg;
124 spin_lock(&xs_state.reply_lock);
126 while (list_empty(&xs_state.reply_list)) {
127 spin_unlock(&xs_state.reply_lock);
128 /* XXX FIXME: Avoid synchronous wait for response here. */
129 wait_event(xs_state.reply_waitq,
130 !list_empty(&xs_state.reply_list));
131 spin_lock(&xs_state.reply_lock);
134 msg = list_entry(xs_state.reply_list.next,
135 struct xs_stored_msg, list);
136 list_del(&msg->list);
138 spin_unlock(&xs_state.reply_lock);
140 *type = msg->hdr.type;
143 body = msg->u.reply.body;
150 /* Emergency write. */
151 void xenbus_debug_write(const char *str, unsigned int count)
153 struct xsd_sockmsg msg = { 0 };
156 msg.len = sizeof("print") + count + 1;
158 mutex_lock(&xs_state.request_mutex);
159 xb_write(&msg, sizeof(msg));
160 xb_write("print", sizeof("print"));
161 xb_write(str, count);
163 mutex_unlock(&xs_state.request_mutex);
166 void *xenbus_dev_request_and_reply(struct xsd_sockmsg *msg)
169 struct xsd_sockmsg req_msg = *msg;
172 if (req_msg.type == XS_TRANSACTION_START)
173 down_read(&xs_state.suspend_mutex);
175 mutex_lock(&xs_state.request_mutex);
177 err = xb_write(msg, sizeof(*msg) + msg->len);
179 msg->type = XS_ERROR;
182 ret = read_reply(&msg->type, &msg->len);
184 mutex_unlock(&xs_state.request_mutex);
186 if ((req_msg.type == XS_TRANSACTION_END) ||
187 ((req_msg.type == XS_TRANSACTION_START) &&
188 (msg->type == XS_ERROR)))
189 up_read(&xs_state.suspend_mutex);
194 /* Send message to xs, get kmalloc'ed reply. ERR_PTR() on error. */
195 static void *xs_talkv(struct xenbus_transaction t,
196 enum xsd_sockmsg_type type,
197 const struct kvec *iovec,
198 unsigned int num_vecs,
201 struct xsd_sockmsg msg;
210 for (i = 0; i < num_vecs; i++)
211 msg.len += iovec[i].iov_len;
213 mutex_lock(&xs_state.request_mutex);
215 err = xb_write(&msg, sizeof(msg));
217 mutex_unlock(&xs_state.request_mutex);
221 for (i = 0; i < num_vecs; i++) {
222 err = xb_write(iovec[i].iov_base, iovec[i].iov_len);;
224 mutex_unlock(&xs_state.request_mutex);
229 ret = read_reply(&msg.type, len);
231 mutex_unlock(&xs_state.request_mutex);
236 if (msg.type == XS_ERROR) {
237 err = get_error(ret);
239 return ERR_PTR(-err);
242 if (msg.type != type) {
243 if (printk_ratelimit())
245 "XENBUS unexpected type [%d], expected [%d]\n",
248 return ERR_PTR(-EINVAL);
253 /* Simplified version of xs_talkv: single message. */
254 static void *xs_single(struct xenbus_transaction t,
255 enum xsd_sockmsg_type type,
261 iovec.iov_base = (void *)string;
262 iovec.iov_len = strlen(string) + 1;
263 return xs_talkv(t, type, &iovec, 1, len);
266 /* Many commands only need an ack, don't care what it says. */
267 static int xs_error(char *reply)
270 return PTR_ERR(reply);
275 static unsigned int count_strings(const char *strings, unsigned int len)
280 for (p = strings, num = 0; p < strings + len; p += strlen(p) + 1)
286 /* Return the path to dir with /name appended. Buffer must be kfree()'ed. */
287 static char *join(const char *dir, const char *name)
291 if (strlen(name) == 0)
292 buffer = kasprintf("%s", dir);
294 buffer = kasprintf("%s/%s", dir, name);
295 return (!buffer) ? ERR_PTR(-ENOMEM) : buffer;
298 static char **split(char *strings, unsigned int len, unsigned int *num)
302 /* Count the strings. */
303 *num = count_strings(strings, len);
305 /* Transfer to one big alloc for easy freeing. */
306 ret = kmalloc(*num * sizeof(char *) + len, GFP_KERNEL);
309 return ERR_PTR(-ENOMEM);
311 memcpy(&ret[*num], strings, len);
314 strings = (char *)&ret[*num];
315 for (p = strings, *num = 0; p < strings + len; p += strlen(p) + 1)
321 char **xenbus_directory(struct xenbus_transaction t,
322 const char *dir, const char *node, unsigned int *num)
324 char *strings, *path;
327 path = join(dir, node);
329 return (char **)path;
331 strings = xs_single(t, XS_DIRECTORY, path, &len);
334 return (char **)strings;
336 return split(strings, len, num);
338 EXPORT_SYMBOL_GPL(xenbus_directory);
340 /* Check if a path exists. Return 1 if it does. */
341 int xenbus_exists(struct xenbus_transaction t,
342 const char *dir, const char *node)
347 d = xenbus_directory(t, dir, node, &dir_n);
353 EXPORT_SYMBOL_GPL(xenbus_exists);
355 /* Get the value of a single file.
356 * Returns a kmalloced value: call free() on it after use.
357 * len indicates length in bytes.
359 void *xenbus_read(struct xenbus_transaction t,
360 const char *dir, const char *node, unsigned int *len)
365 path = join(dir, node);
369 ret = xs_single(t, XS_READ, path, len);
373 EXPORT_SYMBOL_GPL(xenbus_read);
375 /* Write the value of a single file.
376 * Returns -err on failure.
378 int xenbus_write(struct xenbus_transaction t,
379 const char *dir, const char *node, const char *string)
382 struct kvec iovec[2];
385 path = join(dir, node);
387 return PTR_ERR(path);
389 iovec[0].iov_base = (void *)path;
390 iovec[0].iov_len = strlen(path) + 1;
391 iovec[1].iov_base = (void *)string;
392 iovec[1].iov_len = strlen(string);
394 ret = xs_error(xs_talkv(t, XS_WRITE, iovec, ARRAY_SIZE(iovec), NULL));
398 EXPORT_SYMBOL_GPL(xenbus_write);
400 /* Create a new directory. */
401 int xenbus_mkdir(struct xenbus_transaction t,
402 const char *dir, const char *node)
407 path = join(dir, node);
409 return PTR_ERR(path);
411 ret = xs_error(xs_single(t, XS_MKDIR, path, NULL));
415 EXPORT_SYMBOL_GPL(xenbus_mkdir);
417 /* Destroy a file or directory (directories must be empty). */
418 int xenbus_rm(struct xenbus_transaction t, const char *dir, const char *node)
423 path = join(dir, node);
425 return PTR_ERR(path);
427 ret = xs_error(xs_single(t, XS_RM, path, NULL));
431 EXPORT_SYMBOL_GPL(xenbus_rm);
433 /* Start a transaction: changes by others will not be seen during this
434 * transaction, and changes will not be visible to others until end.
436 int xenbus_transaction_start(struct xenbus_transaction *t)
440 down_read(&xs_state.suspend_mutex);
442 id_str = xs_single(XBT_NIL, XS_TRANSACTION_START, "", NULL);
443 if (IS_ERR(id_str)) {
444 up_read(&xs_state.suspend_mutex);
445 return PTR_ERR(id_str);
448 t->id = simple_strtoul(id_str, NULL, 0);
452 EXPORT_SYMBOL_GPL(xenbus_transaction_start);
454 /* End a transaction.
455 * If abandon is true, transaction is discarded instead of committed.
457 int xenbus_transaction_end(struct xenbus_transaction t, int abort)
463 strcpy(abortstr, "F");
465 strcpy(abortstr, "T");
467 err = xs_error(xs_single(t, XS_TRANSACTION_END, abortstr, NULL));
469 up_read(&xs_state.suspend_mutex);
473 EXPORT_SYMBOL_GPL(xenbus_transaction_end);
475 /* Single read and scanf: returns -errno or num scanned. */
476 int xenbus_scanf(struct xenbus_transaction t,
477 const char *dir, const char *node, const char *fmt, ...)
483 val = xenbus_read(t, dir, node, NULL);
488 ret = vsscanf(val, fmt, ap);
491 /* Distinctive errno. */
496 EXPORT_SYMBOL_GPL(xenbus_scanf);
498 /* Single printf and write: returns -errno or 0. */
499 int xenbus_printf(struct xenbus_transaction t,
500 const char *dir, const char *node, const char *fmt, ...)
504 #define PRINTF_BUFFER_SIZE 4096
507 printf_buffer = kmalloc(PRINTF_BUFFER_SIZE, GFP_KERNEL);
508 if (printf_buffer == NULL)
512 ret = vsnprintf(printf_buffer, PRINTF_BUFFER_SIZE, fmt, ap);
515 BUG_ON(ret > PRINTF_BUFFER_SIZE-1);
516 ret = xenbus_write(t, dir, node, printf_buffer);
518 kfree(printf_buffer);
522 EXPORT_SYMBOL_GPL(xenbus_printf);
524 /* Takes tuples of names, scanf-style args, and void **, NULL terminated. */
525 int xenbus_gather(struct xenbus_transaction t, const char *dir, ...)
532 while (ret == 0 && (name = va_arg(ap, char *)) != NULL) {
533 const char *fmt = va_arg(ap, char *);
534 void *result = va_arg(ap, void *);
537 p = xenbus_read(t, dir, name, NULL);
543 if (sscanf(p, fmt, result) == 0)
547 *(char **)result = p;
552 EXPORT_SYMBOL_GPL(xenbus_gather);
554 static int xs_watch(const char *path, const char *token)
558 iov[0].iov_base = (void *)path;
559 iov[0].iov_len = strlen(path) + 1;
560 iov[1].iov_base = (void *)token;
561 iov[1].iov_len = strlen(token) + 1;
563 return xs_error(xs_talkv(XBT_NIL, XS_WATCH, iov,
564 ARRAY_SIZE(iov), NULL));
567 static int xs_unwatch(const char *path, const char *token)
571 iov[0].iov_base = (char *)path;
572 iov[0].iov_len = strlen(path) + 1;
573 iov[1].iov_base = (char *)token;
574 iov[1].iov_len = strlen(token) + 1;
576 return xs_error(xs_talkv(XBT_NIL, XS_UNWATCH, iov,
577 ARRAY_SIZE(iov), NULL));
580 static struct xenbus_watch *find_watch(const char *token)
582 struct xenbus_watch *i, *cmp;
584 cmp = (void *)simple_strtoul(token, NULL, 16);
586 list_for_each_entry(i, &watches, list)
593 /* Register callback to watch this node. */
594 int register_xenbus_watch(struct xenbus_watch *watch)
596 /* Pointer in ascii is the token. */
597 char token[sizeof(watch) * 2 + 1];
600 sprintf(token, "%lX", (long)watch);
602 down_read(&xs_state.suspend_mutex);
604 spin_lock(&watches_lock);
605 BUG_ON(find_watch(token));
606 list_add(&watch->list, &watches);
607 spin_unlock(&watches_lock);
609 err = xs_watch(watch->node, token);
611 /* Ignore errors due to multiple registration. */
612 if ((err != 0) && (err != -EEXIST)) {
613 spin_lock(&watches_lock);
614 list_del(&watch->list);
615 spin_unlock(&watches_lock);
618 up_read(&xs_state.suspend_mutex);
622 EXPORT_SYMBOL_GPL(register_xenbus_watch);
624 void unregister_xenbus_watch(struct xenbus_watch *watch)
626 struct xs_stored_msg *msg, *tmp;
627 char token[sizeof(watch) * 2 + 1];
630 sprintf(token, "%lX", (long)watch);
632 down_read(&xs_state.suspend_mutex);
634 spin_lock(&watches_lock);
635 BUG_ON(!find_watch(token));
636 list_del(&watch->list);
637 spin_unlock(&watches_lock);
639 err = xs_unwatch(watch->node, token);
642 "XENBUS Failed to release watch %s: %i\n",
645 up_read(&xs_state.suspend_mutex);
647 /* Cancel pending watch events. */
648 spin_lock(&watch_events_lock);
649 list_for_each_entry_safe(msg, tmp, &watch_events, list) {
650 if (msg->u.watch.handle != watch)
652 list_del(&msg->list);
653 kfree(msg->u.watch.vec);
656 spin_unlock(&watch_events_lock);
658 /* Flush any currently-executing callback, unless we are it. :-) */
659 if (current->pid != xenwatch_pid) {
660 mutex_lock(&xenwatch_mutex);
661 mutex_unlock(&xenwatch_mutex);
664 EXPORT_SYMBOL_GPL(unregister_xenbus_watch);
666 void xs_suspend(void)
668 down_write(&xs_state.suspend_mutex);
669 mutex_lock(&xs_state.request_mutex);
674 struct xenbus_watch *watch;
675 char token[sizeof(watch) * 2 + 1];
677 mutex_unlock(&xs_state.request_mutex);
679 /* No need for watches_lock: the suspend_mutex is sufficient. */
680 list_for_each_entry(watch, &watches, list) {
681 sprintf(token, "%lX", (long)watch);
682 xs_watch(watch->node, token);
685 up_write(&xs_state.suspend_mutex);
688 static int xenwatch_handle_callback(void *data)
690 struct xs_stored_msg *msg = data;
692 msg->u.watch.handle->callback(msg->u.watch.handle,
693 (const char **)msg->u.watch.vec,
694 msg->u.watch.vec_size);
696 kfree(msg->u.watch.vec);
699 /* Kill this kthread if we were spawned just for this callback. */
700 if (current->pid != xenwatch_pid)
706 static int xenwatch_thread(void *unused)
708 struct list_head *ent;
709 struct xs_stored_msg *msg;
712 wait_event_interruptible(watch_events_waitq,
713 !list_empty(&watch_events));
715 if (kthread_should_stop())
718 mutex_lock(&xenwatch_mutex);
720 spin_lock(&watch_events_lock);
721 ent = watch_events.next;
722 if (ent != &watch_events)
724 spin_unlock(&watch_events_lock);
726 if (ent != &watch_events) {
727 msg = list_entry(ent, struct xs_stored_msg, list);
728 if (msg->u.watch.handle->flags & XBWF_new_thread)
729 kthread_run(xenwatch_handle_callback,
732 xenwatch_handle_callback(msg);
735 mutex_unlock(&xenwatch_mutex);
741 static int process_msg(void)
743 struct xs_stored_msg *msg;
747 msg = kmalloc(sizeof(*msg), GFP_KERNEL);
751 err = xb_read(&msg->hdr, sizeof(msg->hdr));
757 body = kmalloc(msg->hdr.len + 1, GFP_KERNEL);
763 err = xb_read(body, msg->hdr.len);
769 body[msg->hdr.len] = '\0';
771 if (msg->hdr.type == XS_WATCH_EVENT) {
772 msg->u.watch.vec = split(body, msg->hdr.len,
773 &msg->u.watch.vec_size);
774 if (IS_ERR(msg->u.watch.vec)) {
776 return PTR_ERR(msg->u.watch.vec);
779 spin_lock(&watches_lock);
780 msg->u.watch.handle = find_watch(
781 msg->u.watch.vec[XS_WATCH_TOKEN]);
782 if (msg->u.watch.handle != NULL) {
783 spin_lock(&watch_events_lock);
784 list_add_tail(&msg->list, &watch_events);
785 wake_up(&watch_events_waitq);
786 spin_unlock(&watch_events_lock);
788 kfree(msg->u.watch.vec);
791 spin_unlock(&watches_lock);
793 msg->u.reply.body = body;
794 spin_lock(&xs_state.reply_lock);
795 list_add_tail(&msg->list, &xs_state.reply_list);
796 spin_unlock(&xs_state.reply_lock);
797 wake_up(&xs_state.reply_waitq);
803 static int xenbus_thread(void *unused)
810 printk(KERN_WARNING "XENBUS error %d while reading "
812 if (kthread_should_stop())
822 struct task_struct *task;
824 INIT_LIST_HEAD(&xs_state.reply_list);
825 spin_lock_init(&xs_state.reply_lock);
826 init_waitqueue_head(&xs_state.reply_waitq);
828 mutex_init(&xs_state.request_mutex);
829 init_rwsem(&xs_state.suspend_mutex);
831 /* Initialize the shared memory rings to talk to xenstored */
832 err = xb_init_comms();
836 task = kthread_run(xenwatch_thread, NULL, "xenwatch");
838 return PTR_ERR(task);
839 xenwatch_pid = task->pid;
841 task = kthread_run(xenbus_thread, NULL, "xenbus");
843 return PTR_ERR(task);