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