Debian Codegraph @

tools/xenstored/domain.c

raw
1 /*
2 Domain communications for Xen Store Daemon.
3 Copyright (C) 2005 Rusty Russell IBM Corporation
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <assert.h>
20 #include <stdio.h>
21 #include <sys/mman.h>
22 #include <unistd.h>
23 #include <stdlib.h>
24 #include <stdarg.h>
25 #include <time.h>
26 #include <syslog.h>
27
28 #include "utils.h"
29 #include "talloc.h"
30 #include "core.h"
31 #include "domain.h"
32 #include "transaction.h"
33 #include "watch.h"
34 #include "control.h"
35
36 #include <xenevtchn.h>
37 #include <xenctrl.h>
38 #include <xen/grant_table.h>
39
40 #ifdef __MINIOS__
41 #include <mini-os/xenbus.h>
42 #endif
43
44 static xc_interface **xc_handle;
45 xengnttab_handle **xgt_handle;
46 static evtchn_port_t virq_port;
47
48 xenevtchn_handle *xce_handle = NULL;
49
50 struct quota hard_quotas[ACC_N] = {
51 [ACC_NODES] = {
52 .name = "nodes",
53 .descr = "Nodes per domain",
54 .val = 1000,
55 },
56 [ACC_WATCH] = {
57 .name = "watches",
58 .descr = "Watches per domain",
59 .val = 128,
60 },
61 [ACC_OUTST] = {
62 .name = "outstanding",
63 .descr = "Outstanding requests per domain",
64 .val = 20,
65 },
66 [ACC_MEM] = {
67 .name = "memory",
68 .descr = "Total Xenstore memory per domain (error level)",
69 .val = 2 * 1024 * 1024 + 512 * 1024, /* 2.5 MB */
70 },
71 [ACC_TRANS] = {
72 .name = "transactions",
73 .descr = "Active transactions per domain",
74 .val = 10,
75 },
76 [ACC_TRANSNODES] = {
77 .name = "transaction-nodes",
78 .descr = "Max. number of accessed nodes per transaction",
79 .val = 1024,
80 },
81 [ACC_NPERM] = {
82 .name = "node-permissions",
83 .descr = "Max. number of permissions per node",
84 .val = 5,
85 },
86 [ACC_PATHLEN] = {
87 .name = "path-max",
88 .descr = "Max. length of a node path",
89 .val = XENSTORE_REL_PATH_MAX,
90 },
91 [ACC_NODESZ] = {
92 .name = "node-size",
93 .descr = "Max. size of a node",
94 .val = 2048,
95 },
96 };
97
98 struct quota soft_quotas[ACC_N] = {
99 [ACC_MEM] = {
100 .name = "memory",
101 .descr = "Total Xenstore memory per domain (warning level)",
102 .val = 2 * 1024 * 1024, /* 2.0 MB */
103 },
104 };
105
106 typedef int32_t wrl_creditt;
107
108 struct domain
109 {
110 /* The id of this domain */
111 unsigned int domid;
112
113 /* Event channel port */
114 evtchn_port_t port;
115
116 /* Domain path in store. */
117 char *path;
118
119 /* Shared page. */
120 struct xenstore_domain_interface *interface;
121
122 /* The connection associated with this. */
123 struct connection *conn;
124
125 /* Generation count at domain introduction time. */
126 uint64_t generation;
127
128 /* Have we noticed that this domain is shutdown? */
129 bool shutdown;
130
131 /* Has domain been officially introduced? */
132 bool introduced;
133
134 /* Accounting data for this domain. */
135 struct acc {
136 unsigned int val;
137 unsigned int max;
138 } acc[ACC_N];
139
140 /* Memory quota data for this domain. */
141 bool soft_quota_reported;
142 bool hard_quota_reported;
143 time_t mem_last_msg;
144 #define MEM_WARN_MINTIME_SEC 10
145
146 /* write rate limit */
147 wrl_creditt wrl_credit; /* [ -wrl_config_writecost, +_dburst ] */
148 uint64_t wrl_timestamp;
149 bool wrl_delay_logged;
150 };
151
152 struct changed_domain
153 {
154 /* List of all changed domains. */
155 struct list_head list;
156
157 /* Identifier of the changed domain. */
158 unsigned int domid;
159
160 /* Accounting data. */
161 int acc[ACC_CHD_N];
162 };
163
164 static struct hashtable *domhash;
165
166 /* Write rate limiting */
167
168 /* Satisfies non-overflow condition for wrl_xfer_credit. */
169 #define WRL_CREDIT_MAX (1000*1000*1000)
170 #define WRL_FACTOR 1000 /* for fixed-point arithmetic */
171 #define WRL_RATE 200
172 #define WRL_DBURST 10
173 #define WRL_GBURST 1000
174 #define WRL_NEWDOMS 5
175 #define WRL_LOGEVERY 120 /* seconds */
176
177 static wrl_creditt wrl_config_writecost = WRL_FACTOR;
178 static wrl_creditt wrl_config_rate = WRL_RATE * WRL_FACTOR;
179 static wrl_creditt wrl_config_dburst = WRL_DBURST * WRL_FACTOR;
180 static wrl_creditt wrl_config_gburst = WRL_GBURST * WRL_FACTOR;
181 static wrl_creditt wrl_config_newdoms_dburst =
182 WRL_DBURST * WRL_NEWDOMS * WRL_FACTOR;
183
184 long wrl_ntransactions;
185
186 static long wrl_ndomains;
187 static wrl_creditt wrl_reserve; /* [-wrl_config_newdoms_dburst, +_gburst ] */
188 static time_t wrl_log_last_warning; /* 0: no previous warning */
189
190 #define trace_wrl(...) \
191 do { \
192 if (trace_flags & TRACE_WRL) \
193 trace("wrl: " __VA_ARGS__); \
194 } while (0)
195
196 static void wrl_xfer_credit(wrl_creditt *debit, wrl_creditt debit_floor,
197 wrl_creditt *credit, wrl_creditt credit_ceil)
198 /*
199 * Transfers zero or more credit from "debit" to "credit".
200 * Transfers as much as possible while maintaining
201 * debit >= debit_floor and credit <= credit_ceil.
202 * (If that's violated already, does nothing.)
203 *
204 * Sufficient conditions to avoid overflow, either of:
205 * |every argument| <= 0x3fffffff
206 * |every argument| <= 1E9
207 * |every argument| <= WRL_CREDIT_MAX
208 * (And this condition is preserved.)
209 */
210 {
211 wrl_creditt xfer = MIN( *debit - debit_floor,
212 credit_ceil - *credit );
213 if (xfer > 0) {
214 *debit -= xfer;
215 *credit += xfer;
216 }
217 }
218
219 static void wrl_domain_new(struct domain *domain)
220 {
221 domain->wrl_credit = 0;
222 domain->wrl_timestamp = get_now_msec();
223 wrl_ndomains++;
224 /* Steal up to DBURST from the reserve */
225 wrl_xfer_credit(&wrl_reserve, -wrl_config_newdoms_dburst,
226 &domain->wrl_credit, wrl_config_dburst);
227 }
228
229 static void wrl_domain_destroy(struct domain *domain)
230 {
231 wrl_ndomains--;
232 /*
233 * Don't bother recalculating domain's credit - this just
234 * means we don't give the reserve the ending domain's credit
235 * for time elapsed since last update.
236 */
237 wrl_xfer_credit(&domain->wrl_credit, 0,
238 &wrl_reserve, wrl_config_dburst);
239 }
240
241 static void wrl_credit_update(struct domain *domain, uint64_t now)
242 {
243 /*
244 * We want to calculate
245 * credit += (now - timestamp) * RATE / ndoms;
246 * But we want it to saturate, and to avoid floating point.
247 * To avoid rounding errors from constantly adding small
248 * amounts of credit, we only add credit for whole milliseconds.
249 */
250 long msec;
251 int64_t denom, num;
252 wrl_creditt surplus;
253
254 /* Prevent overflow by limiting to 32 bits. */
255 msec = MIN(now - domain->wrl_timestamp, 1000 * 1000 * 1000);
256
257 /* 32x32 -> 64 cannot overflow */
258 denom = (int64_t)msec * wrl_config_rate;
259 num = (int64_t)wrl_ndomains * 1000;
260 /* denom / num <= 1E6 * wrl_config_rate, so with
261 reasonable wrl_config_rate, denom / num << 2^64 */
262
263 /* at last! */
264 domain->wrl_credit = MIN( (int64_t)domain->wrl_credit + denom / num,
265 WRL_CREDIT_MAX );
266 /* (maybe briefly violating the DBURST cap on wrl_credit) */
267
268 /* maybe take from the reserve to make us nonnegative */
269 wrl_xfer_credit(&wrl_reserve, 0,
270 &domain->wrl_credit, 0);
271
272 /* return any surplus (over DBURST) to the reserve */
273 surplus = 0;
274 wrl_xfer_credit(&domain->wrl_credit, wrl_config_dburst,
275 &surplus, WRL_CREDIT_MAX);
276 wrl_xfer_credit(&surplus, 0,
277 &wrl_reserve, wrl_config_gburst);
278 /* surplus is now implicitly discarded */
279
280 domain->wrl_timestamp = now;
281
282 trace_wrl("dom %4d %6ld msec %9ld credit %9ld reserve %9ld discard\n",
283 domain->domid, msec, (long)domain->wrl_credit,
284 (long)wrl_reserve, (long)surplus);
285 }
286
287 void wrl_check_timeout(struct domain *domain, uint64_t now, int *ptimeout)
288 {
289 uint64_t num, denom;
290 int wakeup;
291
292 wrl_credit_update(domain, now);
293
294 if (domain->wrl_credit >= 0)
295 /* not blocked */
296 return;
297
298 if (!*ptimeout)
299 /* already decided on immediate wakeup,
300 so no need to calculate our timeout */
301 return;
302
303 /* calculate wakeup = now + -credit / (RATE / ndoms); */
304
305 /* credit cannot go more -ve than one transaction,
306 * so the first multiplication cannot overflow even 32-bit */
307 num = (uint64_t)(-domain->wrl_credit * 1000) * wrl_ndomains;
308 denom = wrl_config_rate;
309
310 wakeup = MIN( num / denom /* uint64_t */, INT_MAX );
311 if (*ptimeout==-1 || wakeup < *ptimeout)
312 *ptimeout = wakeup;
313
314 trace_wrl("domain %u credit=%ld (reserve=%ld) SLEEPING for %d\n",
315 domain->domid, (long)domain->wrl_credit, (long)wrl_reserve,
316 wakeup);
317 }
318
319 #define WRL_LOG(now, ...) \
320 (syslog(LOG_WARNING, "write rate limit: " __VA_ARGS__))
321
322 void wrl_apply_debit_actual(struct domain *domain)
323 {
324 uint64_t now;
325
326 if (!domain || !domain_is_unprivileged(domain->conn))
327 /* sockets and privileged domain escape the write rate limit */
328 return;
329
330 now = get_now_msec();
331 wrl_credit_update(domain, now);
332
333 domain->wrl_credit -= wrl_config_writecost;
334 trace_wrl("domain %u credit=%ld (reserve=%ld)\n", domain->domid,
335 (long)domain->wrl_credit, (long)wrl_reserve);
336
337 if (domain->wrl_credit < 0) {
338 if (!domain->wrl_delay_logged) {
339 domain->wrl_delay_logged = true;
340 WRL_LOG(now, "domain %ld is affected\n",
341 (long)domain->domid);
342 } else if (!wrl_log_last_warning) {
343 WRL_LOG(now, "rate limiting restarts\n");
344 }
345 wrl_log_last_warning = now / 1000;
346 }
347 }
348
349 void wrl_log_periodic(uint64_t now)
350 {
351 if (wrl_log_last_warning &&
352 (now / 1000 - wrl_log_last_warning) > WRL_LOGEVERY) {
353 WRL_LOG(now, "not in force recently\n");
354 wrl_log_last_warning = 0;
355 }
356 }
357
358 void wrl_apply_debit_direct(struct connection *conn)
359 {
360 if (!conn)
361 /* some writes are generated internally */
362 return;
363
364 if (conn->transaction)
365 /* these are accounted for when the transaction ends */
366 return;
367
368 if (!wrl_ntransactions)
369 /* we don't conflict with anyone */
370 return;
371
372 wrl_apply_debit_actual(conn->domain);
373 }
374
375 void wrl_apply_debit_trans_commit(struct connection *conn)
376 {
377 if (wrl_ntransactions <= 1)
378 /* our own transaction appears in the counter */
379 return;
380
381 wrl_apply_debit_actual(conn->domain);
382 }
383
384 static bool check_indexes(XENSTORE_RING_IDX cons, XENSTORE_RING_IDX prod)
385 {
386 return ((prod - cons) <= XENSTORE_RING_SIZE);
387 }
388
389 static void *get_output_chunk(XENSTORE_RING_IDX cons,
390 XENSTORE_RING_IDX prod,
391 char *buf, uint32_t *len)
392 {
393 *len = XENSTORE_RING_SIZE - MASK_XENSTORE_IDX(prod);
394 if ((XENSTORE_RING_SIZE - (prod - cons)) < *len)
395 *len = XENSTORE_RING_SIZE - (prod - cons);
396 return buf + MASK_XENSTORE_IDX(prod);
397 }
398
399 static const void *get_input_chunk(XENSTORE_RING_IDX cons,
400 XENSTORE_RING_IDX prod,
401 const char *buf, uint32_t *len)
402 {
403 *len = XENSTORE_RING_SIZE - MASK_XENSTORE_IDX(cons);
404 if ((prod - cons) < *len)
405 *len = prod - cons;
406 return buf + MASK_XENSTORE_IDX(cons);
407 }
408
409 static int writechn(struct connection *conn,
410 const void *data, unsigned int len)
411 {
412 uint32_t avail;
413 void *dest;
414 struct xenstore_domain_interface *intf = conn->domain->interface;
415 XENSTORE_RING_IDX cons, prod;
416
417 /* Must read indexes once, and before anything else, and verified. */
418 cons = intf->rsp_cons;
419 prod = intf->rsp_prod;
420 xen_mb();
421
422 if (!check_indexes(cons, prod)) {
423 errno = EIO;
424 return -1;
425 }
426
427 dest = get_output_chunk(cons, prod, intf->rsp, &avail);
428 if (avail < len)
429 len = avail;
430
431 memcpy(dest, data, len);
432 xen_mb();
433 intf->rsp_prod += len;
434
435 xenevtchn_notify(xce_handle, conn->domain->port);
436
437 return len;
438 }
439
440 static int readchn(struct connection *conn, void *data, unsigned int len)
441 {
442 uint32_t avail;
443 const void *src;
444 struct xenstore_domain_interface *intf = conn->domain->interface;
445 XENSTORE_RING_IDX cons, prod;
446
447 /* Must read indexes once, and before anything else, and verified. */
448 cons = intf->req_cons;
449 prod = intf->req_prod;
450 xen_mb();
451
452 if (!check_indexes(cons, prod)) {
453 errno = EIO;
454 return -1;
455 }
456
457 src = get_input_chunk(cons, prod, intf->req, &avail);
458 if (avail < len)
459 len = avail;
460
461 memcpy(data, src, len);
462 xen_mb();
463 intf->req_cons += len;
464
465 xenevtchn_notify(xce_handle, conn->domain->port);
466
467 return len;
468 }
469
470 static bool domain_can_write(struct connection *conn)
471 {
472 struct xenstore_domain_interface *intf = conn->domain->interface;
473
474 return ((intf->rsp_prod - intf->rsp_cons) != XENSTORE_RING_SIZE);
475 }
476
477 static bool domain_can_read(struct connection *conn)
478 {
479 struct domain *domain = conn->domain;
480 struct xenstore_domain_interface *intf = domain->interface;
481
482 if (domain_is_unprivileged(conn)) {
483 if (domain->wrl_credit < 0)
484 return false;
485 if (domain->acc[ACC_OUTST].val >= hard_quotas[ACC_OUTST].val)
486 return false;
487 if (domain->acc[ACC_MEM].val >= hard_quotas[ACC_MEM].val &&
488 hard_quotas[ACC_MEM].val)
489 return false;
490 }
491
492 return (intf->req_cons != intf->req_prod);
493 }
494
495 static const struct interface_funcs domain_funcs = {
496 .write = writechn,
497 .read = readchn,
498 .can_write = domain_can_write,
499 .can_read = domain_can_read,
500 };
501
502 static void *map_interface(domid_t domid)
503 {
504 if (domid == xenbus_master_domid())
505 return xenbus_map();
506
507 #ifdef __MINIOS__
508 if (domid == stub_domid)
509 return xenstore_buf;
510 #endif
511
512 return xengnttab_map_grant_ref(*xgt_handle, domid,
513 GNTTAB_RESERVED_XENSTORE,
514 PROT_READ|PROT_WRITE);
515 }
516
517 static void unmap_interface(domid_t domid, void *interface)
518 {
519 if (domid == xenbus_master_domid())
520 unmap_xenbus(interface);
521 else if (domid != stub_domid)
522 xengnttab_unmap(*xgt_handle, interface, 1);
523 }
524
525 static int domain_tree_remove_sub(const void *ctx, struct connection *conn,
526 struct node *node, void *arg)
527 {
528 struct domain *domain = arg;
529 int ret = WALK_TREE_OK;
530
531 if (node->perms[0].id != domain->domid)
532 return WALK_TREE_OK;
533
534 if (keep_orphans) {
535 domain_nbentry_dec(NULL, domain->domid);
536 node->perms[0].id = priv_domid;
537 node->acc.memory = 0;
538 domain_nbentry_inc(NULL, priv_domid);
539 if (write_node_raw(NULL, node->name, node, NODE_MODIFY, true)) {
540 /* That's unfortunate. We only can try to continue. */
541 syslog(LOG_ERR,
542 "error when moving orphaned node %s to dom0\n",
543 node->name);
544 } else
545 trace("orphaned node %s moved to dom0\n", node->name);
546 } else {
547 if (rm_node(NULL, ctx, node->name)) {
548 /* That's unfortunate. We only can try to continue. */
549 syslog(LOG_ERR,
550 "error when deleting orphaned node %s\n",
551 node->name);
552 } else
553 trace("orphaned node %s deleted\n", node->name);
554
555 /* Skip children in all cases in order to avoid more errors. */
556 ret = WALK_TREE_SKIP_CHILDREN;
557 }
558
559 return domain->acc[ACC_NODES].val ? ret : WALK_TREE_SUCCESS_STOP;
560 }
561
562 static void domain_tree_remove(struct domain *domain)
563 {
564 int ret;
565 struct walk_funcs walkfuncs = { .enter = domain_tree_remove_sub };
566
567 if (domain->acc[ACC_NODES].val) {
568 ret = walk_node_tree(domain, NULL, "/", &walkfuncs, domain);
569 if (ret == WALK_TREE_ERROR_STOP)
570 syslog(LOG_ERR,
571 "error when looking for orphaned nodes\n");
572 }
573
574 walk_node_tree(domain, NULL, "@releaseDomain", &walkfuncs, domain);
575 walk_node_tree(domain, NULL, "@introduceDomain", &walkfuncs, domain);
576 }
577
578 static void fire_special_watches(const char *name)
579 {
580 void *ctx = talloc_new(NULL);
581 const struct node *node;
582
583 if (!ctx)
584 return;
585
586 node = read_node_const(NULL, ctx, name);
587
588 if (node)
589 fire_watches(NULL, ctx, name, node, true, NULL);
590 else
591 log("special node %s not found\n", name);
592
593 talloc_free(ctx);
594 }
595
596 static int destroy_domain(void *_domain)
597 {
598 struct domain *domain = _domain;
599
600 domain_tree_remove(domain);
601
602 hashtable_remove(domhash, &domain->domid);
603
604 if (!domain->introduced)
605 return 0;
606
607 if (domain->port) {
608 if (xenevtchn_unbind(xce_handle, domain->port) == -1)
609 eprintf("> Unbinding port %i failed!\n", domain->port);
610 }
611
612 if (domain->interface)
613 unmap_interface(domain->domid, domain->interface);
614
615 fire_special_watches("@releaseDomain");
616
617 wrl_domain_destroy(domain);
618
619 return 0;
620 }
621
622 static bool get_domain_info(unsigned int domid, xc_domaininfo_t *dominfo)
623 {
624 return xc_domain_getinfo_single(*xc_handle, domid, dominfo) == 0;
625 }
626
627 static int check_domain(const void *k, void *v, void *arg)
628 {
629 xc_domaininfo_t dominfo;
630 struct connection *conn;
631 bool dom_valid;
632 struct domain *domain = v;
633 bool *notify = arg;
634
635 dom_valid = get_domain_info(domain->domid, &dominfo);
636 if (!domain->introduced) {
637 if (!dom_valid)
638 talloc_free(domain);
639 return 0;
640 }
641 if (dom_valid) {
642 if ((dominfo.flags & XEN_DOMINF_shutdown)
643 && !domain->shutdown) {
644 domain->shutdown = true;
645 *notify = true;
646 }
647 if (!(dominfo.flags & XEN_DOMINF_dying))
648 return 0;
649 }
650 if (domain->conn) {
651 /* domain is a talloc child of domain->conn. */
652 conn = domain->conn;
653 domain->conn = NULL;
654 talloc_unlink(talloc_autofree_context(), conn);
655 *notify = false; /* destroy_domain() fires the watch */
656
657 /* Above unlink might result in 2 domains being freed! */
658 return 1;
659 }
660
661 return 0;
662 }
663
664 void check_domains(void)
665 {
666 bool notify = false;
667
668 while (hashtable_iterate(domhash, check_domain, &notify))
669 ;
670
671 if (notify)
672 fire_special_watches("@releaseDomain");
673 }
674
675 /* We scan all domains rather than use the information given here. */
676 void handle_event(void)
677 {
678 evtchn_port_t port;
679
680 if ((port = xenevtchn_pending(xce_handle)) == -1)
681 barf_perror("Failed to read from event fd");
682
683 if (port == virq_port)
684 check_domains();
685
686 if (xenevtchn_unmask(xce_handle, port) == -1)
687 barf_perror("Failed to write to event fd");
688 }
689
690 static char *talloc_domain_path(const void *context, unsigned int domid)
691 {
692 return talloc_asprintf(context, "/local/domain/%u", domid);
693 }
694
695 static struct domain *find_domain_struct(unsigned int domid)
696 {
697 return hashtable_search(domhash, &domid);
698 }
699
700 int domain_get_quota(const void *ctx, struct connection *conn,
701 unsigned int domid)
702 {
703 struct domain *d = find_domain_struct(domid);
704 char *resp;
705 unsigned int i;
706
707 if (!d)
708 return ENOENT;
709
710 resp = talloc_asprintf(ctx, "Domain %u:\n", domid);
711 if (!resp)
712 return ENOMEM;
713
714 for (i = 0; i < ACC_N; i++) {
715 if (!hard_quotas[i].name)
716 continue;
717 resp = talloc_asprintf_append(resp, "%-17s: %8u (max %8u)\n",
718 hard_quotas[i].name,
719 d->acc[i].val, d->acc[i].max);
720 if (!resp)
721 return ENOMEM;
722 }
723
724 send_reply(conn, XS_CONTROL, resp, strlen(resp) + 1);
725
726 return 0;
727 }
728
729 int domain_max_global_acc(const void *ctx, struct connection *conn)
730 {
731 char *resp;
732 unsigned int i;
733
734 resp = talloc_asprintf(ctx, "Max. seen accounting values:\n");
735 if (!resp)
736 return ENOMEM;
737
738 for (i = 0; i < ACC_N; i++) {
739 if (!hard_quotas[i].name)
740 continue;
741 resp = talloc_asprintf_append(resp, "%-17s: %8u\n",
742 hard_quotas[i].name,
743 hard_quotas[i].max);
744 if (!resp)
745 return ENOMEM;
746 }
747
748 send_reply(conn, XS_CONTROL, resp, strlen(resp) + 1);
749
750 return 0;
751 }
752
753 static struct domain *alloc_domain(const void *context, unsigned int domid)
754 {
755 struct domain *domain;
756
757 domain = talloc_zero(context, struct domain);
758 if (!domain) {
759 errno = ENOMEM;
760 return NULL;
761 }
762
763 domain->domid = domid;
764 domain->generation = generation;
765 domain->introduced = false;
766
767 if (hashtable_add(domhash, &domain->domid, domain)) {
768 talloc_free(domain);
769 errno = ENOMEM;
770 return NULL;
771 }
772
773 talloc_set_destructor(domain, destroy_domain);
774
775 return domain;
776 }
777
778 static struct domain *find_or_alloc_domain(const void *ctx, unsigned int domid)
779 {
780 struct domain *domain;
781
782 domain = find_domain_struct(domid);
783 return domain ? : alloc_domain(ctx, domid);
784 }
785
786 static struct domain *find_or_alloc_existing_domain(unsigned int domid)
787 {
788 struct domain *domain;
789 xc_domaininfo_t dominfo;
790
791 domain = find_domain_struct(domid);
792 if (!domain && get_domain_info(domid, &dominfo))
793 domain = alloc_domain(NULL, domid);
794
795 return domain;
796 }
797
798 static int new_domain(struct domain *domain, int port, bool restore)
799 {
800 int rc;
801
802 domain->port = 0;
803 domain->shutdown = false;
804 domain->path = talloc_domain_path(domain, domain->domid);
805 if (!domain->path) {
806 errno = ENOMEM;
807 return errno;
808 }
809
810 wrl_domain_new(domain);
811
812 if (restore)
813 domain->port = port;
814 else {
815 /* Tell kernel we're interested in this event. */
816 rc = xenevtchn_bind_interdomain(xce_handle, domain->domid,
817 port);
818 if (rc == -1)
819 return errno;
820 domain->port = rc;
821 }
822
823 domain->introduced = true;
824
825 domain->conn = new_connection(&domain_funcs);
826 if (!domain->conn) {
827 errno = ENOMEM;
828 return errno;
829 }
830
831 domain->conn->domain = domain;
832 domain->conn->id = domain->domid;
833
834 return 0;
835 }
836
837
838 static struct domain *find_domain_by_domid(unsigned int domid)
839 {
840 struct domain *d;
841
842 d = find_domain_struct(domid);
843
844 return (d && d->introduced) ? d : NULL;
845 }
846
847 #define trace_acc(...) \
848 do { \
849 if (trace_flags & TRACE_ACC) \
850 trace("acc: " __VA_ARGS__); \
851 } while (0)
852
853 int acc_fix_domains(struct list_head *head, bool chk_quota, bool update)
854 {
855 struct changed_domain *cd;
856 int cnt;
857
858 list_for_each_entry(cd, head, list) {
859 cnt = domain_nbentry_fix(cd->domid, cd->acc[ACC_NODES], update);
860 if (!update) {
861 if (chk_quota && cnt >= hard_quotas[ACC_NODES].val)
862 return ENOSPC;
863 if (cnt < 0)
864 return ENOMEM;
865 }
866 }
867
868 return 0;
869 }
870
871 static struct changed_domain *acc_find_changed_domain(struct list_head *head,
872 unsigned int domid)
873 {
874 struct changed_domain *cd;
875
876 list_for_each_entry(cd, head, list) {
877 if (cd->domid == domid)
878 return cd;
879 }
880
881 return NULL;
882 }
883
884 static struct changed_domain *acc_get_changed_domain(const void *ctx,
885 struct list_head *head,
886 unsigned int domid)
887 {
888 struct changed_domain *cd;
889
890 cd = acc_find_changed_domain(head, domid);
891 if (cd)
892 return cd;
893
894 cd = talloc_zero(ctx, struct changed_domain);
895 if (!cd)
896 return NULL;
897
898 cd->domid = domid;
899 list_add_tail(&cd->list, head);
900
901 return cd;
902 }
903
904 static int acc_add_changed_dom(const void *ctx, struct list_head *head,
905 enum accitem what, int val, unsigned int domid)
906 {
907 struct changed_domain *cd;
908
909 assert(what < ARRAY_SIZE(cd->acc));
910
911 cd = acc_get_changed_domain(ctx, head, domid);
912 if (!cd)
913 return 0;
914
915 errno = 0;
916 trace_acc("local change domid %u: what=%u %d add %d\n", domid, what,
917 cd->acc[what], val);
918 cd->acc[what] += val;
919
920 return cd->acc[what];
921 }
922
923 static void domain_conn_reset(struct domain *domain)
924 {
925 struct connection *conn = domain->conn;
926
927 conn_delete_all_watches(conn);
928 conn_delete_all_transactions(conn);
929 conn_free_buffered_data(conn);
930
931 talloc_free(conn->in);
932
933 domain->interface->req_cons = domain->interface->req_prod = 0;
934 domain->interface->rsp_cons = domain->interface->rsp_prod = 0;
935 xen_wmb();
936 }
937
938 /*
939 * Keep the connection alive but stop processing any new request or sending
940 * reponse. This is to allow sending @releaseDomain watch event at the correct
941 * moment and/or to allow the connection to restart (not yet implemented).
942 *
943 * All watches, transactions, buffers will be freed.
944 */
945 void ignore_connection(struct connection *conn, unsigned int err)
946 {
947 trace("CONN %p ignored, reason %u\n", conn, err);
948
949 if (conn->domain && conn->domain->interface)
950 conn->domain->interface->error = err;
951
952 conn->is_ignored = true;
953 conn_delete_all_watches(conn);
954 conn_delete_all_transactions(conn);
955 conn_free_buffered_data(conn);
956
957 talloc_free(conn->in);
958 conn->in = NULL;
959 /* if this is a socket connection, drop it now */
960 if (conn->fd >= 0)
961 talloc_free(conn);
962 }
963
964 static struct domain *introduce_domain(const void *ctx,
965 unsigned int domid,
966 evtchn_port_t port, bool restore)
967 {
968 struct domain *domain;
969 int rc;
970 struct xenstore_domain_interface *interface;
971 bool is_master_domain = (domid == xenbus_master_domid());
972
973 domain = find_or_alloc_domain(ctx, domid);
974 if (!domain)
975 return NULL;
976
977 if (!domain->introduced) {
978 interface = map_interface(domid);
979 if (!interface && !restore)
980 return NULL;
981 if (new_domain(domain, port, restore)) {
982 rc = errno;
983 if (interface)
984 unmap_interface(domid, interface);
985 errno = rc;
986 return NULL;
987 }
988 domain->interface = interface;
989
990 if (is_master_domain)
991 setup_structure(restore);
992
993 /* Now domain belongs to its connection. */
994 talloc_steal(domain->conn, domain);
995
996 if (!is_master_domain && !restore)
997 fire_special_watches("@introduceDomain");
998 } else {
999 /* Use XS_INTRODUCE for recreating the xenbus event-channel. */
1000 if (domain->port)
1001 xenevtchn_unbind(xce_handle, domain->port);
1002 rc = xenevtchn_bind_interdomain(xce_handle, domid, port);
1003 domain->port = (rc == -1) ? 0 : rc;
1004 }
1005
1006 return domain;
1007 }
1008
1009 /* domid, gfn, evtchn, path */
1010 int do_introduce(const void *ctx, struct connection *conn,
1011 struct buffered_data *in)
1012 {
1013 struct domain *domain;
1014 const char *vec[3];
1015 unsigned int domid;
1016 evtchn_port_t port;
1017
1018 if (get_strings(in, vec, ARRAY_SIZE(vec)) < ARRAY_SIZE(vec))
1019 return EINVAL;
1020
1021 domid = atoi(vec[0]);
1022 /* Ignore the gfn, we don't need it. */
1023 port = atoi(vec[2]);
1024
1025 /* Sanity check args. */
1026 if (port <= 0)
1027 return EINVAL;
1028
1029 domain = introduce_domain(ctx, domid, port, false);
1030 if (!domain)
1031 return errno;
1032
1033 domain_conn_reset(domain);
1034
1035 if (domain->interface != NULL &&
1036 domain->interface->connection == XENSTORE_RECONNECT) {
1037 /* Notify the domain that xenstore is available */
1038 domain->interface->connection = XENSTORE_CONNECTED;
1039 xenevtchn_notify(xce_handle, domain->port);
1040 }
1041
1042 send_ack(conn, XS_INTRODUCE);
1043
1044 return 0;
1045 }
1046
1047 static struct domain *find_connected_domain(unsigned int domid)
1048 {
1049 struct domain *domain;
1050
1051 domain = find_domain_by_domid(domid);
1052 if (!domain)
1053 return ERR_PTR(-ENOENT);
1054 if (!domain->conn)
1055 return ERR_PTR(-EINVAL);
1056 return domain;
1057 }
1058
1059 int do_set_target(const void *ctx, struct connection *conn,
1060 struct buffered_data *in)
1061 {
1062 const char *vec[2];
1063 unsigned int domid, tdomid;
1064 struct domain *domain, *tdomain;
1065 if (get_strings(in, vec, ARRAY_SIZE(vec)) < ARRAY_SIZE(vec))
1066 return EINVAL;
1067
1068 domid = atoi(vec[0]);
1069 tdomid = atoi(vec[1]);
1070
1071 domain = find_connected_domain(domid);
1072 if (IS_ERR(domain))
1073 return -PTR_ERR(domain);
1074
1075 tdomain = find_connected_domain(tdomid);
1076 if (IS_ERR(tdomain))
1077 return -PTR_ERR(tdomain);
1078
1079 talloc_reference(domain->conn, tdomain->conn);
1080 domain->conn->target = tdomain->conn;
1081
1082 send_ack(conn, XS_SET_TARGET);
1083
1084 return 0;
1085 }
1086
1087 static struct domain *onearg_domain(struct connection *conn,
1088 struct buffered_data *in)
1089 {
1090 const char *domid_str = onearg(in);
1091 unsigned int domid;
1092
1093 if (!domid_str)
1094 return ERR_PTR(-EINVAL);
1095
1096 domid = atoi(domid_str);
1097 if (domid == dom0_domid)
1098 return ERR_PTR(-EINVAL);
1099
1100 return find_connected_domain(domid);
1101 }
1102
1103 /* domid */
1104 int do_release(const void *ctx, struct connection *conn,
1105 struct buffered_data *in)
1106 {
1107 struct domain *domain;
1108
1109 domain = onearg_domain(conn, in);
1110 if (IS_ERR(domain))
1111 return -PTR_ERR(domain);
1112
1113 /* Avoid triggering watch events when the domain's nodes are deleted. */
1114 conn_delete_all_watches(domain->conn);
1115
1116 talloc_free(domain->conn);
1117
1118 send_ack(conn, XS_RELEASE);
1119
1120 return 0;
1121 }
1122
1123 int do_resume(const void *ctx, struct connection *conn,
1124 struct buffered_data *in)
1125 {
1126 struct domain *domain;
1127
1128 domain = onearg_domain(conn, in);
1129 if (IS_ERR(domain))
1130 return -PTR_ERR(domain);
1131
1132 domain->shutdown = false;
1133
1134 send_ack(conn, XS_RESUME);
1135
1136 return 0;
1137 }
1138
1139 int do_get_domain_path(const void *ctx, struct connection *conn,
1140 struct buffered_data *in)
1141 {
1142 char *path;
1143 const char *domid_str = onearg(in);
1144
1145 if (!domid_str)
1146 return EINVAL;
1147
1148 path = talloc_domain_path(ctx, atoi(domid_str));
1149 if (!path)
1150 return errno;
1151
1152 send_reply(conn, XS_GET_DOMAIN_PATH, path, strlen(path) + 1);
1153
1154 return 0;
1155 }
1156
1157 int do_is_domain_introduced(const void *ctx, struct connection *conn,
1158 struct buffered_data *in)
1159 {
1160 int result;
1161 unsigned int domid;
1162 const char *domid_str = onearg(in);
1163
1164 if (!domid_str)
1165 return EINVAL;
1166
1167 domid = atoi(domid_str);
1168 if (domid == DOMID_SELF)
1169 result = 1;
1170 else
1171 result = (find_domain_by_domid(domid) != NULL);
1172
1173 send_reply(conn, XS_IS_DOMAIN_INTRODUCED, result ? "T" : "F", 2);
1174
1175 return 0;
1176 }
1177
1178 /* Allow guest to reset all watches */
1179 int do_reset_watches(const void *ctx, struct connection *conn,
1180 struct buffered_data *in)
1181 {
1182 conn_delete_all_watches(conn);
1183 conn_delete_all_transactions(conn);
1184
1185 send_ack(conn, XS_RESET_WATCHES);
1186
1187 return 0;
1188 }
1189
1190 static int close_xc_handle(void *_handle)
1191 {
1192 xc_interface_close(*(xc_interface**)_handle);
1193 return 0;
1194 }
1195
1196 static int close_xgt_handle(void *_handle)
1197 {
1198 xengnttab_close(*(xengnttab_handle **)_handle);
1199 return 0;
1200 }
1201
1202 /* Returns the implicit path of a connection (only domains have this) */
1203 const char *get_implicit_path(const struct connection *conn)
1204 {
1205 if (!conn->domain)
1206 return "/local/domain/0";
1207 return conn->domain->path;
1208 }
1209
1210 void dom0_init(void)
1211 {
1212 evtchn_port_t port;
1213 struct domain *dom0;
1214
1215 port = get_xenbus_evtchn();
1216 if (port == -1)
1217 barf_perror("Failed to initialize dom0 port");
1218
1219 dom0 = introduce_domain(NULL, xenbus_master_domid(), port, false);
1220 if (!dom0)
1221 barf_perror("Failed to initialize dom0");
1222
1223 xenevtchn_notify(xce_handle, dom0->port);
1224 }
1225
1226 void stubdom_init(void)
1227 {
1228 #ifdef __MINIOS__
1229 struct domain *stubdom;
1230
1231 if (stub_domid < 0)
1232 return;
1233
1234 stubdom = introduce_domain(NULL, stub_domid, xenbus_evtchn, false);
1235 if (!stubdom)
1236 barf_perror("Failed to initialize stubdom");
1237
1238 xenevtchn_notify(xce_handle, stubdom->port);
1239
1240 mount_9pfs();
1241 #endif
1242 }
1243
1244 static unsigned int domhash_fn(const void *k)
1245 {
1246 return *(const unsigned int *)k;
1247 }
1248
1249 static int domeq_fn(const void *key1, const void *key2)
1250 {
1251 return *(const unsigned int *)key1 == *(const unsigned int *)key2;
1252 }
1253
1254 void domain_early_init(void)
1255 {
1256 /* Start with a random rather low domain count for the hashtable. */
1257 domhash = create_hashtable(NULL, "domains", domhash_fn, domeq_fn, 0);
1258 if (!domhash)
1259 barf_perror("Failed to allocate domain hashtable");
1260
1261 xc_handle = talloc(talloc_autofree_context(), xc_interface*);
1262 if (!xc_handle)
1263 barf_perror("Failed to allocate domain handle");
1264
1265 *xc_handle = xc_interface_open(0,0,0);
1266 if (!*xc_handle)
1267 barf_perror("Failed to open connection to hypervisor");
1268
1269 talloc_set_destructor(xc_handle, close_xc_handle);
1270
1271 xgt_handle = talloc(talloc_autofree_context(), xengnttab_handle*);
1272 if (!xgt_handle)
1273 barf_perror("Failed to allocate domain gnttab handle");
1274
1275 *xgt_handle = xengnttab_open(NULL, 0);
1276 if (*xgt_handle == NULL)
1277 barf_perror("Failed to open connection to gnttab");
1278
1279 /*
1280 * Allow max number of domains for mappings. We allow one grant per
1281 * domain so the theoretical maximum is DOMID_FIRST_RESERVED.
1282 */
1283 xengnttab_set_max_grants(*xgt_handle, DOMID_FIRST_RESERVED);
1284
1285 talloc_set_destructor(xgt_handle, close_xgt_handle);
1286 }
1287
1288 void domain_init(int evtfd)
1289 {
1290 int rc;
1291
1292 if (evtfd < 0)
1293 xce_handle = xenevtchn_open(NULL, XENEVTCHN_NO_CLOEXEC);
1294 else
1295 xce_handle = xenevtchn_fdopen(NULL, evtfd, 0);
1296
1297 if (xce_handle == NULL)
1298 barf_perror("Failed to open evtchn device");
1299
1300 if ((rc = xenevtchn_bind_virq(xce_handle, VIRQ_DOM_EXC)) == -1)
1301 barf_perror("Failed to bind to domain exception virq port");
1302 virq_port = rc;
1303 }
1304
1305 void domain_deinit(void)
1306 {
1307 if (virq_port)
1308 xenevtchn_unbind(xce_handle, virq_port);
1309 }
1310
1311 /*
1312 * Check whether a domain was created before or after a specific generation
1313 * count (used for testing whether a node permission is older than a domain).
1314 *
1315 * Return values:
1316 * false: domain has higher generation count (it is younger than a node with
1317 * the given count), or domain isn't existing any longer
1318 * true: domain is older than the node
1319 */
1320 static bool chk_domain_generation(unsigned int domid, uint64_t gen)
1321 {
1322 struct domain *d;
1323
1324 d = find_domain_struct(domid);
1325
1326 return d && d->generation <= gen;
1327 }
1328
1329 /*
1330 * Allocate all missing struct domain referenced by a permission set.
1331 * Any permission entries for not existing domains will be marked to be
1332 * ignored.
1333 */
1334 int domain_alloc_permrefs(struct node_perms *perms)
1335 {
1336 unsigned int i, domid;
1337 struct domain *d;
1338 xc_domaininfo_t dominfo;
1339
1340 for (i = 0; i < perms->num; i++) {
1341 domid = perms->p[i].id;
1342 d = find_domain_struct(domid);
1343 if (!d) {
1344 if (!get_domain_info(domid, &dominfo))
1345 perms->p[i].perms |= XS_PERM_IGNORE;
1346 else if (!alloc_domain(NULL, domid))
1347 return ENOMEM;
1348 }
1349 }
1350
1351 return 0;
1352 }
1353
1354 /*
1355 * Remove permissions for no longer existing domains in order to avoid a new
1356 * domain with the same domid inheriting the permissions.
1357 */
1358 int domain_adjust_node_perms(struct node *node)
1359 {
1360 unsigned int i;
1361 struct xs_permissions *perms = node->perms;
1362 bool copied = false;
1363
1364 for (i = 1; i < node->hdr.num_perms; i++) {
1365 if ((perms[i].perms & XS_PERM_IGNORE) ||
1366 chk_domain_generation(perms[i].id, node->hdr.generation))
1367 continue;
1368
1369 /*
1370 * Don't do a in-place modification, as the node might
1371 * reference data directly in the data base, which we don't
1372 * want to modify.
1373 */
1374 if (!copied) {
1375 perms = talloc_memdup(node, node->perms,
1376 node->hdr.num_perms * sizeof(*perms));
1377 if (!perms)
1378 return ENOMEM;
1379 node->perms = perms;
1380 copied = true;
1381 }
1382
1383 perms[i].perms |= XS_PERM_IGNORE;
1384 }
1385
1386 return 0;
1387 }
1388
1389 static void domain_acc_valid_max(struct domain *d, enum accitem what,
1390 unsigned int val)
1391 {
1392 assert(what < ARRAY_SIZE(d->acc));
1393 assert(what < ARRAY_SIZE(hard_quotas));
1394
1395 if (val > d->acc[what].max)
1396 d->acc[what].max = val;
1397 if (val > hard_quotas[what].max && domid_is_unprivileged(d->domid))
1398 hard_quotas[what].max = val;
1399 }
1400
1401 static int domain_acc_add_valid(struct domain *d, enum accitem what, int add)
1402 {
1403 unsigned int val;
1404
1405 assert(what < ARRAY_SIZE(d->acc));
1406
1407 if ((add < 0 && -add > d->acc[what].val) ||
1408 (add > 0 && (INT_MAX - d->acc[what].val) < add)) {
1409 /*
1410 * In a transaction when a node is being added/removed AND the
1411 * same node has been added/removed outside the transaction in
1412 * parallel, the resulting value will be wrong. This is no
1413 * problem, as the transaction will fail due to the resulting
1414 * conflict.
1415 */
1416 return (add < 0) ? 0 : INT_MAX;
1417 }
1418
1419 val = d->acc[what].val + add;
1420 domain_acc_valid_max(d, what, val);
1421
1422 return val;
1423 }
1424
1425 static int domain_acc_add(struct connection *conn, unsigned int domid,
1426 enum accitem what, int add, bool no_dom_alloc)
1427 {
1428 struct domain *d;
1429 struct changed_domain *cd;
1430 struct list_head *head;
1431 int ret;
1432
1433 if (conn && domid == conn->id && conn->domain)
1434 d = conn->domain;
1435 else if (no_dom_alloc) {
1436 d = find_domain_struct(domid);
1437 if (!d) {
1438 errno = ENOENT;
1439 corrupt(conn, "Missing domain %u\n", domid);
1440 return -1;
1441 }
1442 } else {
1443 d = find_or_alloc_existing_domain(domid);
1444 if (!d) {
1445 errno = ENOMEM;
1446 return -1;
1447 }
1448 }
1449
1450 /* Temporary accounting data until final commit? */
1451 if (conn && conn->in && what < ACC_REQ_N) {
1452 /* Consider transaction local data. */
1453 ret = 0;
1454 if (conn->transaction && what < ACC_TR_N) {
1455 head = transaction_get_changed_domains(
1456 conn->transaction);
1457 cd = acc_find_changed_domain(head, domid);
1458 if (cd)
1459 ret = cd->acc[what];
1460 }
1461 ret += acc_add_changed_dom(conn->in, &conn->acc_list, what,
1462 add, domid);
1463 return errno ? -1 : domain_acc_add_valid(d, what, ret);
1464 }
1465
1466 if (conn && conn->transaction && what < ACC_TR_N) {
1467 head = transaction_get_changed_domains(conn->transaction);
1468 ret = acc_add_changed_dom(conn->transaction, head, what,
1469 add, domid);
1470 if (errno) {
1471 fail_transaction(conn->transaction);
1472 return -1;
1473 }
1474 return domain_acc_add_valid(d, what, ret);
1475 }
1476
1477 trace_acc("global change domid %u: what=%u %u add %d\n", domid, what,
1478 d->acc[what].val, add);
1479 d->acc[what].val = domain_acc_add_valid(d, what, add);
1480
1481 return d->acc[what].val;
1482 }
1483
1484 void acc_drop(struct connection *conn)
1485 {
1486 struct changed_domain *cd;
1487
1488 while ((cd = list_top(&conn->acc_list, struct changed_domain, list))) {
1489 list_del(&cd->list);
1490 talloc_free(cd);
1491 }
1492 }
1493
1494 void acc_commit(struct connection *conn)
1495 {
1496 struct changed_domain *cd;
1497 enum accitem what;
1498 struct buffered_data *in = conn->in;
1499
1500 /*
1501 * Make sure domain_acc_add() below can't add additional data to
1502 * to be committed accounting records.
1503 */
1504 conn->in = NULL;
1505
1506 while ((cd = list_top(&conn->acc_list, struct changed_domain, list))) {
1507 list_del(&cd->list);
1508 for (what = 0; what < ACC_REQ_N; what++)
1509 if (cd->acc[what])
1510 domain_acc_add(conn, cd->domid, what,
1511 cd->acc[what], true);
1512
1513 talloc_free(cd);
1514 }
1515
1516 conn->in = in;
1517 }
1518
1519 static int domain_reset_global_acc_sub(const void *k, void *v, void *arg)
1520 {
1521 struct domain *d = v;
1522 unsigned int i;
1523
1524 for (i = 0; i < ACC_N; i++)
1525 d->acc[i].max = d->acc[i].val;
1526
1527 return 0;
1528 }
1529
1530 void domain_reset_global_acc(void)
1531 {
1532 unsigned int i;
1533
1534 for (i = 0; i < ACC_N; i++)
1535 hard_quotas[i].max = 0;
1536
1537 /* Set current max values seen. */
1538 hashtable_iterate(domhash, domain_reset_global_acc_sub, NULL);
1539 }
1540
1541 bool domain_max_chk(const struct connection *conn, enum accitem what,
1542 unsigned int val)
1543 {
1544 if (!conn || !conn->domain)
1545 return false;
1546
1547 if (domain_is_unprivileged(conn) && val > hard_quotas[what].val)
1548 return true;
1549
1550 domain_acc_valid_max(conn->domain, what, val);
1551
1552 return false;
1553 }
1554
1555 int domain_nbentry_inc(struct connection *conn, unsigned int domid)
1556 {
1557 return (domain_acc_add(conn, domid, ACC_NODES, 1, false) < 0)
1558 ? errno : 0;
1559 }
1560
1561 int domain_nbentry_dec(struct connection *conn, unsigned int domid)
1562 {
1563 return (domain_acc_add(conn, domid, ACC_NODES, -1, true) < 0)
1564 ? errno : 0;
1565 }
1566
1567 int domain_nbentry_fix(unsigned int domid, int num, bool update)
1568 {
1569 int ret;
1570
1571 ret = domain_acc_add(NULL, domid, ACC_NODES, update ? num : 0, update);
1572 if (ret < 0 || update)
1573 return ret;
1574
1575 return domid_is_unprivileged(domid) ? ret + num : 0;
1576 }
1577
1578 unsigned int domain_nbentry(struct connection *conn)
1579 {
1580 return domain_is_unprivileged(conn)
1581 ? domain_acc_add(conn, conn->id, ACC_NODES, 0, true) : 0;
1582 }
1583
1584 static bool domain_chk_quota(struct connection *conn, unsigned int mem)
1585 {
1586 time_t now;
1587 struct domain *domain;
1588
1589 if (!conn || !domid_is_unprivileged(conn->id) ||
1590 conn->is_ignored)
1591 return false;
1592
1593 domain = conn->domain;
1594 now = time(NULL);
1595
1596 if (mem >= hard_quotas[ACC_MEM].val && hard_quotas[ACC_MEM].val) {
1597 if (domain->hard_quota_reported)
1598 return true;
1599 syslog(LOG_ERR, "Domain %u exceeds hard memory quota, Xenstore interface to domain stalled\n",
1600 domain->domid);
1601 domain->mem_last_msg = now;
1602 domain->hard_quota_reported = true;
1603 return true;
1604 }
1605
1606 if (now - domain->mem_last_msg >= MEM_WARN_MINTIME_SEC) {
1607 if (domain->hard_quota_reported) {
1608 domain->mem_last_msg = now;
1609 domain->hard_quota_reported = false;
1610 syslog(LOG_INFO, "Domain %u below hard memory quota again\n",
1611 domain->domid);
1612 }
1613 if (mem >= soft_quotas[ACC_MEM].val &&
1614 soft_quotas[ACC_MEM].val && !domain->soft_quota_reported) {
1615 domain->mem_last_msg = now;
1616 domain->soft_quota_reported = true;
1617 syslog(LOG_WARNING, "Domain %u exceeds soft memory quota\n",
1618 domain->domid);
1619 }
1620 if (mem < soft_quotas[ACC_MEM].val &&
1621 domain->soft_quota_reported) {
1622 domain->mem_last_msg = now;
1623 domain->soft_quota_reported = false;
1624 syslog(LOG_INFO, "Domain %u below soft memory quota again\n",
1625 domain->domid);
1626 }
1627
1628 }
1629
1630 return false;
1631 }
1632
1633 int domain_memory_add(struct connection *conn, unsigned int domid, int mem,
1634 bool no_quota_check)
1635 {
1636 int ret;
1637
1638 ret = domain_acc_add(conn, domid, ACC_MEM, 0, true);
1639 if (ret < 0)
1640 return -ret;
1641
1642 /*
1643 * domain_chk_quota() will print warning and also store whether the
1644 * soft/hard quota has been hit. So check no_quota_check *after*.
1645 */
1646 if (domain_chk_quota(conn, ret + mem) && !no_quota_check)
1647 return ENOMEM;
1648
1649 /*
1650 * The domain the memory is to be accounted for should always exist,
1651 * as accounting is done either for a domain related to the current
1652 * connection, or for the domain owning a node (which is always
1653 * existing, as the owner of the node is tested to exist and deleted
1654 * or replaced by domid 0 if not).
1655 * So not finding the related domain MUST be an error in the data base.
1656 */
1657 domain_acc_add(conn, domid, ACC_MEM, mem, true);
1658
1659 return 0;
1660 }
1661
1662 void domain_watch_inc(struct connection *conn)
1663 {
1664 domain_acc_add(conn, conn->id, ACC_WATCH, 1, true);
1665 }
1666
1667 void domain_watch_dec(struct connection *conn)
1668 {
1669 domain_acc_add(conn, conn->id, ACC_WATCH, -1, true);
1670 }
1671
1672 int domain_watch(struct connection *conn)
1673 {
1674 return (domain_is_unprivileged(conn))
1675 ? domain_acc_add(conn, conn->id, ACC_WATCH, 0, true)
1676 : 0;
1677 }
1678
1679 void domain_outstanding_inc(struct connection *conn)
1680 {
1681 domain_acc_add(conn, conn->id, ACC_OUTST, 1, true);
1682 }
1683
1684 void domain_outstanding_dec(struct connection *conn, unsigned int domid)
1685 {
1686 domain_acc_add(conn, domid, ACC_OUTST, -1, true);
1687 }
1688
1689 void domain_transaction_inc(struct connection *conn)
1690 {
1691 domain_acc_add(conn, conn->id, ACC_TRANS, 1, true);
1692 }
1693
1694 void domain_transaction_dec(struct connection *conn)
1695 {
1696 domain_acc_add(conn, conn->id, ACC_TRANS, -1, true);
1697 }
1698
1699 unsigned int domain_transaction_get(struct connection *conn)
1700 {
1701 return (domain_is_unprivileged(conn))
1702 ? domain_acc_add(conn, conn->id, ACC_TRANS, 0, true)
1703 : 0;
1704 }
1705
1706 const char *dump_state_connections(FILE *fp)
1707 {
1708 const char *ret = NULL;
1709 unsigned int conn_id = 1;
1710 struct xs_state_connection sc;
1711 struct xs_state_record_header head;
1712 struct connection *c;
1713
1714 list_for_each_entry(c, &connections, list) {
1715 head.type = XS_STATE_TYPE_CONN;
1716 head.length = sizeof(sc);
1717
1718 sc.conn_id = conn_id++;
1719 sc.pad = 0;
1720 memset(&sc.spec, 0, sizeof(sc.spec));
1721 if (c->domain) {
1722 sc.conn_type = XS_STATE_CONN_TYPE_RING;
1723 sc.spec.ring.domid = c->id;
1724 sc.spec.ring.tdomid = c->target ? c->target->id
1725 : DOMID_INVALID;
1726 sc.spec.ring.evtchn = c->domain->port;
1727 } else {
1728 sc.conn_type = XS_STATE_CONN_TYPE_SOCKET;
1729 sc.spec.socket_fd = c->fd;
1730 }
1731
1732 ret = dump_state_buffered_data(NULL, c, &sc);
1733 if (ret)
1734 return ret;
1735 head.length += sc.data_in_len + sc.data_out_len;
1736 head.length = ROUNDUP(head.length, 3);
1737 if (fwrite(&head, sizeof(head), 1, fp) != 1)
1738 return "Dump connection state error";
1739 if (fwrite(&sc, offsetof(struct xs_state_connection, data),
1740 1, fp) != 1)
1741 return "Dump connection state error";
1742 ret = dump_state_buffered_data(fp, c, NULL);
1743 if (ret)
1744 return ret;
1745 ret = dump_state_align(fp);
1746 if (ret)
1747 return ret;
1748
1749 ret = dump_state_watches(fp, c, sc.conn_id);
1750 if (ret)
1751 return ret;
1752 }
1753
1754 return ret;
1755 }
1756
1757 void read_state_connection(const void *ctx, const void *state)
1758 {
1759 const struct xs_state_connection *sc = state;
1760 struct connection *conn;
1761 struct domain *domain, *tdomain;
1762
1763 if (sc->conn_type == XS_STATE_CONN_TYPE_SOCKET) {
1764 conn = add_socket_connection(sc->spec.socket_fd);
1765 } else {
1766 domain = introduce_domain(ctx, sc->spec.ring.domid,
1767 sc->spec.ring.evtchn, true);
1768 if (!domain)
1769 barf("domain allocation error");
1770
1771 conn = domain->conn;
1772
1773 /*
1774 * We may not have been able to restore the domain (for
1775 * instance because it revoked the Xenstore grant). We need
1776 * to keep it around to send @releaseDomain when it is
1777 * dead. So mark it as ignored.
1778 */
1779 if (!domain->port || !domain->interface)
1780 ignore_connection(conn, XENSTORE_ERROR_COMM);
1781
1782 if (sc->spec.ring.tdomid != DOMID_INVALID) {
1783 tdomain = find_or_alloc_domain(ctx,
1784 sc->spec.ring.tdomid);
1785 if (!tdomain)
1786 barf("target domain allocation error");
1787 talloc_reference(domain->conn, tdomain->conn);
1788 domain->conn->target = tdomain->conn;
1789 }
1790 }
1791
1792 conn->conn_id = sc->conn_id;
1793
1794 read_state_buffered_data(ctx, conn, sc);
1795 }
1796
1797 struct domain_acc {
1798 unsigned int domid;
1799 int nodes;
1800 };
1801
1802 static int domain_check_acc_init_sub(const void *k, void *v, void *arg)
1803 {
1804 struct hashtable *domains = arg;
1805 struct domain *d = v;
1806 struct domain_acc *dom;
1807
1808 dom = talloc_zero(NULL, struct domain_acc);
1809 if (!dom)
1810 return -1;
1811
1812 dom->domid = d->domid;
1813 /*
1814 * Set the initial value to the negative one of the current domain.
1815 * If everything is correct incrementing the value for each node will
1816 * result in dom->nodes being 0 at the end.
1817 */
1818 dom->nodes = -d->acc[ACC_NODES].val;
1819
1820 if (hashtable_add(domains, &dom->domid, dom)) {
1821 talloc_free(dom);
1822 return -1;
1823 }
1824
1825 return 0;
1826 }
1827
1828 struct hashtable *domain_check_acc_init(void)
1829 {
1830 struct hashtable *domains;
1831
1832 domains = create_hashtable(NULL, "domain_check", domhash_fn, domeq_fn,
1833 HASHTABLE_FREE_VALUE);
1834 if (!domains)
1835 return NULL;
1836
1837 if (hashtable_iterate(domhash, domain_check_acc_init_sub, domains)) {
1838 hashtable_destroy(domains);
1839 return NULL;
1840 }
1841
1842 return domains;
1843 }
1844
1845 void domain_check_acc_add(const struct node *node, struct hashtable *domains)
1846 {
1847 struct domain_acc *dom;
1848 unsigned int domid;
1849
1850 domid = get_node_owner(node);
1851 dom = hashtable_search(domains, &domid);
1852 if (!dom)
1853 log("Node %s owned by unknown domain %u", node->name, domid);
1854 else
1855 dom->nodes++;
1856 }
1857
1858 static int domain_check_acc_cb(const void *k, void *v, void *arg)
1859 {
1860 struct domain_acc *dom = v;
1861 struct domain *d;
1862
1863 if (!dom->nodes)
1864 return 0;
1865
1866 log("Correct accounting data for domain %u: nodes are %d off",
1867 dom->domid, dom->nodes);
1868
1869 d = find_domain_struct(dom->domid);
1870 if (!d)
1871 return 0;
1872
1873 d->acc[ACC_NODES].val += dom->nodes;
1874
1875 return 0;
1876 }
1877
1878 void domain_check_acc(struct hashtable *domains)
1879 {
1880 hashtable_iterate(domains, domain_check_acc_cb, NULL);
1881 }
1882
1883 /*
1884 * Local variables:
1885 * mode: C
1886 * c-file-style: "linux"
1887 * indent-tabs-mode: t
1888 * c-basic-offset: 8
1889 * tab-width: 8
1890 * End:
1891 */