]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/xen/xenstore/xenstore.c
Update subversion-1.8.0 -> 1.8.1. Update supporting
[FreeBSD/FreeBSD.git] / sys / xen / xenstore / xenstore.c
1 /******************************************************************************
2  * xenstore.c
3  *
4  * Low-level kernel interface to the XenStore.
5  *
6  * Copyright (C) 2005 Rusty Russell, IBM Corporation
7  * Copyright (C) 2009,2010 Spectra Logic Corporation
8  *
9  * This file may be distributed separately from the Linux kernel, or
10  * incorporated into other software packages, subject to the following license:
11  *
12  * Permission is hereby granted, free of charge, to any person obtaining a copy
13  * of this source file (the "Software"), to deal in the Software without
14  * restriction, including without limitation the rights to use, copy, modify,
15  * merge, publish, distribute, sublicense, and/or sell copies of the Software,
16  * and to permit persons to whom the Software is furnished to do so, subject to
17  * the following conditions:
18  *
19  * The above copyright notice and this permission notice shall be included in
20  * all copies or substantial portions of the Software.
21  *
22  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
28  * IN THE SOFTWARE.
29  */
30
31
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34
35 #include <sys/param.h>
36 #include <sys/bus.h>
37 #include <sys/kernel.h>
38 #include <sys/lock.h>
39 #include <sys/module.h>
40 #include <sys/mutex.h>
41 #include <sys/sx.h>
42 #include <sys/syslog.h>
43 #include <sys/malloc.h>
44 #include <sys/systm.h>
45 #include <sys/proc.h>
46 #include <sys/kthread.h>
47 #include <sys/sbuf.h>
48 #include <sys/sysctl.h>
49 #include <sys/uio.h>
50 #include <sys/unistd.h>
51
52 #include <machine/xen/xen-os.h>
53 #include <machine/stdarg.h>
54
55 #include <xen/evtchn.h>
56 #include <xen/gnttab.h>
57 #include <xen/hypervisor.h>
58 #include <xen/xen_intr.h>
59
60 #include <xen/interface/hvm/params.h>
61 #include <xen/hvm.h>
62
63 #include <xen/xenstore/xenstorevar.h>
64 #include <xen/xenstore/xenstore_internal.h>
65
66 #include <vm/vm.h>
67 #include <vm/pmap.h>
68
69 /**
70  * \file xenstore.c
71  * \brief XenStore interface
72  *
73  * The XenStore interface is a simple storage system that is a means of
74  * communicating state and configuration data between the Xen Domain 0
75  * and the various guest domains.  All configuration data other than
76  * a small amount of essential information required during the early
77  * boot process of launching a Xen aware guest, is managed using the
78  * XenStore.
79  *
80  * The XenStore is ASCII string based, and has a structure and semantics
81  * similar to a filesystem.  There are files and directories, the directories
82  * able to contain files or other directories.  The depth of the hierachy
83  * is only limited by the XenStore's maximum path length.
84  *
85  * The communication channel between the XenStore service and other
86  * domains is via two, guest specific, ring buffers in a shared memory
87  * area.  One ring buffer is used for communicating in each direction.
88  * The grant table references for this shared memory are given to the
89  * guest either via the xen_start_info structure for a fully para-
90  * virtualized guest, or via HVM hypercalls for a hardware virtualized
91  * guest.
92  *
93  * The XenStore communication relies on an event channel and thus
94  * interrupts.  For this reason, the attachment of the XenStore
95  * relies on an interrupt driven configuration hook to hold off
96  * boot processing until communication with the XenStore service
97  * can be established.
98  *
99  * Several Xen services depend on the XenStore, most notably the
100  * XenBus used to discover and manage Xen devices.  These services
101  * are implemented as NewBus child attachments to a bus exported
102  * by this XenStore driver.
103  */
104
105 static struct xs_watch *find_watch(const char *token);
106
107 MALLOC_DEFINE(M_XENSTORE, "xenstore", "XenStore data and results");
108
109 /**
110  * Pointer to shared memory communication structures allowing us
111  * to communicate with the XenStore service.
112  *
113  * When operating in full PV mode, this pointer is set early in kernel
114  * startup from within xen_machdep.c.  In HVM mode, we use hypercalls
115  * to get the guest frame number for the shared page and then map it
116  * into kva.  See xs_init() for details.
117  */
118 struct xenstore_domain_interface *xen_store;
119
120 /*-------------------------- Private Data Structures ------------------------*/
121
122 /**
123  * Structure capturing messages received from the XenStore service.
124  */
125 struct xs_stored_msg {
126         TAILQ_ENTRY(xs_stored_msg) list;
127
128         struct xsd_sockmsg hdr;
129
130         union {
131                 /* Queued replies. */
132                 struct {
133                         char *body;
134                 } reply;
135
136                 /* Queued watch events. */
137                 struct {
138                         struct xs_watch *handle;
139                         const char **vec;
140                         u_int vec_size;
141                 } watch;
142         } u;
143 };
144 TAILQ_HEAD(xs_stored_msg_list, xs_stored_msg);
145
146 /**
147  * Container for all XenStore related state.
148  */
149 struct xs_softc {
150         /** Newbus device for the XenStore. */
151         device_t xs_dev;
152
153         /**
154          * Lock serializing access to ring producer/consumer
155          * indexes.  Use of this lock guarantees that wakeups
156          * of blocking readers/writers are not missed due to
157          * races with the XenStore service.
158          */
159         struct mtx ring_lock;
160
161         /*
162          * Mutex used to insure exclusive access to the outgoing
163          * communication ring.  We use a lock type that can be
164          * held while sleeping so that xs_write() can block waiting
165          * for space in the ring to free up, without allowing another
166          * writer to come in and corrupt a partial message write.
167          */
168         struct sx request_mutex;
169
170         /**
171          * A list of replies to our requests.
172          *
173          * The reply list is filled by xs_rcv_thread().  It
174          * is consumed by the context that issued the request
175          * to which a reply is made.  The requester blocks in
176          * xs_read_reply().
177          *
178          * /note Only one requesting context can be active at a time.
179          *       This is guaranteed by the request_mutex and insures
180          *       that the requester sees replies matching the order
181          *       of its requests.
182          */
183         struct xs_stored_msg_list reply_list;
184
185         /** Lock protecting the reply list. */
186         struct mtx reply_lock;
187
188         /**
189          * List of registered watches.
190          */
191         struct xs_watch_list  registered_watches;
192
193         /** Lock protecting the registered watches list. */
194         struct mtx registered_watches_lock;
195
196         /**
197          * List of pending watch callback events.
198          */
199         struct xs_stored_msg_list watch_events;
200
201         /** Lock protecting the watch calback list. */
202         struct mtx watch_events_lock;
203
204         /**
205          * Sleepable lock used to prevent VM suspension while a
206          * xenstore transaction is outstanding.
207          *
208          * Each active transaction holds a shared lock on the
209          * suspend mutex.  Our suspend method blocks waiting
210          * to acquire an exclusive lock.  This guarantees that
211          * suspend processing will only proceed once all active
212          * transactions have been retired.
213          */
214         struct sx suspend_mutex;
215
216         /**
217          * The processid of the xenwatch thread.
218          */
219         pid_t xenwatch_pid;
220
221         /**
222          * Sleepable mutex used to gate the execution of XenStore
223          * watch event callbacks.
224          *
225          * xenwatch_thread holds an exclusive lock on this mutex
226          * while delivering event callbacks, and xenstore_unregister_watch()
227          * uses an exclusive lock of this mutex to guarantee that no
228          * callbacks of the just unregistered watch are pending
229          * before returning to its caller.
230          */
231         struct sx xenwatch_mutex;
232
233 #ifdef XENHVM
234         /**
235          * The HVM guest pseudo-physical frame number.  This is Xen's mapping
236          * of the true machine frame number into our "physical address space".
237          */
238         unsigned long gpfn;
239 #endif
240
241         /**
242          * The event channel for communicating with the
243          * XenStore service.
244          */
245         int evtchn;
246
247         /** Interrupt number for our event channel. */
248         u_int irq;
249
250         /**
251          * Interrupt driven config hook allowing us to defer
252          * attaching children until interrupts (and thus communication
253          * with the XenStore service) are available.
254          */
255         struct intr_config_hook xs_attachcb;
256 };
257
258 /*-------------------------------- Global Data ------------------------------*/
259 static struct xs_softc xs;
260
261 /*------------------------- Private Utility Functions -----------------------*/
262
263 /**
264  * Count and optionally record pointers to a number of NUL terminated
265  * strings in a buffer.
266  *
267  * \param strings  A pointer to a contiguous buffer of NUL terminated strings.
268  * \param dest     An array to store pointers to each string found in strings.
269  * \param len      The length of the buffer pointed to by strings.
270  *
271  * \return  A count of the number of strings found.
272  */
273 static u_int
274 extract_strings(const char *strings, const char **dest, u_int len)
275 {
276         u_int num;
277         const char *p;
278
279         for (p = strings, num = 0; p < strings + len; p += strlen(p) + 1) {
280                 if (dest != NULL)
281                         *dest++ = p;
282                 num++;
283         }
284
285         return (num);
286 }
287
288 /**
289  * Convert a contiguous buffer containing a series of NUL terminated
290  * strings into an array of pointers to strings.
291  *
292  * The returned pointer references the array of string pointers which
293  * is followed by the storage for the string data.  It is the client's
294  * responsibility to free this storage.
295  *
296  * The storage addressed by strings is free'd prior to split returning.
297  *
298  * \param strings  A pointer to a contiguous buffer of NUL terminated strings.
299  * \param len      The length of the buffer pointed to by strings.
300  * \param num      The number of strings found and returned in the strings
301  *                 array.
302  *
303  * \return  An array of pointers to the strings found in the input buffer.
304  */
305 static const char **
306 split(char *strings, u_int len, u_int *num)
307 {
308         const char **ret;
309
310         /* Protect against unterminated buffers. */
311         if (len > 0)
312                 strings[len - 1] = '\0';
313
314         /* Count the strings. */
315         *num = extract_strings(strings, /*dest*/NULL, len);
316
317         /* Transfer to one big alloc for easy freeing by the caller. */
318         ret = malloc(*num * sizeof(char *) + len, M_XENSTORE, M_WAITOK);
319         memcpy(&ret[*num], strings, len);
320         free(strings, M_XENSTORE);
321
322         /* Extract pointers to newly allocated array. */
323         strings = (char *)&ret[*num];
324         (void)extract_strings(strings, /*dest*/ret, len);
325
326         return (ret);
327 }
328
329 /*------------------------- Public Utility Functions -------------------------*/
330 /*------- API comments for these methods can be found in xenstorevar.h -------*/
331 struct sbuf *
332 xs_join(const char *dir, const char *name)
333 {
334         struct sbuf *sb;
335
336         sb = sbuf_new_auto();
337         sbuf_cat(sb, dir);
338         if (name[0] != '\0') {
339                 sbuf_putc(sb, '/');
340                 sbuf_cat(sb, name);
341         }
342         sbuf_finish(sb);
343
344         return (sb);
345 }
346
347 /*-------------------- Low Level Communication Management --------------------*/
348 /**
349  * Interrupt handler for the XenStore event channel.
350  *
351  * XenStore reads and writes block on "xen_store" for buffer
352  * space.  Wakeup any blocking operations when the XenStore
353  * service has modified the queues.
354  */
355 static void
356 xs_intr(void * arg __unused /*__attribute__((unused))*/)
357 {
358
359         /*
360          * Hold ring lock across wakeup so that clients
361          * cannot miss a wakeup.
362          */
363         mtx_lock(&xs.ring_lock);
364         wakeup(xen_store);
365         mtx_unlock(&xs.ring_lock);
366 }
367
368 /**
369  * Verify that the indexes for a ring are valid.
370  *
371  * The difference between the producer and consumer cannot
372  * exceed the size of the ring.
373  *
374  * \param cons  The consumer index for the ring to test.
375  * \param prod  The producer index for the ring to test.
376  *
377  * \retval 1  If indexes are in range.
378  * \retval 0  If the indexes are out of range.
379  */
380 static int
381 xs_check_indexes(XENSTORE_RING_IDX cons, XENSTORE_RING_IDX prod)
382 {
383
384         return ((prod - cons) <= XENSTORE_RING_SIZE);
385 }
386
387 /**
388  * Return a pointer to, and the length of, the contiguous
389  * free region available for output in a ring buffer.
390  *
391  * \param cons  The consumer index for the ring.
392  * \param prod  The producer index for the ring.
393  * \param buf   The base address of the ring's storage.
394  * \param len   The amount of contiguous storage available.
395  *
396  * \return  A pointer to the start location of the free region.
397  */
398 static void *
399 xs_get_output_chunk(XENSTORE_RING_IDX cons, XENSTORE_RING_IDX prod,
400     char *buf, uint32_t *len)
401 {
402
403         *len = XENSTORE_RING_SIZE - MASK_XENSTORE_IDX(prod);
404         if ((XENSTORE_RING_SIZE - (prod - cons)) < *len)
405                 *len = XENSTORE_RING_SIZE - (prod - cons);
406         return (buf + MASK_XENSTORE_IDX(prod));
407 }
408
409 /**
410  * Return a pointer to, and the length of, the contiguous
411  * data available to read from a ring buffer.
412  *
413  * \param cons  The consumer index for the ring.
414  * \param prod  The producer index for the ring.
415  * \param buf   The base address of the ring's storage.
416  * \param len   The amount of contiguous data available to read.
417  *
418  * \return  A pointer to the start location of the available data.
419  */
420 static const void *
421 xs_get_input_chunk(XENSTORE_RING_IDX cons, XENSTORE_RING_IDX prod,
422     const char *buf, uint32_t *len)
423 {
424
425         *len = XENSTORE_RING_SIZE - MASK_XENSTORE_IDX(cons);
426         if ((prod - cons) < *len)
427                 *len = prod - cons;
428         return (buf + MASK_XENSTORE_IDX(cons));
429 }
430
431 /**
432  * Transmit data to the XenStore service.
433  *
434  * \param tdata  A pointer to the contiguous data to send.
435  * \param len    The amount of data to send.
436  *
437  * \return  On success 0, otherwise an errno value indicating the
438  *          cause of failure.
439  *
440  * \invariant  Called from thread context.
441  * \invariant  The buffer pointed to by tdata is at least len bytes
442  *             in length.
443  * \invariant  xs.request_mutex exclusively locked.
444  */
445 static int
446 xs_write_store(const void *tdata, unsigned len)
447 {
448         XENSTORE_RING_IDX cons, prod;
449         const char *data = (const char *)tdata;
450         int error;
451
452         sx_assert(&xs.request_mutex, SX_XLOCKED);
453         while (len != 0) {
454                 void *dst;
455                 u_int avail;
456
457                 /* Hold lock so we can't miss wakeups should we block. */
458                 mtx_lock(&xs.ring_lock);
459                 cons = xen_store->req_cons;
460                 prod = xen_store->req_prod;
461                 if ((prod - cons) == XENSTORE_RING_SIZE) {
462                         /*
463                          * Output ring is full. Wait for a ring event.
464                          *
465                          * Note that the events from both queues
466                          * are combined, so being woken does not
467                          * guarantee that data exist in the read
468                          * ring.
469                          *
470                          * To simplify error recovery and the retry,
471                          * we specify PDROP so our lock is *not* held
472                          * when msleep returns.
473                          */
474                         error = msleep(xen_store, &xs.ring_lock, PCATCH|PDROP,
475                              "xbwrite", /*timeout*/0);
476                         if (error && error != EWOULDBLOCK)
477                                 return (error);
478
479                         /* Try again. */
480                         continue;
481                 }
482                 mtx_unlock(&xs.ring_lock);
483
484                 /* Verify queue sanity. */
485                 if (!xs_check_indexes(cons, prod)) {
486                         xen_store->req_cons = xen_store->req_prod = 0;
487                         return (EIO);
488                 }
489
490                 dst = xs_get_output_chunk(cons, prod, xen_store->req, &avail);
491                 if (avail > len)
492                         avail = len;
493
494                 memcpy(dst, data, avail);
495                 data += avail;
496                 len -= avail;
497
498                 /*
499                  * The store to the producer index, which indicates
500                  * to the other side that new data has arrived, must
501                  * be visible only after our copy of the data into the
502                  * ring has completed.
503                  */
504                 wmb();
505                 xen_store->req_prod += avail;
506
507                 /*
508                  * notify_remote_via_evtchn implies mb(). The other side
509                  * will see the change to req_prod at the time of the
510                  * interrupt.
511                  */
512                 notify_remote_via_evtchn(xs.evtchn);
513         }
514
515         return (0);
516 }
517
518 /**
519  * Receive data from the XenStore service.
520  *
521  * \param tdata  A pointer to the contiguous buffer to receive the data.
522  * \param len    The amount of data to receive.
523  *
524  * \return  On success 0, otherwise an errno value indicating the
525  *          cause of failure.
526  *
527  * \invariant  Called from thread context.
528  * \invariant  The buffer pointed to by tdata is at least len bytes
529  *             in length.
530  *
531  * \note xs_read does not perform any internal locking to guarantee
532  *       serial access to the incoming ring buffer.  However, there
533  *       is only one context processing reads: xs_rcv_thread().
534  */
535 static int
536 xs_read_store(void *tdata, unsigned len)
537 {
538         XENSTORE_RING_IDX cons, prod;
539         char *data = (char *)tdata;
540         int error;
541
542         while (len != 0) {
543                 u_int avail;
544                 const char *src;
545
546                 /* Hold lock so we can't miss wakeups should we block. */
547                 mtx_lock(&xs.ring_lock);
548                 cons = xen_store->rsp_cons;
549                 prod = xen_store->rsp_prod;
550                 if (cons == prod) {
551                         /*
552                          * Nothing to read. Wait for a ring event.
553                          *
554                          * Note that the events from both queues
555                          * are combined, so being woken does not
556                          * guarantee that data exist in the read
557                          * ring.
558                          *
559                          * To simplify error recovery and the retry,
560                          * we specify PDROP so our lock is *not* held
561                          * when msleep returns.
562                          */
563                         error = msleep(xen_store, &xs.ring_lock, PCATCH|PDROP,
564                             "xbread", /*timeout*/0);
565                         if (error && error != EWOULDBLOCK)
566                                 return (error);
567                         continue;
568                 }
569                 mtx_unlock(&xs.ring_lock);
570
571                 /* Verify queue sanity. */
572                 if (!xs_check_indexes(cons, prod)) {
573                         xen_store->rsp_cons = xen_store->rsp_prod = 0;
574                         return (EIO);
575                 }
576
577                 src = xs_get_input_chunk(cons, prod, xen_store->rsp, &avail);
578                 if (avail > len)
579                         avail = len;
580
581                 /*
582                  * Insure the data we read is related to the indexes
583                  * we read above.
584                  */
585                 rmb();
586
587                 memcpy(data, src, avail);
588                 data += avail;
589                 len -= avail;
590
591                 /*
592                  * Insure that the producer of this ring does not see
593                  * the ring space as free until after we have copied it
594                  * out.
595                  */
596                 mb();
597                 xen_store->rsp_cons += avail;
598
599                 /*
600                  * notify_remote_via_evtchn implies mb(). The producer
601                  * will see the updated consumer index when the event
602                  * is delivered.
603                  */
604                 notify_remote_via_evtchn(xs.evtchn);
605         }
606
607         return (0);
608 }
609
610 /*----------------------- Received Message Processing ------------------------*/
611 /**
612  * Block reading the next message from the XenStore service and
613  * process the result.
614  *
615  * \param type  The returned type of the XenStore message received.
616  *
617  * \return  0 on success.  Otherwise an errno value indicating the
618  *          type of failure encountered.
619  */
620 static int
621 xs_process_msg(enum xsd_sockmsg_type *type)
622 {
623         struct xs_stored_msg *msg;
624         char *body;
625         int error;
626
627         msg = malloc(sizeof(*msg), M_XENSTORE, M_WAITOK);
628         error = xs_read_store(&msg->hdr, sizeof(msg->hdr));
629         if (error) {
630                 free(msg, M_XENSTORE);
631                 return (error);
632         }
633
634         body = malloc(msg->hdr.len + 1, M_XENSTORE, M_WAITOK);
635         error = xs_read_store(body, msg->hdr.len);
636         if (error) {
637                 free(body, M_XENSTORE);
638                 free(msg, M_XENSTORE);
639                 return (error);
640         }
641         body[msg->hdr.len] = '\0';
642
643         *type = msg->hdr.type;
644         if (msg->hdr.type == XS_WATCH_EVENT) {
645                 msg->u.watch.vec = split(body, msg->hdr.len,
646                     &msg->u.watch.vec_size);
647
648                 mtx_lock(&xs.registered_watches_lock);
649                 msg->u.watch.handle = find_watch(
650                     msg->u.watch.vec[XS_WATCH_TOKEN]);
651                 if (msg->u.watch.handle != NULL) {
652                         mtx_lock(&xs.watch_events_lock);
653                         TAILQ_INSERT_TAIL(&xs.watch_events, msg, list);
654                         wakeup(&xs.watch_events);
655                         mtx_unlock(&xs.watch_events_lock);
656                 } else {
657                         free(msg->u.watch.vec, M_XENSTORE);
658                         free(msg, M_XENSTORE);
659                 }
660                 mtx_unlock(&xs.registered_watches_lock);
661         } else {
662                 msg->u.reply.body = body;
663                 mtx_lock(&xs.reply_lock);
664                 TAILQ_INSERT_TAIL(&xs.reply_list, msg, list);
665                 wakeup(&xs.reply_list);
666                 mtx_unlock(&xs.reply_lock);
667         }
668
669         return (0);
670 }
671
672 /**
673  * Thread body of the XenStore receive thread.
674  *
675  * This thread blocks waiting for data from the XenStore service
676  * and processes and received messages.
677  */
678 static void
679 xs_rcv_thread(void *arg __unused)
680 {
681         int error;
682         enum xsd_sockmsg_type type;
683
684         for (;;) {
685                 error = xs_process_msg(&type);
686                 if (error)
687                         printf("XENSTORE error %d while reading message\n",
688                             error);
689         }
690 }
691
692 /*---------------- XenStore Message Request/Reply Processing -----------------*/
693 /**
694  * Filter invoked before transmitting any message to the XenStore service.
695  *
696  * The role of the filter may expand, but currently serves to manage
697  * the interactions of messages with transaction state.
698  *
699  * \param request_msg_type  The message type for the request.
700  */
701 static inline void
702 xs_request_filter(uint32_t request_msg_type)
703 {
704         if (request_msg_type == XS_TRANSACTION_START)
705                 sx_slock(&xs.suspend_mutex);
706 }
707
708 /**
709  * Filter invoked after transmitting any message to the XenStore service.
710  *
711  * The role of the filter may expand, but currently serves to manage
712  * the interactions of messages with transaction state.
713  *
714  * \param request_msg_type     The message type for the original request.
715  * \param reply_msg_type       The message type for any received reply.
716  * \param request_reply_error  The error status from the attempt to send
717  *                             the request or retrieve the reply.
718  */
719 static inline void
720 xs_reply_filter(uint32_t request_msg_type,
721     uint32_t reply_msg_type, int request_reply_error)
722 {
723         /*
724          * The count of transactions drops if we attempted
725          * to end a transaction (even if that attempt fails
726          * in error), we receive a transaction end acknowledgement,
727          * or if our attempt to begin a transaction fails.
728          */
729         if (request_msg_type == XS_TRANSACTION_END
730          || (request_reply_error == 0 && reply_msg_type == XS_TRANSACTION_END)
731          || (request_msg_type == XS_TRANSACTION_START
732           && (request_reply_error != 0 || reply_msg_type == XS_ERROR)))
733                 sx_sunlock(&xs.suspend_mutex);
734
735 }
736
737 #define xsd_error_count (sizeof(xsd_errors) / sizeof(xsd_errors[0]))
738
739 /**
740  * Convert a XenStore error string into an errno number.
741  *
742  * \param errorstring  The error string to convert.
743  *
744  * \return  The errno best matching the input string.
745  *
746  * \note Unknown error strings are converted to EINVAL.
747  */
748 static int
749 xs_get_error(const char *errorstring)
750 {
751         u_int i;
752
753         for (i = 0; i < xsd_error_count; i++) {
754                 if (!strcmp(errorstring, xsd_errors[i].errstring))
755                         return (xsd_errors[i].errnum);
756         }
757         log(LOG_WARNING, "XENSTORE xen store gave: unknown error %s",
758             errorstring);
759         return (EINVAL);
760 }
761
762 /**
763  * Block waiting for a reply to a message request.
764  *
765  * \param type    The returned type of the reply.
766  * \param len     The returned body length of the reply.
767  * \param result  The returned body of the reply.
768  *
769  * \return  0 on success.  Otherwise an errno indicating the
770  *          cause of failure.
771  */
772 static int
773 xs_read_reply(enum xsd_sockmsg_type *type, u_int *len, void **result)
774 {
775         struct xs_stored_msg *msg;
776         char *body;
777         int error;
778
779         mtx_lock(&xs.reply_lock);
780         while (TAILQ_EMPTY(&xs.reply_list)) {
781                 error = mtx_sleep(&xs.reply_list, &xs.reply_lock,
782                     PCATCH, "xswait", hz/10);
783                 if (error && error != EWOULDBLOCK) {
784                         mtx_unlock(&xs.reply_lock);
785                         return (error);
786                 }
787         }
788         msg = TAILQ_FIRST(&xs.reply_list);
789         TAILQ_REMOVE(&xs.reply_list, msg, list);
790         mtx_unlock(&xs.reply_lock);
791
792         *type = msg->hdr.type;
793         if (len)
794                 *len = msg->hdr.len;
795         body = msg->u.reply.body;
796
797         free(msg, M_XENSTORE);
798         *result = body;
799         return (0);
800 }
801
802 /**
803  * Pass-thru interface for XenStore access by userland processes
804  * via the XenStore device.
805  *
806  * Reply type and length data are returned by overwriting these
807  * fields in the passed in request message.
808  *
809  * \param msg     A properly formatted message to transmit to
810  *                the XenStore service.
811  * \param result  The returned body of the reply.
812  *
813  * \return  0 on success.  Otherwise an errno indicating the cause
814  *          of failure.
815  *
816  * \note The returned result is provided in malloced storage and thus
817  *       must be free'd by the caller with 'free(result, M_XENSTORE);
818  */
819 int
820 xs_dev_request_and_reply(struct xsd_sockmsg *msg, void **result)
821 {
822         uint32_t request_type;
823         int error;
824
825         request_type = msg->type;
826         xs_request_filter(request_type);
827
828         sx_xlock(&xs.request_mutex);
829         if ((error = xs_write_store(msg, sizeof(*msg) + msg->len)) == 0)
830                 error = xs_read_reply(&msg->type, &msg->len, result);
831         sx_xunlock(&xs.request_mutex);
832
833         xs_reply_filter(request_type, msg->type, error);
834
835         return (error);
836 }
837
838 /**
839  * Send a message with an optionally muti-part body to the XenStore service.
840  *
841  * \param t              The transaction to use for this request.
842  * \param request_type   The type of message to send.
843  * \param iovec          Pointers to the body sections of the request.
844  * \param num_vecs       The number of body sections in the request.
845  * \param len            The returned length of the reply.
846  * \param result         The returned body of the reply.
847  *
848  * \return  0 on success.  Otherwise an errno indicating
849  *          the cause of failure.
850  *
851  * \note The returned result is provided in malloced storage and thus
852  *       must be free'd by the caller with 'free(*result, M_XENSTORE);
853  */
854 static int
855 xs_talkv(struct xs_transaction t, enum xsd_sockmsg_type request_type,
856     const struct iovec *iovec, u_int num_vecs, u_int *len, void **result)
857 {
858         struct xsd_sockmsg msg;
859         void *ret = NULL;
860         u_int i;
861         int error;
862
863         msg.tx_id = t.id;
864         msg.req_id = 0;
865         msg.type = request_type;
866         msg.len = 0;
867         for (i = 0; i < num_vecs; i++)
868                 msg.len += iovec[i].iov_len;
869
870         xs_request_filter(request_type);
871
872         sx_xlock(&xs.request_mutex);
873         error = xs_write_store(&msg, sizeof(msg));
874         if (error) {
875                 printf("xs_talkv failed %d\n", error);
876                 goto error_lock_held;
877         }
878
879         for (i = 0; i < num_vecs; i++) {
880                 error = xs_write_store(iovec[i].iov_base, iovec[i].iov_len);
881                 if (error) {
882                         printf("xs_talkv failed %d\n", error);
883                         goto error_lock_held;
884                 }
885         }
886
887         error = xs_read_reply(&msg.type, len, &ret);
888
889 error_lock_held:
890         sx_xunlock(&xs.request_mutex);
891         xs_reply_filter(request_type, msg.type, error);
892         if (error)
893                 return (error);
894
895         if (msg.type == XS_ERROR) {
896                 error = xs_get_error(ret);
897                 free(ret, M_XENSTORE);
898                 return (error);
899         }
900
901         /* Reply is either error or an echo of our request message type. */
902         KASSERT(msg.type == request_type, ("bad xenstore message type"));
903
904         if (result)
905                 *result = ret;
906         else
907                 free(ret, M_XENSTORE);
908
909         return (0);
910 }
911
912 /**
913  * Wrapper for xs_talkv allowing easy transmission of a message with
914  * a single, contiguous, message body.
915  *
916  * \param t              The transaction to use for this request.
917  * \param request_type   The type of message to send.
918  * \param body           The body of the request.
919  * \param len            The returned length of the reply.
920  * \param result         The returned body of the reply.
921  *
922  * \return  0 on success.  Otherwise an errno indicating
923  *          the cause of failure.
924  *
925  * \note The returned result is provided in malloced storage and thus
926  *       must be free'd by the caller with 'free(*result, M_XENSTORE);
927  */
928 static int
929 xs_single(struct xs_transaction t, enum xsd_sockmsg_type request_type,
930     const char *body, u_int *len, void **result)
931 {
932         struct iovec iovec;
933
934         iovec.iov_base = (void *)(uintptr_t)body;
935         iovec.iov_len = strlen(body) + 1;
936
937         return (xs_talkv(t, request_type, &iovec, 1, len, result));
938 }
939
940 /*------------------------- XenStore Watch Support ---------------------------*/
941 /**
942  * Transmit a watch request to the XenStore service.
943  *
944  * \param path    The path in the XenStore to watch.
945  * \param tocken  A unique identifier for this watch.
946  *
947  * \return  0 on success.  Otherwise an errno indicating the
948  *          cause of failure.
949  */
950 static int
951 xs_watch(const char *path, const char *token)
952 {
953         struct iovec iov[2];
954
955         iov[0].iov_base = (void *)(uintptr_t) path;
956         iov[0].iov_len = strlen(path) + 1;
957         iov[1].iov_base = (void *)(uintptr_t) token;
958         iov[1].iov_len = strlen(token) + 1;
959
960         return (xs_talkv(XST_NIL, XS_WATCH, iov, 2, NULL, NULL));
961 }
962
963 /**
964  * Transmit an uwatch request to the XenStore service.
965  *
966  * \param path    The path in the XenStore to watch.
967  * \param tocken  A unique identifier for this watch.
968  *
969  * \return  0 on success.  Otherwise an errno indicating the
970  *          cause of failure.
971  */
972 static int
973 xs_unwatch(const char *path, const char *token)
974 {
975         struct iovec iov[2];
976
977         iov[0].iov_base = (void *)(uintptr_t) path;
978         iov[0].iov_len = strlen(path) + 1;
979         iov[1].iov_base = (void *)(uintptr_t) token;
980         iov[1].iov_len = strlen(token) + 1;
981
982         return (xs_talkv(XST_NIL, XS_UNWATCH, iov, 2, NULL, NULL));
983 }
984
985 /**
986  * Convert from watch token (unique identifier) to the associated
987  * internal tracking structure for this watch.
988  *
989  * \param tocken  The unique identifier for the watch to find.
990  *
991  * \return  A pointer to the found watch structure or NULL.
992  */
993 static struct xs_watch *
994 find_watch(const char *token)
995 {
996         struct xs_watch *i, *cmp;
997
998         cmp = (void *)strtoul(token, NULL, 16);
999
1000         LIST_FOREACH(i, &xs.registered_watches, list)
1001                 if (i == cmp)
1002                         return (i);
1003
1004         return (NULL);
1005 }
1006
1007 /**
1008  * Thread body of the XenStore watch event dispatch thread.
1009  */
1010 static void
1011 xenwatch_thread(void *unused)
1012 {
1013         struct xs_stored_msg *msg;
1014
1015         for (;;) {
1016
1017                 mtx_lock(&xs.watch_events_lock);
1018                 while (TAILQ_EMPTY(&xs.watch_events))
1019                         mtx_sleep(&xs.watch_events,
1020                             &xs.watch_events_lock,
1021                             PWAIT | PCATCH, "waitev", hz/10);
1022
1023                 mtx_unlock(&xs.watch_events_lock);
1024                 sx_xlock(&xs.xenwatch_mutex);
1025
1026                 mtx_lock(&xs.watch_events_lock);
1027                 msg = TAILQ_FIRST(&xs.watch_events);
1028                 if (msg)
1029                         TAILQ_REMOVE(&xs.watch_events, msg, list);
1030                 mtx_unlock(&xs.watch_events_lock);
1031
1032                 if (msg != NULL) {
1033                         /*
1034                          * XXX There are messages coming in with a NULL
1035                          * XXX callback.  This deserves further investigation;
1036                          * XXX the workaround here simply prevents the kernel
1037                          * XXX from panic'ing on startup.
1038                          */
1039                         if (msg->u.watch.handle->callback != NULL)
1040                                 msg->u.watch.handle->callback(
1041                                         msg->u.watch.handle,
1042                                         (const char **)msg->u.watch.vec,
1043                                         msg->u.watch.vec_size);
1044                         free(msg->u.watch.vec, M_XENSTORE);
1045                         free(msg, M_XENSTORE);
1046                 }
1047
1048                 sx_xunlock(&xs.xenwatch_mutex);
1049         }
1050 }
1051
1052 /*----------- XenStore Configuration, Initialization, and Control ------------*/
1053 /**
1054  * Setup communication channels with the XenStore service.
1055  *
1056  * \return  On success, 0. Otherwise an errno value indicating the
1057  *          type of failure.
1058  */
1059 static int
1060 xs_init_comms(void)
1061 {
1062         int error;
1063
1064         if (xen_store->rsp_prod != xen_store->rsp_cons) {
1065                 log(LOG_WARNING, "XENSTORE response ring is not quiescent "
1066                     "(%08x:%08x): fixing up\n",
1067                     xen_store->rsp_cons, xen_store->rsp_prod);
1068                 xen_store->rsp_cons = xen_store->rsp_prod;
1069         }
1070
1071         if (xs.irq)
1072                 unbind_from_irqhandler(xs.irq);
1073
1074         error = bind_caller_port_to_irqhandler(xs.evtchn, "xenstore",
1075             xs_intr, NULL, INTR_TYPE_NET, &xs.irq);
1076         if (error) {
1077                 log(LOG_WARNING, "XENSTORE request irq failed %i\n", error);
1078                 return (error);
1079         }
1080
1081         return (0);
1082 }
1083
1084 /*------------------ Private Device Attachment Functions  --------------------*/
1085 static void
1086 xs_identify(driver_t *driver, device_t parent)
1087 {
1088
1089         BUS_ADD_CHILD(parent, 0, "xenstore", 0);
1090 }
1091
1092 /**
1093  * Probe for the existance of the XenStore.
1094  *
1095  * \param dev
1096  */
1097 static int 
1098 xs_probe(device_t dev)
1099 {
1100         /*
1101          * We are either operating within a PV kernel or being probed
1102          * as the child of the successfully attached xenpci device.
1103          * Thus we are in a Xen environment and there will be a XenStore.
1104          * Unconditionally return success.
1105          */
1106         device_set_desc(dev, "XenStore");
1107         return (0);
1108 }
1109
1110 static void
1111 xs_attach_deferred(void *arg)
1112 {
1113         xs_dev_init();
1114
1115         bus_generic_probe(xs.xs_dev);
1116         bus_generic_attach(xs.xs_dev);
1117
1118         config_intrhook_disestablish(&xs.xs_attachcb);
1119 }
1120
1121 /**
1122  * Attach to the XenStore.
1123  *
1124  * This routine also prepares for the probe/attach of drivers that rely
1125  * on the XenStore.  
1126  */
1127 static int
1128 xs_attach(device_t dev)
1129 {
1130         int error;
1131
1132         /* Allow us to get device_t from softc and vice-versa. */
1133         xs.xs_dev = dev;
1134         device_set_softc(dev, &xs);
1135
1136         /*
1137          * This seems to be a layering violation.  The XenStore is just
1138          * one of many clients of the Grant Table facility.  It happens
1139          * to be the first and a gating consumer to all other devices,
1140          * so this does work.  A better place would be in the PV support
1141          * code for fully PV kernels and the xenpci driver for HVM kernels.
1142          */
1143         error = gnttab_init();
1144         if (error != 0) {
1145                 log(LOG_WARNING,
1146                     "XENSTORE: Error initializing grant tables: %d\n", error);
1147                 return (ENXIO);
1148         }
1149
1150         /* Initialize the interface to xenstore. */
1151         struct proc *p;
1152
1153 #ifdef XENHVM
1154         xs.evtchn = hvm_get_parameter(HVM_PARAM_STORE_EVTCHN);
1155         xs.gpfn = hvm_get_parameter(HVM_PARAM_STORE_PFN);
1156         xen_store = pmap_mapdev(xs.gpfn * PAGE_SIZE, PAGE_SIZE);
1157 #else
1158         xs.evtchn = xen_start_info->store_evtchn;
1159 #endif
1160
1161         TAILQ_INIT(&xs.reply_list);
1162         TAILQ_INIT(&xs.watch_events);
1163
1164         mtx_init(&xs.ring_lock, "ring lock", NULL, MTX_DEF);
1165         mtx_init(&xs.reply_lock, "reply lock", NULL, MTX_DEF);
1166         sx_init(&xs.xenwatch_mutex, "xenwatch");
1167         sx_init(&xs.request_mutex, "xenstore request");
1168         sx_init(&xs.suspend_mutex, "xenstore suspend");
1169         mtx_init(&xs.registered_watches_lock, "watches", NULL, MTX_DEF);
1170         mtx_init(&xs.watch_events_lock, "watch events", NULL, MTX_DEF);
1171         xs.irq = 0;
1172
1173         /* Initialize the shared memory rings to talk to xenstored */
1174         error = xs_init_comms();
1175         if (error)
1176                 return (error);
1177
1178         error = kproc_create(xenwatch_thread, NULL, &p, RFHIGHPID,
1179             0, "xenwatch");
1180         if (error)
1181                 return (error);
1182         xs.xenwatch_pid = p->p_pid;
1183
1184         error = kproc_create(xs_rcv_thread, NULL, NULL,
1185             RFHIGHPID, 0, "xenstore_rcv");
1186
1187         xs.xs_attachcb.ich_func = xs_attach_deferred;
1188         xs.xs_attachcb.ich_arg = NULL;
1189         config_intrhook_establish(&xs.xs_attachcb);
1190
1191         return (error);
1192 }
1193
1194 /**
1195  * Prepare for suspension of this VM by halting XenStore access after
1196  * all transactions and individual requests have completed.
1197  */
1198 static int
1199 xs_suspend(device_t dev)
1200 {
1201         int error;
1202
1203         /* Suspend child Xen devices. */
1204         error = bus_generic_suspend(dev);
1205         if (error != 0)
1206                 return (error);
1207
1208         sx_xlock(&xs.suspend_mutex);
1209         sx_xlock(&xs.request_mutex);
1210
1211         return (0);
1212 }
1213
1214 /**
1215  * Resume XenStore operations after this VM is resumed.
1216  */
1217 static int
1218 xs_resume(device_t dev __unused)
1219 {
1220         struct xs_watch *watch;
1221         char token[sizeof(watch) * 2 + 1];
1222
1223         xs_init_comms();
1224
1225         sx_xunlock(&xs.request_mutex);
1226
1227         /*
1228          * No need for registered_watches_lock: the suspend_mutex
1229          * is sufficient.
1230          */
1231         LIST_FOREACH(watch, &xs.registered_watches, list) {
1232                 sprintf(token, "%lX", (long)watch);
1233                 xs_watch(watch->node, token);
1234         }
1235
1236         sx_xunlock(&xs.suspend_mutex);
1237
1238         /* Resume child Xen devices. */
1239         bus_generic_resume(dev);
1240
1241         return (0);
1242 }
1243
1244 /*-------------------- Private Device Attachment Data  -----------------------*/
1245 static device_method_t xenstore_methods[] = { 
1246         /* Device interface */ 
1247         DEVMETHOD(device_identify,      xs_identify),
1248         DEVMETHOD(device_probe,         xs_probe), 
1249         DEVMETHOD(device_attach,        xs_attach), 
1250         DEVMETHOD(device_detach,        bus_generic_detach), 
1251         DEVMETHOD(device_shutdown,      bus_generic_shutdown), 
1252         DEVMETHOD(device_suspend,       xs_suspend), 
1253         DEVMETHOD(device_resume,        xs_resume), 
1254  
1255         /* Bus interface */ 
1256         DEVMETHOD(bus_add_child,        bus_generic_add_child),
1257         DEVMETHOD(bus_alloc_resource,   bus_generic_alloc_resource),
1258         DEVMETHOD(bus_release_resource, bus_generic_release_resource),
1259         DEVMETHOD(bus_activate_resource, bus_generic_activate_resource),
1260         DEVMETHOD(bus_deactivate_resource, bus_generic_deactivate_resource),
1261
1262         DEVMETHOD_END
1263 }; 
1264
1265 DEFINE_CLASS_0(xenstore, xenstore_driver, xenstore_methods, 0);
1266 static devclass_t xenstore_devclass; 
1267  
1268 #ifdef XENHVM
1269 DRIVER_MODULE(xenstore, xenpci, xenstore_driver, xenstore_devclass, 0, 0);
1270 #else
1271 DRIVER_MODULE(xenstore, nexus, xenstore_driver, xenstore_devclass, 0, 0);
1272 #endif
1273
1274 /*------------------------------- Sysctl Data --------------------------------*/
1275 /* XXX Shouldn't the node be somewhere else? */
1276 SYSCTL_NODE(_dev, OID_AUTO, xen, CTLFLAG_RD, NULL, "Xen");
1277 SYSCTL_INT(_dev_xen, OID_AUTO, xsd_port, CTLFLAG_RD, &xs.evtchn, 0, "");
1278 SYSCTL_ULONG(_dev_xen, OID_AUTO, xsd_kva, CTLFLAG_RD, (u_long *) &xen_store, 0, "");
1279
1280 /*-------------------------------- Public API --------------------------------*/
1281 /*------- API comments for these methods can be found in xenstorevar.h -------*/
1282 int
1283 xs_directory(struct xs_transaction t, const char *dir, const char *node,
1284     u_int *num, const char ***result)
1285 {
1286         struct sbuf *path;
1287         char *strings;
1288         u_int len = 0;
1289         int error;
1290
1291         path = xs_join(dir, node);
1292         error = xs_single(t, XS_DIRECTORY, sbuf_data(path), &len,
1293             (void **)&strings);
1294         sbuf_delete(path);
1295         if (error)
1296                 return (error);
1297
1298         *result = split(strings, len, num);
1299
1300         return (0);
1301 }
1302
1303 int
1304 xs_exists(struct xs_transaction t, const char *dir, const char *node)
1305 {
1306         const char **d;
1307         int error, dir_n;
1308
1309         error = xs_directory(t, dir, node, &dir_n, &d);
1310         if (error)
1311                 return (0);
1312         free(d, M_XENSTORE);
1313         return (1);
1314 }
1315
1316 int
1317 xs_read(struct xs_transaction t, const char *dir, const char *node,
1318     u_int *len, void **result)
1319 {
1320         struct sbuf *path;
1321         void *ret;
1322         int error;
1323
1324         path = xs_join(dir, node);
1325         error = xs_single(t, XS_READ, sbuf_data(path), len, &ret);
1326         sbuf_delete(path);
1327         if (error)
1328                 return (error);
1329         *result = ret;
1330         return (0);
1331 }
1332
1333 int
1334 xs_write(struct xs_transaction t, const char *dir, const char *node,
1335     const char *string)
1336 {
1337         struct sbuf *path;
1338         struct iovec iovec[2];
1339         int error;
1340
1341         path = xs_join(dir, node);
1342
1343         iovec[0].iov_base = (void *)(uintptr_t) sbuf_data(path);
1344         iovec[0].iov_len = sbuf_len(path) + 1;
1345         iovec[1].iov_base = (void *)(uintptr_t) string;
1346         iovec[1].iov_len = strlen(string);
1347
1348         error = xs_talkv(t, XS_WRITE, iovec, 2, NULL, NULL);
1349         sbuf_delete(path);
1350
1351         return (error);
1352 }
1353
1354 int
1355 xs_mkdir(struct xs_transaction t, const char *dir, const char *node)
1356 {
1357         struct sbuf *path;
1358         int ret;
1359
1360         path = xs_join(dir, node);
1361         ret = xs_single(t, XS_MKDIR, sbuf_data(path), NULL, NULL);
1362         sbuf_delete(path);
1363
1364         return (ret);
1365 }
1366
1367 int
1368 xs_rm(struct xs_transaction t, const char *dir, const char *node)
1369 {
1370         struct sbuf *path;
1371         int ret;
1372
1373         path = xs_join(dir, node);
1374         ret = xs_single(t, XS_RM, sbuf_data(path), NULL, NULL);
1375         sbuf_delete(path);
1376
1377         return (ret);
1378 }
1379
1380 int
1381 xs_rm_tree(struct xs_transaction xbt, const char *base, const char *node)
1382 {
1383         struct xs_transaction local_xbt;
1384         struct sbuf *root_path_sbuf;
1385         struct sbuf *cur_path_sbuf;
1386         char *root_path;
1387         char *cur_path;
1388         const char **dir;
1389         int error;
1390         int empty;
1391
1392 retry:
1393         root_path_sbuf = xs_join(base, node);
1394         cur_path_sbuf  = xs_join(base, node);
1395         root_path      = sbuf_data(root_path_sbuf);
1396         cur_path       = sbuf_data(cur_path_sbuf);
1397         dir            = NULL;
1398         local_xbt.id   = 0;
1399
1400         if (xbt.id == 0) {
1401                 error = xs_transaction_start(&local_xbt);
1402                 if (error != 0)
1403                         goto out;
1404                 xbt = local_xbt;
1405         }
1406
1407         empty = 0;
1408         while (1) {
1409                 u_int count;
1410                 u_int i;
1411
1412                 error = xs_directory(xbt, cur_path, "", &count, &dir);
1413                 if (error)
1414                         goto out;
1415
1416                 for (i = 0; i < count; i++) {
1417                         error = xs_rm(xbt, cur_path, dir[i]);
1418                         if (error == ENOTEMPTY) {
1419                                 struct sbuf *push_dir;
1420
1421                                 /*
1422                                  * Descend to clear out this sub directory.
1423                                  * We'll return to cur_dir once push_dir
1424                                  * is empty.
1425                                  */
1426                                 push_dir = xs_join(cur_path, dir[i]);
1427                                 sbuf_delete(cur_path_sbuf);
1428                                 cur_path_sbuf = push_dir;
1429                                 cur_path = sbuf_data(cur_path_sbuf);
1430                                 break;
1431                         } else if (error != 0) {
1432                                 goto out;
1433                         }
1434                 }
1435
1436                 free(dir, M_XENSTORE);
1437                 dir = NULL;
1438
1439                 if (i == count) {
1440                         char *last_slash;
1441
1442                         /* Directory is empty.  It is now safe to remove. */
1443                         error = xs_rm(xbt, cur_path, "");
1444                         if (error != 0)
1445                                 goto out;
1446
1447                         if (!strcmp(cur_path, root_path))
1448                                 break;
1449
1450                         /* Return to processing the parent directory. */
1451                         last_slash = strrchr(cur_path, '/');
1452                         KASSERT(last_slash != NULL,
1453                                 ("xs_rm_tree: mangled path %s", cur_path));
1454                         *last_slash = '\0';
1455                 }
1456         }
1457
1458 out:
1459         sbuf_delete(cur_path_sbuf);
1460         sbuf_delete(root_path_sbuf);
1461         if (dir != NULL)
1462                 free(dir, M_XENSTORE);
1463
1464         if (local_xbt.id != 0) {
1465                 int terror;
1466
1467                 terror = xs_transaction_end(local_xbt, /*abort*/error != 0);
1468                 xbt.id = 0;
1469                 if (terror == EAGAIN && error == 0)
1470                         goto retry;
1471         }
1472         return (error);
1473 }
1474
1475 int
1476 xs_transaction_start(struct xs_transaction *t)
1477 {
1478         char *id_str;
1479         int error;
1480
1481         error = xs_single(XST_NIL, XS_TRANSACTION_START, "", NULL,
1482             (void **)&id_str);
1483         if (error == 0) {
1484                 t->id = strtoul(id_str, NULL, 0);
1485                 free(id_str, M_XENSTORE);
1486         }
1487         return (error);
1488 }
1489
1490 int
1491 xs_transaction_end(struct xs_transaction t, int abort)
1492 {
1493         char abortstr[2];
1494
1495         if (abort)
1496                 strcpy(abortstr, "F");
1497         else
1498                 strcpy(abortstr, "T");
1499
1500         return (xs_single(t, XS_TRANSACTION_END, abortstr, NULL, NULL));
1501 }
1502
1503 int
1504 xs_scanf(struct xs_transaction t, const char *dir, const char *node,
1505      int *scancountp, const char *fmt, ...)
1506 {
1507         va_list ap;
1508         int error, ns;
1509         char *val;
1510
1511         error = xs_read(t, dir, node, NULL, (void **) &val);
1512         if (error)
1513                 return (error);
1514
1515         va_start(ap, fmt);
1516         ns = vsscanf(val, fmt, ap);
1517         va_end(ap);
1518         free(val, M_XENSTORE);
1519         /* Distinctive errno. */
1520         if (ns == 0)
1521                 return (ERANGE);
1522         if (scancountp)
1523                 *scancountp = ns;
1524         return (0);
1525 }
1526
1527 int
1528 xs_vprintf(struct xs_transaction t,
1529     const char *dir, const char *node, const char *fmt, va_list ap)
1530 {
1531         struct sbuf *sb;
1532         int error;
1533
1534         sb = sbuf_new_auto();
1535         sbuf_vprintf(sb, fmt, ap);
1536         sbuf_finish(sb);
1537         error = xs_write(t, dir, node, sbuf_data(sb));
1538         sbuf_delete(sb);
1539
1540         return (error);
1541 }
1542
1543 int
1544 xs_printf(struct xs_transaction t, const char *dir, const char *node,
1545      const char *fmt, ...)
1546 {
1547         va_list ap;
1548         int error;
1549
1550         va_start(ap, fmt);
1551         error = xs_vprintf(t, dir, node, fmt, ap);
1552         va_end(ap);
1553
1554         return (error);
1555 }
1556
1557 int
1558 xs_gather(struct xs_transaction t, const char *dir, ...)
1559 {
1560         va_list ap;
1561         const char *name;
1562         int error;
1563
1564         va_start(ap, dir);
1565         error = 0;
1566         while (error == 0 && (name = va_arg(ap, char *)) != NULL) {
1567                 const char *fmt = va_arg(ap, char *);
1568                 void *result = va_arg(ap, void *);
1569                 char *p;
1570
1571                 error = xs_read(t, dir, name, NULL, (void **) &p);
1572                 if (error)
1573                         break;
1574
1575                 if (fmt) {
1576                         if (sscanf(p, fmt, result) == 0)
1577                                 error = EINVAL;
1578                         free(p, M_XENSTORE);
1579                 } else
1580                         *(char **)result = p;
1581         }
1582         va_end(ap);
1583
1584         return (error);
1585 }
1586
1587 int
1588 xs_register_watch(struct xs_watch *watch)
1589 {
1590         /* Pointer in ascii is the token. */
1591         char token[sizeof(watch) * 2 + 1];
1592         int error;
1593
1594         sprintf(token, "%lX", (long)watch);
1595
1596         sx_slock(&xs.suspend_mutex);
1597
1598         mtx_lock(&xs.registered_watches_lock);
1599         KASSERT(find_watch(token) == NULL, ("watch already registered"));
1600         LIST_INSERT_HEAD(&xs.registered_watches, watch, list);
1601         mtx_unlock(&xs.registered_watches_lock);
1602
1603         error = xs_watch(watch->node, token);
1604
1605         /* Ignore errors due to multiple registration. */
1606         if (error == EEXIST)
1607                 error = 0;
1608
1609         if (error != 0) {
1610                 mtx_lock(&xs.registered_watches_lock);
1611                 LIST_REMOVE(watch, list);
1612                 mtx_unlock(&xs.registered_watches_lock);
1613         }
1614
1615         sx_sunlock(&xs.suspend_mutex);
1616
1617         return (error);
1618 }
1619
1620 void
1621 xs_unregister_watch(struct xs_watch *watch)
1622 {
1623         struct xs_stored_msg *msg, *tmp;
1624         char token[sizeof(watch) * 2 + 1];
1625         int error;
1626
1627         sprintf(token, "%lX", (long)watch);
1628
1629         sx_slock(&xs.suspend_mutex);
1630
1631         mtx_lock(&xs.registered_watches_lock);
1632         if (find_watch(token) == NULL) {
1633                 mtx_unlock(&xs.registered_watches_lock);
1634                 sx_sunlock(&xs.suspend_mutex);
1635                 return;
1636         }
1637         LIST_REMOVE(watch, list);
1638         mtx_unlock(&xs.registered_watches_lock);
1639
1640         error = xs_unwatch(watch->node, token);
1641         if (error)
1642                 log(LOG_WARNING, "XENSTORE Failed to release watch %s: %i\n",
1643                     watch->node, error);
1644
1645         sx_sunlock(&xs.suspend_mutex);
1646
1647         /* Cancel pending watch events. */
1648         mtx_lock(&xs.watch_events_lock);
1649         TAILQ_FOREACH_SAFE(msg, &xs.watch_events, list, tmp) {
1650                 if (msg->u.watch.handle != watch)
1651                         continue;
1652                 TAILQ_REMOVE(&xs.watch_events, msg, list);
1653                 free(msg->u.watch.vec, M_XENSTORE);
1654                 free(msg, M_XENSTORE);
1655         }
1656         mtx_unlock(&xs.watch_events_lock);
1657
1658         /* Flush any currently-executing callback, unless we are it. :-) */
1659         if (curproc->p_pid != xs.xenwatch_pid) {
1660                 sx_xlock(&xs.xenwatch_mutex);
1661                 sx_xunlock(&xs.xenwatch_mutex);
1662         }
1663 }