0bd3d47ad24d3433588311b216747858311f5db1
[cascardo/linux.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 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
35
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>
50 #include <xen/xen.h>
51 #include "xenbus_comms.h"
52 #include "xenbus_probe.h"
53
54 struct xs_stored_msg {
55         struct list_head list;
56
57         struct xsd_sockmsg hdr;
58
59         union {
60                 /* Queued replies. */
61                 struct {
62                         char *body;
63                 } reply;
64
65                 /* Queued watch events. */
66                 struct {
67                         struct xenbus_watch *handle;
68                         char **vec;
69                         unsigned int vec_size;
70                 } watch;
71         } u;
72 };
73
74 struct xs_handle {
75         /* A list of replies. Currently only one will ever be outstanding. */
76         struct list_head reply_list;
77         spinlock_t reply_lock;
78         wait_queue_head_t reply_waitq;
79
80         /*
81          * Mutex ordering: transaction_mutex -> watch_mutex -> request_mutex.
82          * response_mutex is never taken simultaneously with the other three.
83          *
84          * transaction_mutex must be held before incrementing
85          * transaction_count. The mutex is held when a suspend is in
86          * progress to prevent new transactions starting.
87          *
88          * When decrementing transaction_count to zero the wait queue
89          * should be woken up, the suspend code waits for count to
90          * reach zero.
91          */
92
93         /* One request at a time. */
94         struct mutex request_mutex;
95
96         /* Protect xenbus reader thread against save/restore. */
97         struct mutex response_mutex;
98
99         /* Protect transactions against save/restore. */
100         struct mutex transaction_mutex;
101         atomic_t transaction_count;
102         wait_queue_head_t transaction_wq;
103
104         /* Protect watch (de)register against save/restore. */
105         struct rw_semaphore watch_mutex;
106 };
107
108 static struct xs_handle xs_state;
109
110 /* List of registered watches, and a lock to protect it. */
111 static LIST_HEAD(watches);
112 static DEFINE_SPINLOCK(watches_lock);
113
114 /* List of pending watch callback events, and a lock to protect it. */
115 static LIST_HEAD(watch_events);
116 static DEFINE_SPINLOCK(watch_events_lock);
117
118 /*
119  * Details of the xenwatch callback kernel thread. The thread waits on the
120  * watch_events_waitq for work to do (queued on watch_events list). When it
121  * wakes up it acquires the xenwatch_mutex before reading the list and
122  * carrying out work.
123  */
124 static pid_t xenwatch_pid;
125 static DEFINE_MUTEX(xenwatch_mutex);
126 static DECLARE_WAIT_QUEUE_HEAD(watch_events_waitq);
127
128 static int get_error(const char *errorstring)
129 {
130         unsigned int i;
131
132         for (i = 0; strcmp(errorstring, xsd_errors[i].errstring) != 0; i++) {
133                 if (i == ARRAY_SIZE(xsd_errors) - 1) {
134                         pr_warn("xen store gave: unknown error %s\n",
135                                 errorstring);
136                         return EINVAL;
137                 }
138         }
139         return xsd_errors[i].errnum;
140 }
141
142 static bool xenbus_ok(void)
143 {
144         switch (xen_store_domain_type) {
145         case XS_LOCAL:
146                 switch (system_state) {
147                 case SYSTEM_POWER_OFF:
148                 case SYSTEM_RESTART:
149                 case SYSTEM_HALT:
150                         return false;
151                 default:
152                         break;
153                 }
154                 return true;
155         case XS_PV:
156         case XS_HVM:
157                 /* FIXME: Could check that the remote domain is alive,
158                  * but it is normally initial domain. */
159                 return true;
160         default:
161                 break;
162         }
163         return false;
164 }
165 static void *read_reply(enum xsd_sockmsg_type *type, unsigned int *len)
166 {
167         struct xs_stored_msg *msg;
168         char *body;
169
170         spin_lock(&xs_state.reply_lock);
171
172         while (list_empty(&xs_state.reply_list)) {
173                 spin_unlock(&xs_state.reply_lock);
174                 if (xenbus_ok())
175                         /* XXX FIXME: Avoid synchronous wait for response here. */
176                         wait_event_timeout(xs_state.reply_waitq,
177                                            !list_empty(&xs_state.reply_list),
178                                            msecs_to_jiffies(500));
179                 else {
180                         /*
181                          * If we are in the process of being shut-down there is
182                          * no point of trying to contact XenBus - it is either
183                          * killed (xenstored application) or the other domain
184                          * has been killed or is unreachable.
185                          */
186                         return ERR_PTR(-EIO);
187                 }
188                 spin_lock(&xs_state.reply_lock);
189         }
190
191         msg = list_entry(xs_state.reply_list.next,
192                          struct xs_stored_msg, list);
193         list_del(&msg->list);
194
195         spin_unlock(&xs_state.reply_lock);
196
197         *type = msg->hdr.type;
198         if (len)
199                 *len = msg->hdr.len;
200         body = msg->u.reply.body;
201
202         kfree(msg);
203
204         return body;
205 }
206
207 static void transaction_start(void)
208 {
209         mutex_lock(&xs_state.transaction_mutex);
210         atomic_inc(&xs_state.transaction_count);
211         mutex_unlock(&xs_state.transaction_mutex);
212 }
213
214 static void transaction_end(void)
215 {
216         if (atomic_dec_and_test(&xs_state.transaction_count))
217                 wake_up(&xs_state.transaction_wq);
218 }
219
220 static void transaction_suspend(void)
221 {
222         mutex_lock(&xs_state.transaction_mutex);
223         wait_event(xs_state.transaction_wq,
224                    atomic_read(&xs_state.transaction_count) == 0);
225 }
226
227 static void transaction_resume(void)
228 {
229         mutex_unlock(&xs_state.transaction_mutex);
230 }
231
232 void *xenbus_dev_request_and_reply(struct xsd_sockmsg *msg)
233 {
234         void *ret;
235         struct xsd_sockmsg req_msg = *msg;
236         int err;
237
238         if (req_msg.type == XS_TRANSACTION_START)
239                 transaction_start();
240
241         mutex_lock(&xs_state.request_mutex);
242
243         err = xb_write(msg, sizeof(*msg) + msg->len);
244         if (err) {
245                 msg->type = XS_ERROR;
246                 ret = ERR_PTR(err);
247         } else
248                 ret = read_reply(&msg->type, &msg->len);
249
250         mutex_unlock(&xs_state.request_mutex);
251
252         if ((msg->type == XS_TRANSACTION_END) ||
253             ((req_msg.type == XS_TRANSACTION_START) &&
254              (msg->type == XS_ERROR)))
255                 transaction_end();
256
257         return ret;
258 }
259 EXPORT_SYMBOL(xenbus_dev_request_and_reply);
260
261 /* Send message to xs, get kmalloc'ed reply.  ERR_PTR() on error. */
262 static void *xs_talkv(struct xenbus_transaction t,
263                       enum xsd_sockmsg_type type,
264                       const struct kvec *iovec,
265                       unsigned int num_vecs,
266                       unsigned int *len)
267 {
268         struct xsd_sockmsg msg;
269         void *ret = NULL;
270         unsigned int i;
271         int err;
272
273         msg.tx_id = t.id;
274         msg.req_id = 0;
275         msg.type = type;
276         msg.len = 0;
277         for (i = 0; i < num_vecs; i++)
278                 msg.len += iovec[i].iov_len;
279
280         mutex_lock(&xs_state.request_mutex);
281
282         err = xb_write(&msg, sizeof(msg));
283         if (err) {
284                 mutex_unlock(&xs_state.request_mutex);
285                 return ERR_PTR(err);
286         }
287
288         for (i = 0; i < num_vecs; i++) {
289                 err = xb_write(iovec[i].iov_base, iovec[i].iov_len);
290                 if (err) {
291                         mutex_unlock(&xs_state.request_mutex);
292                         return ERR_PTR(err);
293                 }
294         }
295
296         ret = read_reply(&msg.type, len);
297
298         mutex_unlock(&xs_state.request_mutex);
299
300         if (IS_ERR(ret))
301                 return ret;
302
303         if (msg.type == XS_ERROR) {
304                 err = get_error(ret);
305                 kfree(ret);
306                 return ERR_PTR(-err);
307         }
308
309         if (msg.type != type) {
310                 pr_warn_ratelimited("unexpected type [%d], expected [%d]\n",
311                                     msg.type, type);
312                 kfree(ret);
313                 return ERR_PTR(-EINVAL);
314         }
315         return ret;
316 }
317
318 /* Simplified version of xs_talkv: single message. */
319 static void *xs_single(struct xenbus_transaction t,
320                        enum xsd_sockmsg_type type,
321                        const char *string,
322                        unsigned int *len)
323 {
324         struct kvec iovec;
325
326         iovec.iov_base = (void *)string;
327         iovec.iov_len = strlen(string) + 1;
328         return xs_talkv(t, type, &iovec, 1, len);
329 }
330
331 /* Many commands only need an ack, don't care what it says. */
332 static int xs_error(char *reply)
333 {
334         if (IS_ERR(reply))
335                 return PTR_ERR(reply);
336         kfree(reply);
337         return 0;
338 }
339
340 static unsigned int count_strings(const char *strings, unsigned int len)
341 {
342         unsigned int num;
343         const char *p;
344
345         for (p = strings, num = 0; p < strings + len; p += strlen(p) + 1)
346                 num++;
347
348         return num;
349 }
350
351 /* Return the path to dir with /name appended. Buffer must be kfree()'ed. */
352 static char *join(const char *dir, const char *name)
353 {
354         char *buffer;
355
356         if (strlen(name) == 0)
357                 buffer = kasprintf(GFP_NOIO | __GFP_HIGH, "%s", dir);
358         else
359                 buffer = kasprintf(GFP_NOIO | __GFP_HIGH, "%s/%s", dir, name);
360         return (!buffer) ? ERR_PTR(-ENOMEM) : buffer;
361 }
362
363 static char **split(char *strings, unsigned int len, unsigned int *num)
364 {
365         char *p, **ret;
366
367         /* Count the strings. */
368         *num = count_strings(strings, len);
369
370         /* Transfer to one big alloc for easy freeing. */
371         ret = kmalloc(*num * sizeof(char *) + len, GFP_NOIO | __GFP_HIGH);
372         if (!ret) {
373                 kfree(strings);
374                 return ERR_PTR(-ENOMEM);
375         }
376         memcpy(&ret[*num], strings, len);
377         kfree(strings);
378
379         strings = (char *)&ret[*num];
380         for (p = strings, *num = 0; p < strings + len; p += strlen(p) + 1)
381                 ret[(*num)++] = p;
382
383         return ret;
384 }
385
386 char **xenbus_directory(struct xenbus_transaction t,
387                         const char *dir, const char *node, unsigned int *num)
388 {
389         char *strings, *path;
390         unsigned int len;
391
392         path = join(dir, node);
393         if (IS_ERR(path))
394                 return (char **)path;
395
396         strings = xs_single(t, XS_DIRECTORY, path, &len);
397         kfree(path);
398         if (IS_ERR(strings))
399                 return (char **)strings;
400
401         return split(strings, len, num);
402 }
403 EXPORT_SYMBOL_GPL(xenbus_directory);
404
405 /* Check if a path exists. Return 1 if it does. */
406 int xenbus_exists(struct xenbus_transaction t,
407                   const char *dir, const char *node)
408 {
409         char **d;
410         int dir_n;
411
412         d = xenbus_directory(t, dir, node, &dir_n);
413         if (IS_ERR(d))
414                 return 0;
415         kfree(d);
416         return 1;
417 }
418 EXPORT_SYMBOL_GPL(xenbus_exists);
419
420 /* Get the value of a single file.
421  * Returns a kmalloced value: call free() on it after use.
422  * len indicates length in bytes.
423  */
424 void *xenbus_read(struct xenbus_transaction t,
425                   const char *dir, const char *node, unsigned int *len)
426 {
427         char *path;
428         void *ret;
429
430         path = join(dir, node);
431         if (IS_ERR(path))
432                 return (void *)path;
433
434         ret = xs_single(t, XS_READ, path, len);
435         kfree(path);
436         return ret;
437 }
438 EXPORT_SYMBOL_GPL(xenbus_read);
439
440 /* Write the value of a single file.
441  * Returns -err on failure.
442  */
443 int xenbus_write(struct xenbus_transaction t,
444                  const char *dir, const char *node, const char *string)
445 {
446         const char *path;
447         struct kvec iovec[2];
448         int ret;
449
450         path = join(dir, node);
451         if (IS_ERR(path))
452                 return PTR_ERR(path);
453
454         iovec[0].iov_base = (void *)path;
455         iovec[0].iov_len = strlen(path) + 1;
456         iovec[1].iov_base = (void *)string;
457         iovec[1].iov_len = strlen(string);
458
459         ret = xs_error(xs_talkv(t, XS_WRITE, iovec, ARRAY_SIZE(iovec), NULL));
460         kfree(path);
461         return ret;
462 }
463 EXPORT_SYMBOL_GPL(xenbus_write);
464
465 /* Create a new directory. */
466 int xenbus_mkdir(struct xenbus_transaction t,
467                  const char *dir, const char *node)
468 {
469         char *path;
470         int ret;
471
472         path = join(dir, node);
473         if (IS_ERR(path))
474                 return PTR_ERR(path);
475
476         ret = xs_error(xs_single(t, XS_MKDIR, path, NULL));
477         kfree(path);
478         return ret;
479 }
480 EXPORT_SYMBOL_GPL(xenbus_mkdir);
481
482 /* Destroy a file or directory (directories must be empty). */
483 int xenbus_rm(struct xenbus_transaction t, const char *dir, const char *node)
484 {
485         char *path;
486         int ret;
487
488         path = join(dir, node);
489         if (IS_ERR(path))
490                 return PTR_ERR(path);
491
492         ret = xs_error(xs_single(t, XS_RM, path, NULL));
493         kfree(path);
494         return ret;
495 }
496 EXPORT_SYMBOL_GPL(xenbus_rm);
497
498 /* Start a transaction: changes by others will not be seen during this
499  * transaction, and changes will not be visible to others until end.
500  */
501 int xenbus_transaction_start(struct xenbus_transaction *t)
502 {
503         char *id_str;
504
505         transaction_start();
506
507         id_str = xs_single(XBT_NIL, XS_TRANSACTION_START, "", NULL);
508         if (IS_ERR(id_str)) {
509                 transaction_end();
510                 return PTR_ERR(id_str);
511         }
512
513         t->id = simple_strtoul(id_str, NULL, 0);
514         kfree(id_str);
515         return 0;
516 }
517 EXPORT_SYMBOL_GPL(xenbus_transaction_start);
518
519 /* End a transaction.
520  * If abandon is true, transaction is discarded instead of committed.
521  */
522 int xenbus_transaction_end(struct xenbus_transaction t, int abort)
523 {
524         char abortstr[2];
525         int err;
526
527         if (abort)
528                 strcpy(abortstr, "F");
529         else
530                 strcpy(abortstr, "T");
531
532         err = xs_error(xs_single(t, XS_TRANSACTION_END, abortstr, NULL));
533
534         transaction_end();
535
536         return err;
537 }
538 EXPORT_SYMBOL_GPL(xenbus_transaction_end);
539
540 /* Single read and scanf: returns -errno or num scanned. */
541 int xenbus_scanf(struct xenbus_transaction t,
542                  const char *dir, const char *node, const char *fmt, ...)
543 {
544         va_list ap;
545         int ret;
546         char *val;
547
548         val = xenbus_read(t, dir, node, NULL);
549         if (IS_ERR(val))
550                 return PTR_ERR(val);
551
552         va_start(ap, fmt);
553         ret = vsscanf(val, fmt, ap);
554         va_end(ap);
555         kfree(val);
556         /* Distinctive errno. */
557         if (ret == 0)
558                 return -ERANGE;
559         return ret;
560 }
561 EXPORT_SYMBOL_GPL(xenbus_scanf);
562
563 /* Single printf and write: returns -errno or 0. */
564 int xenbus_printf(struct xenbus_transaction t,
565                   const char *dir, const char *node, const char *fmt, ...)
566 {
567         va_list ap;
568         int ret;
569         char *buf;
570
571         va_start(ap, fmt);
572         buf = kvasprintf(GFP_NOIO | __GFP_HIGH, fmt, ap);
573         va_end(ap);
574
575         if (!buf)
576                 return -ENOMEM;
577
578         ret = xenbus_write(t, dir, node, buf);
579
580         kfree(buf);
581
582         return ret;
583 }
584 EXPORT_SYMBOL_GPL(xenbus_printf);
585
586 /* Takes tuples of names, scanf-style args, and void **, NULL terminated. */
587 int xenbus_gather(struct xenbus_transaction t, const char *dir, ...)
588 {
589         va_list ap;
590         const char *name;
591         int ret = 0;
592
593         va_start(ap, dir);
594         while (ret == 0 && (name = va_arg(ap, char *)) != NULL) {
595                 const char *fmt = va_arg(ap, char *);
596                 void *result = va_arg(ap, void *);
597                 char *p;
598
599                 p = xenbus_read(t, dir, name, NULL);
600                 if (IS_ERR(p)) {
601                         ret = PTR_ERR(p);
602                         break;
603                 }
604                 if (fmt) {
605                         if (sscanf(p, fmt, result) == 0)
606                                 ret = -EINVAL;
607                         kfree(p);
608                 } else
609                         *(char **)result = p;
610         }
611         va_end(ap);
612         return ret;
613 }
614 EXPORT_SYMBOL_GPL(xenbus_gather);
615
616 static int xs_watch(const char *path, const char *token)
617 {
618         struct kvec iov[2];
619
620         iov[0].iov_base = (void *)path;
621         iov[0].iov_len = strlen(path) + 1;
622         iov[1].iov_base = (void *)token;
623         iov[1].iov_len = strlen(token) + 1;
624
625         return xs_error(xs_talkv(XBT_NIL, XS_WATCH, iov,
626                                  ARRAY_SIZE(iov), NULL));
627 }
628
629 static int xs_unwatch(const char *path, const char *token)
630 {
631         struct kvec iov[2];
632
633         iov[0].iov_base = (char *)path;
634         iov[0].iov_len = strlen(path) + 1;
635         iov[1].iov_base = (char *)token;
636         iov[1].iov_len = strlen(token) + 1;
637
638         return xs_error(xs_talkv(XBT_NIL, XS_UNWATCH, iov,
639                                  ARRAY_SIZE(iov), NULL));
640 }
641
642 static struct xenbus_watch *find_watch(const char *token)
643 {
644         struct xenbus_watch *i, *cmp;
645
646         cmp = (void *)simple_strtoul(token, NULL, 16);
647
648         list_for_each_entry(i, &watches, list)
649                 if (i == cmp)
650                         return i;
651
652         return NULL;
653 }
654 /*
655  * Certain older XenBus toolstack cannot handle reading values that are
656  * not populated. Some Xen 3.4 installation are incapable of doing this
657  * so if we are running on anything older than 4 do not attempt to read
658  * control/platform-feature-xs_reset_watches.
659  */
660 static bool xen_strict_xenbus_quirk(void)
661 {
662 #ifdef CONFIG_X86
663         uint32_t eax, ebx, ecx, edx, base;
664
665         base = xen_cpuid_base();
666         cpuid(base + 1, &eax, &ebx, &ecx, &edx);
667
668         if ((eax >> 16) < 4)
669                 return true;
670 #endif
671         return false;
672
673 }
674 static void xs_reset_watches(void)
675 {
676         int err, supported = 0;
677
678         if (!xen_hvm_domain() || xen_initial_domain())
679                 return;
680
681         if (xen_strict_xenbus_quirk())
682                 return;
683
684         err = xenbus_scanf(XBT_NIL, "control",
685                         "platform-feature-xs_reset_watches", "%d", &supported);
686         if (err != 1 || !supported)
687                 return;
688
689         err = xs_error(xs_single(XBT_NIL, XS_RESET_WATCHES, "", NULL));
690         if (err && err != -EEXIST)
691                 pr_warn("xs_reset_watches failed: %d\n", err);
692 }
693
694 /* Register callback to watch this node. */
695 int register_xenbus_watch(struct xenbus_watch *watch)
696 {
697         /* Pointer in ascii is the token. */
698         char token[sizeof(watch) * 2 + 1];
699         int err;
700
701         sprintf(token, "%lX", (long)watch);
702
703         down_read(&xs_state.watch_mutex);
704
705         spin_lock(&watches_lock);
706         BUG_ON(find_watch(token));
707         list_add(&watch->list, &watches);
708         spin_unlock(&watches_lock);
709
710         err = xs_watch(watch->node, token);
711
712         if (err) {
713                 spin_lock(&watches_lock);
714                 list_del(&watch->list);
715                 spin_unlock(&watches_lock);
716         }
717
718         up_read(&xs_state.watch_mutex);
719
720         return err;
721 }
722 EXPORT_SYMBOL_GPL(register_xenbus_watch);
723
724 void unregister_xenbus_watch(struct xenbus_watch *watch)
725 {
726         struct xs_stored_msg *msg, *tmp;
727         char token[sizeof(watch) * 2 + 1];
728         int err;
729
730         sprintf(token, "%lX", (long)watch);
731
732         down_read(&xs_state.watch_mutex);
733
734         spin_lock(&watches_lock);
735         BUG_ON(!find_watch(token));
736         list_del(&watch->list);
737         spin_unlock(&watches_lock);
738
739         err = xs_unwatch(watch->node, token);
740         if (err)
741                 pr_warn("Failed to release watch %s: %i\n", watch->node, err);
742
743         up_read(&xs_state.watch_mutex);
744
745         /* Make sure there are no callbacks running currently (unless
746            its us) */
747         if (current->pid != xenwatch_pid)
748                 mutex_lock(&xenwatch_mutex);
749
750         /* Cancel pending watch events. */
751         spin_lock(&watch_events_lock);
752         list_for_each_entry_safe(msg, tmp, &watch_events, list) {
753                 if (msg->u.watch.handle != watch)
754                         continue;
755                 list_del(&msg->list);
756                 kfree(msg->u.watch.vec);
757                 kfree(msg);
758         }
759         spin_unlock(&watch_events_lock);
760
761         if (current->pid != xenwatch_pid)
762                 mutex_unlock(&xenwatch_mutex);
763 }
764 EXPORT_SYMBOL_GPL(unregister_xenbus_watch);
765
766 void xs_suspend(void)
767 {
768         transaction_suspend();
769         down_write(&xs_state.watch_mutex);
770         mutex_lock(&xs_state.request_mutex);
771         mutex_lock(&xs_state.response_mutex);
772 }
773
774 void xs_resume(void)
775 {
776         struct xenbus_watch *watch;
777         char token[sizeof(watch) * 2 + 1];
778
779         xb_init_comms();
780
781         mutex_unlock(&xs_state.response_mutex);
782         mutex_unlock(&xs_state.request_mutex);
783         transaction_resume();
784
785         /* No need for watches_lock: the watch_mutex is sufficient. */
786         list_for_each_entry(watch, &watches, list) {
787                 sprintf(token, "%lX", (long)watch);
788                 xs_watch(watch->node, token);
789         }
790
791         up_write(&xs_state.watch_mutex);
792 }
793
794 void xs_suspend_cancel(void)
795 {
796         mutex_unlock(&xs_state.response_mutex);
797         mutex_unlock(&xs_state.request_mutex);
798         up_write(&xs_state.watch_mutex);
799         mutex_unlock(&xs_state.transaction_mutex);
800 }
801
802 static int xenwatch_thread(void *unused)
803 {
804         struct list_head *ent;
805         struct xs_stored_msg *msg;
806
807         for (;;) {
808                 wait_event_interruptible(watch_events_waitq,
809                                          !list_empty(&watch_events));
810
811                 if (kthread_should_stop())
812                         break;
813
814                 mutex_lock(&xenwatch_mutex);
815
816                 spin_lock(&watch_events_lock);
817                 ent = watch_events.next;
818                 if (ent != &watch_events)
819                         list_del(ent);
820                 spin_unlock(&watch_events_lock);
821
822                 if (ent != &watch_events) {
823                         msg = list_entry(ent, struct xs_stored_msg, list);
824                         msg->u.watch.handle->callback(
825                                 msg->u.watch.handle,
826                                 (const char **)msg->u.watch.vec,
827                                 msg->u.watch.vec_size);
828                         kfree(msg->u.watch.vec);
829                         kfree(msg);
830                 }
831
832                 mutex_unlock(&xenwatch_mutex);
833         }
834
835         return 0;
836 }
837
838 static int process_msg(void)
839 {
840         struct xs_stored_msg *msg;
841         char *body;
842         int err;
843
844         /*
845          * We must disallow save/restore while reading a xenstore message.
846          * A partial read across s/r leaves us out of sync with xenstored.
847          */
848         for (;;) {
849                 err = xb_wait_for_data_to_read();
850                 if (err)
851                         return err;
852                 mutex_lock(&xs_state.response_mutex);
853                 if (xb_data_to_read())
854                         break;
855                 /* We raced with save/restore: pending data 'disappeared'. */
856                 mutex_unlock(&xs_state.response_mutex);
857         }
858
859
860         msg = kmalloc(sizeof(*msg), GFP_NOIO | __GFP_HIGH);
861         if (msg == NULL) {
862                 err = -ENOMEM;
863                 goto out;
864         }
865
866         err = xb_read(&msg->hdr, sizeof(msg->hdr));
867         if (err) {
868                 kfree(msg);
869                 goto out;
870         }
871
872         if (msg->hdr.len > XENSTORE_PAYLOAD_MAX) {
873                 kfree(msg);
874                 err = -EINVAL;
875                 goto out;
876         }
877
878         body = kmalloc(msg->hdr.len + 1, GFP_NOIO | __GFP_HIGH);
879         if (body == NULL) {
880                 kfree(msg);
881                 err = -ENOMEM;
882                 goto out;
883         }
884
885         err = xb_read(body, msg->hdr.len);
886         if (err) {
887                 kfree(body);
888                 kfree(msg);
889                 goto out;
890         }
891         body[msg->hdr.len] = '\0';
892
893         if (msg->hdr.type == XS_WATCH_EVENT) {
894                 msg->u.watch.vec = split(body, msg->hdr.len,
895                                          &msg->u.watch.vec_size);
896                 if (IS_ERR(msg->u.watch.vec)) {
897                         err = PTR_ERR(msg->u.watch.vec);
898                         kfree(msg);
899                         goto out;
900                 }
901
902                 spin_lock(&watches_lock);
903                 msg->u.watch.handle = find_watch(
904                         msg->u.watch.vec[XS_WATCH_TOKEN]);
905                 if (msg->u.watch.handle != NULL) {
906                         spin_lock(&watch_events_lock);
907                         list_add_tail(&msg->list, &watch_events);
908                         wake_up(&watch_events_waitq);
909                         spin_unlock(&watch_events_lock);
910                 } else {
911                         kfree(msg->u.watch.vec);
912                         kfree(msg);
913                 }
914                 spin_unlock(&watches_lock);
915         } else {
916                 msg->u.reply.body = body;
917                 spin_lock(&xs_state.reply_lock);
918                 list_add_tail(&msg->list, &xs_state.reply_list);
919                 spin_unlock(&xs_state.reply_lock);
920                 wake_up(&xs_state.reply_waitq);
921         }
922
923  out:
924         mutex_unlock(&xs_state.response_mutex);
925         return err;
926 }
927
928 static int xenbus_thread(void *unused)
929 {
930         int err;
931
932         for (;;) {
933                 err = process_msg();
934                 if (err)
935                         pr_warn("error %d while reading message\n", err);
936                 if (kthread_should_stop())
937                         break;
938         }
939
940         return 0;
941 }
942
943 int xs_init(void)
944 {
945         int err;
946         struct task_struct *task;
947
948         INIT_LIST_HEAD(&xs_state.reply_list);
949         spin_lock_init(&xs_state.reply_lock);
950         init_waitqueue_head(&xs_state.reply_waitq);
951
952         mutex_init(&xs_state.request_mutex);
953         mutex_init(&xs_state.response_mutex);
954         mutex_init(&xs_state.transaction_mutex);
955         init_rwsem(&xs_state.watch_mutex);
956         atomic_set(&xs_state.transaction_count, 0);
957         init_waitqueue_head(&xs_state.transaction_wq);
958
959         /* Initialize the shared memory rings to talk to xenstored */
960         err = xb_init_comms();
961         if (err)
962                 return err;
963
964         task = kthread_run(xenwatch_thread, NULL, "xenwatch");
965         if (IS_ERR(task))
966                 return PTR_ERR(task);
967         xenwatch_pid = task->pid;
968
969         task = kthread_run(xenbus_thread, NULL, "xenbus");
970         if (IS_ERR(task))
971                 return PTR_ERR(task);
972
973         /* shutdown watches for kexec boot */
974         xs_reset_watches();
975
976         return 0;
977 }