ACPI / thermal: Remove create_workqueue()
[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 (IS_ERR(ret))
253                 return ret;
254
255         if ((msg->type == XS_TRANSACTION_END) ||
256             ((req_msg.type == XS_TRANSACTION_START) &&
257              (msg->type == XS_ERROR)))
258                 transaction_end();
259
260         return ret;
261 }
262 EXPORT_SYMBOL(xenbus_dev_request_and_reply);
263
264 /* Send message to xs, get kmalloc'ed reply.  ERR_PTR() on error. */
265 static void *xs_talkv(struct xenbus_transaction t,
266                       enum xsd_sockmsg_type type,
267                       const struct kvec *iovec,
268                       unsigned int num_vecs,
269                       unsigned int *len)
270 {
271         struct xsd_sockmsg msg;
272         void *ret = NULL;
273         unsigned int i;
274         int err;
275
276         msg.tx_id = t.id;
277         msg.req_id = 0;
278         msg.type = type;
279         msg.len = 0;
280         for (i = 0; i < num_vecs; i++)
281                 msg.len += iovec[i].iov_len;
282
283         mutex_lock(&xs_state.request_mutex);
284
285         err = xb_write(&msg, sizeof(msg));
286         if (err) {
287                 mutex_unlock(&xs_state.request_mutex);
288                 return ERR_PTR(err);
289         }
290
291         for (i = 0; i < num_vecs; i++) {
292                 err = xb_write(iovec[i].iov_base, iovec[i].iov_len);
293                 if (err) {
294                         mutex_unlock(&xs_state.request_mutex);
295                         return ERR_PTR(err);
296                 }
297         }
298
299         ret = read_reply(&msg.type, len);
300
301         mutex_unlock(&xs_state.request_mutex);
302
303         if (IS_ERR(ret))
304                 return ret;
305
306         if (msg.type == XS_ERROR) {
307                 err = get_error(ret);
308                 kfree(ret);
309                 return ERR_PTR(-err);
310         }
311
312         if (msg.type != type) {
313                 pr_warn_ratelimited("unexpected type [%d], expected [%d]\n",
314                                     msg.type, type);
315                 kfree(ret);
316                 return ERR_PTR(-EINVAL);
317         }
318         return ret;
319 }
320
321 /* Simplified version of xs_talkv: single message. */
322 static void *xs_single(struct xenbus_transaction t,
323                        enum xsd_sockmsg_type type,
324                        const char *string,
325                        unsigned int *len)
326 {
327         struct kvec iovec;
328
329         iovec.iov_base = (void *)string;
330         iovec.iov_len = strlen(string) + 1;
331         return xs_talkv(t, type, &iovec, 1, len);
332 }
333
334 /* Many commands only need an ack, don't care what it says. */
335 static int xs_error(char *reply)
336 {
337         if (IS_ERR(reply))
338                 return PTR_ERR(reply);
339         kfree(reply);
340         return 0;
341 }
342
343 static unsigned int count_strings(const char *strings, unsigned int len)
344 {
345         unsigned int num;
346         const char *p;
347
348         for (p = strings, num = 0; p < strings + len; p += strlen(p) + 1)
349                 num++;
350
351         return num;
352 }
353
354 /* Return the path to dir with /name appended. Buffer must be kfree()'ed. */
355 static char *join(const char *dir, const char *name)
356 {
357         char *buffer;
358
359         if (strlen(name) == 0)
360                 buffer = kasprintf(GFP_NOIO | __GFP_HIGH, "%s", dir);
361         else
362                 buffer = kasprintf(GFP_NOIO | __GFP_HIGH, "%s/%s", dir, name);
363         return (!buffer) ? ERR_PTR(-ENOMEM) : buffer;
364 }
365
366 static char **split(char *strings, unsigned int len, unsigned int *num)
367 {
368         char *p, **ret;
369
370         /* Count the strings. */
371         *num = count_strings(strings, len);
372
373         /* Transfer to one big alloc for easy freeing. */
374         ret = kmalloc(*num * sizeof(char *) + len, GFP_NOIO | __GFP_HIGH);
375         if (!ret) {
376                 kfree(strings);
377                 return ERR_PTR(-ENOMEM);
378         }
379         memcpy(&ret[*num], strings, len);
380         kfree(strings);
381
382         strings = (char *)&ret[*num];
383         for (p = strings, *num = 0; p < strings + len; p += strlen(p) + 1)
384                 ret[(*num)++] = p;
385
386         return ret;
387 }
388
389 char **xenbus_directory(struct xenbus_transaction t,
390                         const char *dir, const char *node, unsigned int *num)
391 {
392         char *strings, *path;
393         unsigned int len;
394
395         path = join(dir, node);
396         if (IS_ERR(path))
397                 return (char **)path;
398
399         strings = xs_single(t, XS_DIRECTORY, path, &len);
400         kfree(path);
401         if (IS_ERR(strings))
402                 return (char **)strings;
403
404         return split(strings, len, num);
405 }
406 EXPORT_SYMBOL_GPL(xenbus_directory);
407
408 /* Check if a path exists. Return 1 if it does. */
409 int xenbus_exists(struct xenbus_transaction t,
410                   const char *dir, const char *node)
411 {
412         char **d;
413         int dir_n;
414
415         d = xenbus_directory(t, dir, node, &dir_n);
416         if (IS_ERR(d))
417                 return 0;
418         kfree(d);
419         return 1;
420 }
421 EXPORT_SYMBOL_GPL(xenbus_exists);
422
423 /* Get the value of a single file.
424  * Returns a kmalloced value: call free() on it after use.
425  * len indicates length in bytes.
426  */
427 void *xenbus_read(struct xenbus_transaction t,
428                   const char *dir, const char *node, unsigned int *len)
429 {
430         char *path;
431         void *ret;
432
433         path = join(dir, node);
434         if (IS_ERR(path))
435                 return (void *)path;
436
437         ret = xs_single(t, XS_READ, path, len);
438         kfree(path);
439         return ret;
440 }
441 EXPORT_SYMBOL_GPL(xenbus_read);
442
443 /* Write the value of a single file.
444  * Returns -err on failure.
445  */
446 int xenbus_write(struct xenbus_transaction t,
447                  const char *dir, const char *node, const char *string)
448 {
449         const char *path;
450         struct kvec iovec[2];
451         int ret;
452
453         path = join(dir, node);
454         if (IS_ERR(path))
455                 return PTR_ERR(path);
456
457         iovec[0].iov_base = (void *)path;
458         iovec[0].iov_len = strlen(path) + 1;
459         iovec[1].iov_base = (void *)string;
460         iovec[1].iov_len = strlen(string);
461
462         ret = xs_error(xs_talkv(t, XS_WRITE, iovec, ARRAY_SIZE(iovec), NULL));
463         kfree(path);
464         return ret;
465 }
466 EXPORT_SYMBOL_GPL(xenbus_write);
467
468 /* Create a new directory. */
469 int xenbus_mkdir(struct xenbus_transaction t,
470                  const char *dir, const char *node)
471 {
472         char *path;
473         int ret;
474
475         path = join(dir, node);
476         if (IS_ERR(path))
477                 return PTR_ERR(path);
478
479         ret = xs_error(xs_single(t, XS_MKDIR, path, NULL));
480         kfree(path);
481         return ret;
482 }
483 EXPORT_SYMBOL_GPL(xenbus_mkdir);
484
485 /* Destroy a file or directory (directories must be empty). */
486 int xenbus_rm(struct xenbus_transaction t, const char *dir, const char *node)
487 {
488         char *path;
489         int ret;
490
491         path = join(dir, node);
492         if (IS_ERR(path))
493                 return PTR_ERR(path);
494
495         ret = xs_error(xs_single(t, XS_RM, path, NULL));
496         kfree(path);
497         return ret;
498 }
499 EXPORT_SYMBOL_GPL(xenbus_rm);
500
501 /* Start a transaction: changes by others will not be seen during this
502  * transaction, and changes will not be visible to others until end.
503  */
504 int xenbus_transaction_start(struct xenbus_transaction *t)
505 {
506         char *id_str;
507
508         transaction_start();
509
510         id_str = xs_single(XBT_NIL, XS_TRANSACTION_START, "", NULL);
511         if (IS_ERR(id_str)) {
512                 transaction_end();
513                 return PTR_ERR(id_str);
514         }
515
516         t->id = simple_strtoul(id_str, NULL, 0);
517         kfree(id_str);
518         return 0;
519 }
520 EXPORT_SYMBOL_GPL(xenbus_transaction_start);
521
522 /* End a transaction.
523  * If abandon is true, transaction is discarded instead of committed.
524  */
525 int xenbus_transaction_end(struct xenbus_transaction t, int abort)
526 {
527         char abortstr[2];
528         int err;
529
530         if (abort)
531                 strcpy(abortstr, "F");
532         else
533                 strcpy(abortstr, "T");
534
535         err = xs_error(xs_single(t, XS_TRANSACTION_END, abortstr, NULL));
536
537         transaction_end();
538
539         return err;
540 }
541 EXPORT_SYMBOL_GPL(xenbus_transaction_end);
542
543 /* Single read and scanf: returns -errno or num scanned. */
544 int xenbus_scanf(struct xenbus_transaction t,
545                  const char *dir, const char *node, const char *fmt, ...)
546 {
547         va_list ap;
548         int ret;
549         char *val;
550
551         val = xenbus_read(t, dir, node, NULL);
552         if (IS_ERR(val))
553                 return PTR_ERR(val);
554
555         va_start(ap, fmt);
556         ret = vsscanf(val, fmt, ap);
557         va_end(ap);
558         kfree(val);
559         /* Distinctive errno. */
560         if (ret == 0)
561                 return -ERANGE;
562         return ret;
563 }
564 EXPORT_SYMBOL_GPL(xenbus_scanf);
565
566 /* Single printf and write: returns -errno or 0. */
567 int xenbus_printf(struct xenbus_transaction t,
568                   const char *dir, const char *node, const char *fmt, ...)
569 {
570         va_list ap;
571         int ret;
572         char *buf;
573
574         va_start(ap, fmt);
575         buf = kvasprintf(GFP_NOIO | __GFP_HIGH, fmt, ap);
576         va_end(ap);
577
578         if (!buf)
579                 return -ENOMEM;
580
581         ret = xenbus_write(t, dir, node, buf);
582
583         kfree(buf);
584
585         return ret;
586 }
587 EXPORT_SYMBOL_GPL(xenbus_printf);
588
589 /* Takes tuples of names, scanf-style args, and void **, NULL terminated. */
590 int xenbus_gather(struct xenbus_transaction t, const char *dir, ...)
591 {
592         va_list ap;
593         const char *name;
594         int ret = 0;
595
596         va_start(ap, dir);
597         while (ret == 0 && (name = va_arg(ap, char *)) != NULL) {
598                 const char *fmt = va_arg(ap, char *);
599                 void *result = va_arg(ap, void *);
600                 char *p;
601
602                 p = xenbus_read(t, dir, name, NULL);
603                 if (IS_ERR(p)) {
604                         ret = PTR_ERR(p);
605                         break;
606                 }
607                 if (fmt) {
608                         if (sscanf(p, fmt, result) == 0)
609                                 ret = -EINVAL;
610                         kfree(p);
611                 } else
612                         *(char **)result = p;
613         }
614         va_end(ap);
615         return ret;
616 }
617 EXPORT_SYMBOL_GPL(xenbus_gather);
618
619 static int xs_watch(const char *path, const char *token)
620 {
621         struct kvec iov[2];
622
623         iov[0].iov_base = (void *)path;
624         iov[0].iov_len = strlen(path) + 1;
625         iov[1].iov_base = (void *)token;
626         iov[1].iov_len = strlen(token) + 1;
627
628         return xs_error(xs_talkv(XBT_NIL, XS_WATCH, iov,
629                                  ARRAY_SIZE(iov), NULL));
630 }
631
632 static int xs_unwatch(const char *path, const char *token)
633 {
634         struct kvec iov[2];
635
636         iov[0].iov_base = (char *)path;
637         iov[0].iov_len = strlen(path) + 1;
638         iov[1].iov_base = (char *)token;
639         iov[1].iov_len = strlen(token) + 1;
640
641         return xs_error(xs_talkv(XBT_NIL, XS_UNWATCH, iov,
642                                  ARRAY_SIZE(iov), NULL));
643 }
644
645 static struct xenbus_watch *find_watch(const char *token)
646 {
647         struct xenbus_watch *i, *cmp;
648
649         cmp = (void *)simple_strtoul(token, NULL, 16);
650
651         list_for_each_entry(i, &watches, list)
652                 if (i == cmp)
653                         return i;
654
655         return NULL;
656 }
657 /*
658  * Certain older XenBus toolstack cannot handle reading values that are
659  * not populated. Some Xen 3.4 installation are incapable of doing this
660  * so if we are running on anything older than 4 do not attempt to read
661  * control/platform-feature-xs_reset_watches.
662  */
663 static bool xen_strict_xenbus_quirk(void)
664 {
665 #ifdef CONFIG_X86
666         uint32_t eax, ebx, ecx, edx, base;
667
668         base = xen_cpuid_base();
669         cpuid(base + 1, &eax, &ebx, &ecx, &edx);
670
671         if ((eax >> 16) < 4)
672                 return true;
673 #endif
674         return false;
675
676 }
677 static void xs_reset_watches(void)
678 {
679         int err, supported = 0;
680
681         if (!xen_hvm_domain() || xen_initial_domain())
682                 return;
683
684         if (xen_strict_xenbus_quirk())
685                 return;
686
687         err = xenbus_scanf(XBT_NIL, "control",
688                         "platform-feature-xs_reset_watches", "%d", &supported);
689         if (err != 1 || !supported)
690                 return;
691
692         err = xs_error(xs_single(XBT_NIL, XS_RESET_WATCHES, "", NULL));
693         if (err && err != -EEXIST)
694                 pr_warn("xs_reset_watches failed: %d\n", err);
695 }
696
697 /* Register callback to watch this node. */
698 int register_xenbus_watch(struct xenbus_watch *watch)
699 {
700         /* Pointer in ascii is the token. */
701         char token[sizeof(watch) * 2 + 1];
702         int err;
703
704         sprintf(token, "%lX", (long)watch);
705
706         down_read(&xs_state.watch_mutex);
707
708         spin_lock(&watches_lock);
709         BUG_ON(find_watch(token));
710         list_add(&watch->list, &watches);
711         spin_unlock(&watches_lock);
712
713         err = xs_watch(watch->node, token);
714
715         if (err) {
716                 spin_lock(&watches_lock);
717                 list_del(&watch->list);
718                 spin_unlock(&watches_lock);
719         }
720
721         up_read(&xs_state.watch_mutex);
722
723         return err;
724 }
725 EXPORT_SYMBOL_GPL(register_xenbus_watch);
726
727 void unregister_xenbus_watch(struct xenbus_watch *watch)
728 {
729         struct xs_stored_msg *msg, *tmp;
730         char token[sizeof(watch) * 2 + 1];
731         int err;
732
733         sprintf(token, "%lX", (long)watch);
734
735         down_read(&xs_state.watch_mutex);
736
737         spin_lock(&watches_lock);
738         BUG_ON(!find_watch(token));
739         list_del(&watch->list);
740         spin_unlock(&watches_lock);
741
742         err = xs_unwatch(watch->node, token);
743         if (err)
744                 pr_warn("Failed to release watch %s: %i\n", watch->node, err);
745
746         up_read(&xs_state.watch_mutex);
747
748         /* Make sure there are no callbacks running currently (unless
749            its us) */
750         if (current->pid != xenwatch_pid)
751                 mutex_lock(&xenwatch_mutex);
752
753         /* Cancel pending watch events. */
754         spin_lock(&watch_events_lock);
755         list_for_each_entry_safe(msg, tmp, &watch_events, list) {
756                 if (msg->u.watch.handle != watch)
757                         continue;
758                 list_del(&msg->list);
759                 kfree(msg->u.watch.vec);
760                 kfree(msg);
761         }
762         spin_unlock(&watch_events_lock);
763
764         if (current->pid != xenwatch_pid)
765                 mutex_unlock(&xenwatch_mutex);
766 }
767 EXPORT_SYMBOL_GPL(unregister_xenbus_watch);
768
769 void xs_suspend(void)
770 {
771         transaction_suspend();
772         down_write(&xs_state.watch_mutex);
773         mutex_lock(&xs_state.request_mutex);
774         mutex_lock(&xs_state.response_mutex);
775 }
776
777 void xs_resume(void)
778 {
779         struct xenbus_watch *watch;
780         char token[sizeof(watch) * 2 + 1];
781
782         xb_init_comms();
783
784         mutex_unlock(&xs_state.response_mutex);
785         mutex_unlock(&xs_state.request_mutex);
786         transaction_resume();
787
788         /* No need for watches_lock: the watch_mutex is sufficient. */
789         list_for_each_entry(watch, &watches, list) {
790                 sprintf(token, "%lX", (long)watch);
791                 xs_watch(watch->node, token);
792         }
793
794         up_write(&xs_state.watch_mutex);
795 }
796
797 void xs_suspend_cancel(void)
798 {
799         mutex_unlock(&xs_state.response_mutex);
800         mutex_unlock(&xs_state.request_mutex);
801         up_write(&xs_state.watch_mutex);
802         mutex_unlock(&xs_state.transaction_mutex);
803 }
804
805 static int xenwatch_thread(void *unused)
806 {
807         struct list_head *ent;
808         struct xs_stored_msg *msg;
809
810         for (;;) {
811                 wait_event_interruptible(watch_events_waitq,
812                                          !list_empty(&watch_events));
813
814                 if (kthread_should_stop())
815                         break;
816
817                 mutex_lock(&xenwatch_mutex);
818
819                 spin_lock(&watch_events_lock);
820                 ent = watch_events.next;
821                 if (ent != &watch_events)
822                         list_del(ent);
823                 spin_unlock(&watch_events_lock);
824
825                 if (ent != &watch_events) {
826                         msg = list_entry(ent, struct xs_stored_msg, list);
827                         msg->u.watch.handle->callback(
828                                 msg->u.watch.handle,
829                                 (const char **)msg->u.watch.vec,
830                                 msg->u.watch.vec_size);
831                         kfree(msg->u.watch.vec);
832                         kfree(msg);
833                 }
834
835                 mutex_unlock(&xenwatch_mutex);
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         for (;;) {
936                 err = process_msg();
937                 if (err)
938                         pr_warn("error %d while reading message\n", err);
939                 if (kthread_should_stop())
940                         break;
941         }
942
943         return 0;
944 }
945
946 int xs_init(void)
947 {
948         int err;
949         struct task_struct *task;
950
951         INIT_LIST_HEAD(&xs_state.reply_list);
952         spin_lock_init(&xs_state.reply_lock);
953         init_waitqueue_head(&xs_state.reply_waitq);
954
955         mutex_init(&xs_state.request_mutex);
956         mutex_init(&xs_state.response_mutex);
957         mutex_init(&xs_state.transaction_mutex);
958         init_rwsem(&xs_state.watch_mutex);
959         atomic_set(&xs_state.transaction_count, 0);
960         init_waitqueue_head(&xs_state.transaction_wq);
961
962         /* Initialize the shared memory rings to talk to xenstored */
963         err = xb_init_comms();
964         if (err)
965                 return err;
966
967         task = kthread_run(xenwatch_thread, NULL, "xenwatch");
968         if (IS_ERR(task))
969                 return PTR_ERR(task);
970         xenwatch_pid = task->pid;
971
972         task = kthread_run(xenbus_thread, NULL, "xenbus");
973         if (IS_ERR(task))
974                 return PTR_ERR(task);
975
976         /* shutdown watches for kexec boot */
977         xs_reset_watches();
978
979         return 0;
980 }