- Update Xen patches to 3.3-rc5 and c/s 1157.
[linux-flexiantxendom0-3.2.10.git] / drivers / xen / xenbus / xenbus_xs.c
1 /******************************************************************************
2  * xenbus_xs.c
3  *
4  * This is the kernel equivalent of the "xs" library.  We don't need everything
5  * and we use xenbus_comms for communication.
6  *
7  * Copyright (C) 2005 Rusty Russell, IBM Corporation
8  *
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:
14  *
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:
21  *
22  * The above copyright notice and this permission notice shall be included in
23  * all copies or substantial portions of the Software.
24  *
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
31  * IN THE SOFTWARE.
32  */
33
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>
48 #include <xen/xen.h>
49 #include "xenbus_comms.h"
50
51 #ifdef HAVE_XEN_PLATFORM_COMPAT_H
52 #include <xen/platform-compat.h>
53 #endif
54
55 #ifndef PF_NOFREEZE /* Old kernel (pre-2.6.6). */
56 #define PF_NOFREEZE     0
57 #endif
58
59 struct xs_stored_msg {
60         struct list_head list;
61
62         struct xsd_sockmsg hdr;
63
64         union {
65                 /* Queued replies. */
66                 struct {
67                         char *body;
68                 } reply;
69
70                 /* Queued watch events. */
71                 struct {
72                         struct xenbus_watch *handle;
73                         char **vec;
74                         unsigned int vec_size;
75                 } watch;
76         } u;
77 };
78
79 struct xs_handle {
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;
84
85         /*
86          * Mutex ordering: transaction_mutex -> watch_mutex -> request_mutex.
87          * response_mutex is never taken simultaneously with the other three.
88          *
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.
92          *
93          * When decrementing transaction_count to zero the wait queue
94          * should be woken up, the suspend code waits for count to
95          * reach zero.
96          */
97
98         /* One request at a time. */
99         struct mutex request_mutex;
100
101         /* Protect xenbus reader thread against save/restore. */
102         struct mutex response_mutex;
103
104         /* Protect transactions against save/restore. */
105         struct mutex transaction_mutex;
106         atomic_t transaction_count;
107         wait_queue_head_t transaction_wq;
108
109         /* Protect watch (de)register against save/restore. */
110         struct rw_semaphore watch_mutex;
111 };
112
113 static struct xs_handle xs_state;
114
115 /* List of registered watches, and a lock to protect it. */
116 static LIST_HEAD(watches);
117 static DEFINE_SPINLOCK(watches_lock);
118
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);
122
123 /*
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
127  * carrying out work.
128  */
129 static pid_t xenwatch_pid;
130 /* static */ DEFINE_MUTEX(xenwatch_mutex);
131 static DECLARE_WAIT_QUEUE_HEAD(watch_events_waitq);
132
133 static int get_error(const char *errorstring)
134 {
135         unsigned int i;
136
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",
140                                    errorstring);
141                         return EINVAL;
142                 }
143         }
144         return xsd_errors[i].errnum;
145 }
146
147 static void *read_reply(enum xsd_sockmsg_type *type, unsigned int *len)
148 {
149         struct xs_stored_msg *msg;
150         char *body;
151
152         spin_lock(&xs_state.reply_lock);
153
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);
160         }
161
162         msg = list_entry(xs_state.reply_list.next,
163                          struct xs_stored_msg, list);
164         list_del(&msg->list);
165
166         spin_unlock(&xs_state.reply_lock);
167
168         *type = msg->hdr.type;
169         if (len)
170                 *len = msg->hdr.len;
171         body = msg->u.reply.body;
172
173         kfree(msg);
174
175         return body;
176 }
177
178 static void transaction_start(void)
179 {
180         mutex_lock(&xs_state.transaction_mutex);
181         atomic_inc(&xs_state.transaction_count);
182         mutex_unlock(&xs_state.transaction_mutex);
183 }
184
185 static void transaction_end(void)
186 {
187         if (atomic_dec_and_test(&xs_state.transaction_count))
188                 wake_up(&xs_state.transaction_wq);
189 }
190
191 static void transaction_suspend(void)
192 {
193         mutex_lock(&xs_state.transaction_mutex);
194         wait_event(xs_state.transaction_wq,
195                    atomic_read(&xs_state.transaction_count) == 0);
196 }
197
198 static void transaction_resume(void)
199 {
200         mutex_unlock(&xs_state.transaction_mutex);
201 }
202
203 void *xenbus_dev_request_and_reply(struct xsd_sockmsg *msg)
204 {
205         void *ret;
206         enum xsd_sockmsg_type type = msg->type;
207         int err;
208
209         if (type == XS_TRANSACTION_START)
210                 transaction_start();
211
212         mutex_lock(&xs_state.request_mutex);
213
214         err = xb_write(msg, sizeof(*msg) + msg->len);
215         if (err) {
216                 msg->type = XS_ERROR;
217                 ret = ERR_PTR(err);
218         } else
219                 ret = read_reply(&msg->type, &msg->len);
220
221         mutex_unlock(&xs_state.request_mutex);
222
223         if ((type == XS_TRANSACTION_END) ||
224             ((type == XS_TRANSACTION_START) && (msg->type == XS_ERROR)))
225                 transaction_end();
226
227         return ret;
228 }
229 #if !defined(CONFIG_XEN) && !defined(MODULE)
230 EXPORT_SYMBOL(xenbus_dev_request_and_reply);
231 #endif
232
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,
238                       unsigned int *len)
239 {
240         struct xsd_sockmsg msg;
241         void *ret = NULL;
242         unsigned int i;
243         int err;
244
245         msg.tx_id = t.id;
246         msg.req_id = 0;
247         msg.type = type;
248         msg.len = 0;
249         for (i = 0; i < num_vecs; i++)
250                 msg.len += iovec[i].iov_len;
251
252         mutex_lock(&xs_state.request_mutex);
253
254         err = xb_write(&msg, sizeof(msg));
255         if (err) {
256                 mutex_unlock(&xs_state.request_mutex);
257                 return ERR_PTR(err);
258         }
259
260         for (i = 0; i < num_vecs; i++) {
261                 err = xb_write(iovec[i].iov_base, iovec[i].iov_len);
262                 if (err) {
263                         mutex_unlock(&xs_state.request_mutex);
264                         return ERR_PTR(err);
265                 }
266         }
267
268         ret = read_reply(&msg.type, len);
269
270         mutex_unlock(&xs_state.request_mutex);
271
272         if (IS_ERR(ret))
273                 return ret;
274
275         if (msg.type == XS_ERROR) {
276                 err = get_error(ret);
277                 kfree(ret);
278                 return ERR_PTR(-err);
279         }
280
281         if (msg.type != type) {
282                 if (printk_ratelimit())
283                         pr_warning("XENBUS unexpected type [%d],"
284                                    " expected [%d]\n",
285                                    msg.type, type);
286                 kfree(ret);
287                 return ERR_PTR(-EINVAL);
288         }
289         return ret;
290 }
291
292 /* Simplified version of xs_talkv: single message. */
293 static void *xs_single(struct xenbus_transaction t,
294                        enum xsd_sockmsg_type type,
295                        const char *string,
296                        unsigned int *len)
297 {
298         struct kvec iovec;
299
300         iovec.iov_base = (void *)string;
301         iovec.iov_len = strlen(string) + 1;
302         return xs_talkv(t, type, &iovec, 1, len);
303 }
304
305 /* Many commands only need an ack, don't care what it says. */
306 static int xs_error(char *reply)
307 {
308         if (IS_ERR(reply))
309                 return PTR_ERR(reply);
310         kfree(reply);
311         return 0;
312 }
313
314 static unsigned int count_strings(const char *strings, unsigned int len)
315 {
316         unsigned int num;
317         const char *p;
318
319         for (p = strings, num = 0; p < strings + len; p += strlen(p) + 1)
320                 num++;
321
322         return num;
323 }
324
325 /* Return the path to dir with /name appended. Buffer must be kfree()'ed. */
326 static char *join(const char *dir, const char *name)
327 {
328         char *buffer;
329
330         if (strlen(name) == 0)
331                 buffer = kasprintf(GFP_NOIO | __GFP_HIGH, "%s", dir);
332         else
333                 buffer = kasprintf(GFP_NOIO | __GFP_HIGH, "%s/%s", dir, name);
334         return (!buffer) ? ERR_PTR(-ENOMEM) : buffer;
335 }
336
337 static char **split(char *strings, unsigned int len, unsigned int *num)
338 {
339         char *p, **ret;
340
341         /* Count the strings. */
342         *num = count_strings(strings, len) + 1;
343
344         /* Transfer to one big alloc for easy freeing. */
345         ret = kmalloc(*num * sizeof(char *) + len, GFP_NOIO | __GFP_HIGH);
346         if (!ret) {
347                 kfree(strings);
348                 return ERR_PTR(-ENOMEM);
349         }
350         memcpy(&ret[*num], strings, len);
351         kfree(strings);
352
353         strings = (char *)&ret[*num];
354         for (p = strings, *num = 0; p < strings + len; p += strlen(p) + 1)
355                 ret[(*num)++] = p;
356         ret[*num] = strings + len;
357
358         return ret;
359 }
360
361 char **xenbus_directory(struct xenbus_transaction t,
362                         const char *dir, const char *node, unsigned int *num)
363 {
364         char *strings, *path;
365         unsigned int len;
366
367         path = join(dir, node);
368         if (IS_ERR(path))
369                 return (char **)path;
370
371         strings = xs_single(t, XS_DIRECTORY, path, &len);
372         kfree(path);
373         if (IS_ERR(strings))
374                 return (char **)strings;
375
376         return split(strings, len, num);
377 }
378 EXPORT_SYMBOL_GPL(xenbus_directory);
379
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)
383 {
384         char **d;
385         int dir_n;
386
387         d = xenbus_directory(t, dir, node, &dir_n);
388         if (IS_ERR(d))
389                 return 0;
390         kfree(d);
391         return 1;
392 }
393 EXPORT_SYMBOL_GPL(xenbus_exists);
394
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.
398  */
399 void *xenbus_read(struct xenbus_transaction t,
400                   const char *dir, const char *node, unsigned int *len)
401 {
402         char *path;
403         void *ret;
404
405         path = join(dir, node);
406         if (IS_ERR(path))
407                 return (void *)path;
408
409         ret = xs_single(t, XS_READ, path, len);
410         kfree(path);
411         return ret;
412 }
413 EXPORT_SYMBOL_GPL(xenbus_read);
414
415 /* Write the value of a single file.
416  * Returns -err on failure.
417  */
418 int xenbus_write(struct xenbus_transaction t,
419                  const char *dir, const char *node, const char *string)
420 {
421         const char *path;
422         struct kvec iovec[2];
423         int ret;
424
425         path = join(dir, node);
426         if (IS_ERR(path))
427                 return PTR_ERR(path);
428
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);
433
434         ret = xs_error(xs_talkv(t, XS_WRITE, iovec, ARRAY_SIZE(iovec), NULL));
435         kfree(path);
436         return ret;
437 }
438 EXPORT_SYMBOL_GPL(xenbus_write);
439
440 /* Create a new directory. */
441 int xenbus_mkdir(struct xenbus_transaction t,
442                  const char *dir, const char *node)
443 {
444         char *path;
445         int ret;
446
447         path = join(dir, node);
448         if (IS_ERR(path))
449                 return PTR_ERR(path);
450
451         ret = xs_error(xs_single(t, XS_MKDIR, path, NULL));
452         kfree(path);
453         return ret;
454 }
455 EXPORT_SYMBOL_GPL(xenbus_mkdir);
456
457 /* Destroy a file or directory (directories must be empty). */
458 int xenbus_rm(struct xenbus_transaction t, const char *dir, const char *node)
459 {
460         char *path;
461         int ret;
462
463         path = join(dir, node);
464         if (IS_ERR(path))
465                 return PTR_ERR(path);
466
467         ret = xs_error(xs_single(t, XS_RM, path, NULL));
468         kfree(path);
469         return ret;
470 }
471 EXPORT_SYMBOL_GPL(xenbus_rm);
472
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.
475  */
476 int xenbus_transaction_start(struct xenbus_transaction *t)
477 {
478         char *id_str;
479
480         transaction_start();
481
482         id_str = xs_single(XBT_NIL, XS_TRANSACTION_START, "", NULL);
483         if (IS_ERR(id_str)) {
484                 transaction_end();
485                 return PTR_ERR(id_str);
486         }
487
488         t->id = simple_strtoul(id_str, NULL, 0);
489         kfree(id_str);
490         return 0;
491 }
492 EXPORT_SYMBOL_GPL(xenbus_transaction_start);
493
494 /* End a transaction.
495  * If abandon is true, transaction is discarded instead of committed.
496  */
497 int xenbus_transaction_end(struct xenbus_transaction t, int abort)
498 {
499         char abortstr[2];
500         int err;
501
502         if (abort)
503                 strcpy(abortstr, "F");
504         else
505                 strcpy(abortstr, "T");
506
507         err = xs_error(xs_single(t, XS_TRANSACTION_END, abortstr, NULL));
508
509         transaction_end();
510
511         return err;
512 }
513 EXPORT_SYMBOL_GPL(xenbus_transaction_end);
514
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, ...)
518 {
519         va_list ap;
520         int ret;
521         char *val;
522
523         val = xenbus_read(t, dir, node, NULL);
524         if (IS_ERR(val))
525                 return PTR_ERR(val);
526
527         va_start(ap, fmt);
528         ret = vsscanf(val, fmt, ap);
529         va_end(ap);
530         kfree(val);
531         /* Distinctive errno. */
532         if (ret == 0)
533                 return -ERANGE;
534         return ret;
535 }
536 EXPORT_SYMBOL_GPL(xenbus_scanf);
537
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, ...)
541 {
542         va_list ap;
543         int ret;
544         char *printf_buffer;
545
546         va_start(ap, fmt);
547         printf_buffer = kvasprintf(GFP_NOIO | __GFP_HIGH, fmt, ap);
548         va_end(ap);
549
550         if (!printf_buffer)
551                 return -ENOMEM;
552
553         ret = xenbus_write(t, dir, node, printf_buffer);
554
555         kfree(printf_buffer);
556
557         return ret;
558 }
559 EXPORT_SYMBOL_GPL(xenbus_printf);
560
561 /* Takes tuples of names, scanf-style args, and void **, NULL terminated. */
562 int xenbus_gather(struct xenbus_transaction t, const char *dir, ...)
563 {
564         va_list ap;
565         const char *name;
566         int ret = 0;
567
568         va_start(ap, 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 *);
572                 char *p;
573
574                 p = xenbus_read(t, dir, name, NULL);
575                 if (IS_ERR(p)) {
576                         ret = PTR_ERR(p);
577                         break;
578                 }
579                 if (fmt) {
580                         if (sscanf(p, fmt, result) == 0)
581                                 ret = -EINVAL;
582                         kfree(p);
583                 } else
584                         *(char **)result = p;
585         }
586         va_end(ap);
587         return ret;
588 }
589 EXPORT_SYMBOL_GPL(xenbus_gather);
590
591 static int xs_watch(const char *path, const char *token)
592 {
593         struct kvec iov[2];
594
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;
599
600         return xs_error(xs_talkv(XBT_NIL, XS_WATCH, iov,
601                                  ARRAY_SIZE(iov), NULL));
602 }
603
604 static int xs_unwatch(const char *path, const char *token)
605 {
606         struct kvec iov[2];
607
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;
612
613         return xs_error(xs_talkv(XBT_NIL, XS_UNWATCH, iov,
614                                  ARRAY_SIZE(iov), NULL));
615 }
616
617 static struct xenbus_watch *find_watch(const char *token)
618 {
619         struct xenbus_watch *i, *cmp;
620
621         cmp = (void *)simple_strtoul(token, NULL, 16);
622
623         list_for_each_entry(i, &watches, list)
624                 if (i == cmp)
625                         return i;
626
627         return NULL;
628 }
629
630 static void xs_reset_watches(void)
631 {
632 #ifdef MODULE
633         int err, supported = 0;
634
635         err = xenbus_scanf(XBT_NIL, "control",
636                            "platform-feature-xs_reset_watches", "%d",
637                            &supported);
638         if (err != 1 || !supported)
639                 return;
640
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);
644 #endif
645 }
646
647 /* Register callback to watch this node. */
648 int register_xenbus_watch(struct xenbus_watch *watch)
649 {
650         /* Pointer in ascii is the token. */
651         char token[sizeof(watch) * 2 + 1];
652         int err;
653
654         sprintf(token, "%lX", (long)watch);
655
656         down_read(&xs_state.watch_mutex);
657
658         spin_lock(&watches_lock);
659         BUG_ON(find_watch(token));
660         list_add(&watch->list, &watches);
661         spin_unlock(&watches_lock);
662
663         err = xs_watch(watch->node, token);
664
665         if (err) {
666                 spin_lock(&watches_lock);
667                 list_del(&watch->list);
668                 spin_unlock(&watches_lock);
669         }
670
671         up_read(&xs_state.watch_mutex);
672
673         return err;
674 }
675 EXPORT_SYMBOL_GPL(register_xenbus_watch);
676
677 void unregister_xenbus_watch(struct xenbus_watch *watch)
678 {
679         struct xs_stored_msg *msg, *tmp;
680         char token[sizeof(watch) * 2 + 1];
681         int err;
682
683 #if defined(CONFIG_XEN) || defined(MODULE)
684         BUG_ON(watch->flags & XBWF_new_thread);
685 #endif
686
687         sprintf(token, "%lX", (long)watch);
688
689         down_read(&xs_state.watch_mutex);
690
691         spin_lock(&watches_lock);
692         BUG_ON(!find_watch(token));
693         list_del(&watch->list);
694         spin_unlock(&watches_lock);
695
696         err = xs_unwatch(watch->node, token);
697         if (err)
698                 pr_warning("XENBUS Failed to release watch %s: %i\n",
699                            watch->node, err);
700
701         up_read(&xs_state.watch_mutex);
702
703         /* Make sure there are no callbacks running currently (unless
704            its us) */
705         if (current->pid != xenwatch_pid)
706                 mutex_lock(&xenwatch_mutex);
707
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)
712                         continue;
713                 list_del(&msg->list);
714                 kfree(msg->u.watch.vec);
715                 kfree(msg);
716         }
717         spin_unlock(&watch_events_lock);
718
719         if (current->pid != xenwatch_pid)
720                 mutex_unlock(&xenwatch_mutex);
721 }
722 EXPORT_SYMBOL_GPL(unregister_xenbus_watch);
723
724 void xs_suspend(void)
725 {
726         transaction_suspend();
727         down_write(&xs_state.watch_mutex);
728         mutex_lock(&xs_state.request_mutex);
729         mutex_lock(&xs_state.response_mutex);
730 }
731
732 void xs_resume(void)
733 {
734         struct xenbus_watch *watch;
735         char token[sizeof(watch) * 2 + 1];
736
737 #if !defined(CONFIG_XEN) && !defined(MODULE)
738         xb_init_comms();
739 #endif
740
741         mutex_unlock(&xs_state.response_mutex);
742         mutex_unlock(&xs_state.request_mutex);
743         transaction_resume();
744
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);
749         }
750
751         up_write(&xs_state.watch_mutex);
752 }
753
754 void xs_suspend_cancel(void)
755 {
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);
760 }
761
762 #if defined(CONFIG_XEN) || defined(MODULE)
763 static int xenwatch_handle_callback(void *data)
764 {
765         struct xs_stored_msg *msg = data;
766
767         msg->u.watch.handle->callback(msg->u.watch.handle,
768                                       (const char **)msg->u.watch.vec,
769                                       msg->u.watch.vec_size);
770
771         kfree(msg->u.watch.vec);
772         kfree(msg);
773
774         /* Kill this kthread if we were spawned just for this callback. */
775         if (current->pid != xenwatch_pid)
776                 do_exit(0);
777
778         return 0;
779 }
780 #endif
781
782 static int xenwatch_thread(void *unused)
783 {
784         struct list_head *ent;
785         struct xs_stored_msg *msg;
786
787         current->flags |= PF_NOFREEZE;
788         for (;;) {
789                 wait_event_interruptible(watch_events_waitq,
790                                          !list_empty(&watch_events));
791
792                 if (kthread_should_stop())
793                         break;
794
795                 mutex_lock(&xenwatch_mutex);
796
797                 spin_lock(&watch_events_lock);
798                 ent = watch_events.next;
799                 if (ent != &watch_events)
800                         list_del(ent);
801                 spin_unlock(&watch_events_lock);
802
803                 if (ent == &watch_events) {
804                         mutex_unlock(&xenwatch_mutex);
805                         continue;
806                 }
807
808                 msg = list_entry(ent, struct xs_stored_msg, list);
809
810 #if defined(CONFIG_XEN) || defined(MODULE)
811                 /*
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.
818                  */
819                 if (msg->u.watch.handle->flags & XBWF_new_thread) {
820                         mutex_unlock(&xenwatch_mutex);
821                         kthread_run(xenwatch_handle_callback,
822                                     msg, "xenwatch_cb");
823                 } else {
824                         xenwatch_handle_callback(msg);
825                         mutex_unlock(&xenwatch_mutex);
826                 }
827 #else
828                 msg->u.watch.handle->callback(
829                         msg->u.watch.handle,
830                         (const char **)msg->u.watch.vec,
831                         msg->u.watch.vec_size);
832                 mutex_unlock(&xenwatch_mutex);
833                 kfree(msg->u.watch.vec);
834                 kfree(msg);
835 #endif
836         }
837
838         return 0;
839 }
840
841 static int process_msg(void)
842 {
843         struct xs_stored_msg *msg;
844         char *body;
845         int err;
846
847         /*
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.
850          */
851         for (;;) {
852                 err = xb_wait_for_data_to_read();
853                 if (err)
854                         return err;
855                 mutex_lock(&xs_state.response_mutex);
856                 if (xb_data_to_read())
857                         break;
858                 /* We raced with save/restore: pending data 'disappeared'. */
859                 mutex_unlock(&xs_state.response_mutex);
860         }
861
862
863         msg = kmalloc(sizeof(*msg), GFP_NOIO | __GFP_HIGH);
864         if (msg == NULL) {
865                 err = -ENOMEM;
866                 goto out;
867         }
868
869         err = xb_read(&msg->hdr, sizeof(msg->hdr));
870         if (err) {
871                 kfree(msg);
872                 goto out;
873         }
874
875         if (msg->hdr.len > XENSTORE_PAYLOAD_MAX) {
876                 kfree(msg);
877                 err = -EINVAL;
878                 goto out;
879         }
880
881         body = kmalloc(msg->hdr.len + 1, GFP_NOIO | __GFP_HIGH);
882         if (body == NULL) {
883                 kfree(msg);
884                 err = -ENOMEM;
885                 goto out;
886         }
887
888         err = xb_read(body, msg->hdr.len);
889         if (err) {
890                 kfree(body);
891                 kfree(msg);
892                 goto out;
893         }
894         body[msg->hdr.len] = '\0';
895
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);
901                         kfree(msg);
902                         goto out;
903                 }
904
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);
913                 } else {
914                         kfree(msg->u.watch.vec);
915                         kfree(msg);
916                 }
917                 spin_unlock(&watches_lock);
918         } else {
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);
924         }
925
926  out:
927         mutex_unlock(&xs_state.response_mutex);
928         return err;
929 }
930
931 static int xenbus_thread(void *unused)
932 {
933         int err;
934
935         current->flags |= PF_NOFREEZE;
936         for (;;) {
937                 err = process_msg();
938                 if (err)
939                         pr_warning("XENBUS error %d while reading "
940                                    "message\n", err);
941                 if (kthread_should_stop())
942                         break;
943         }
944
945         return 0;
946 }
947
948 int xs_init(void)
949 {
950         struct task_struct *task;
951
952         INIT_LIST_HEAD(&xs_state.reply_list);
953         spin_lock_init(&xs_state.reply_lock);
954         init_waitqueue_head(&xs_state.reply_waitq);
955
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);
962
963         task = kthread_run(xenwatch_thread, NULL, "xenwatch");
964         if (IS_ERR(task))
965                 return PTR_ERR(task);
966         xenwatch_pid = task->pid;
967
968         task = kthread_run(xenbus_thread, NULL, "xenbus");
969         if (IS_ERR(task))
970                 return PTR_ERR(task);
971
972         /* shutdown watches for kexec boot */
973         xs_reset_watches();
974
975         return 0;
976 }