]> git.saurik.com Git - apple/xnu.git/blob - osfmk/kern/ledger.c
983e51b9c522d9c82431ca05cffdeb4a4da6fc9f
[apple/xnu.git] / osfmk / kern / ledger.c
1 /*
2 * Copyright (c) 2010 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /*
29 * @OSF_COPYRIGHT@
30 */
31
32 #include <kern/kern_types.h>
33 #include <kern/ledger.h>
34 #include <kern/kalloc.h>
35 #include <kern/task.h>
36 #include <kern/thread.h>
37
38 #include <kern/processor.h>
39 #include <kern/machine.h>
40 #include <kern/queue.h>
41 #include <kern/policy_internal.h>
42
43 #include <sys/errno.h>
44
45 #include <libkern/OSAtomic.h>
46 #include <mach/mach_types.h>
47
48 /*
49 * Ledger entry flags. Bits in second nibble (masked by 0xF0) are used for
50 * ledger actions (LEDGER_ACTION_BLOCK, etc).
51 */
52 #define LF_ENTRY_ACTIVE 0x0001 /* entry is active if set */
53 #define LF_WAKE_NEEDED 0x0100 /* one or more threads are asleep */
54 #define LF_WAKE_INPROGRESS 0x0200 /* the wait queue is being processed */
55 #define LF_REFILL_SCHEDULED 0x0400 /* a refill timer has been set */
56 #define LF_REFILL_INPROGRESS 0x0800 /* the ledger is being refilled */
57 #define LF_CALLED_BACK 0x1000 /* callback was called for balance in deficit */
58 #define LF_WARNED 0x2000 /* callback was called for balance warning */
59 #define LF_TRACKING_MAX 0x4000 /* track max balance over user-specfied time */
60 #define LF_PANIC_ON_NEGATIVE 0x8000 /* panic if it goes negative */
61 #define LF_TRACK_CREDIT_ONLY 0x10000 /* only update "credit" */
62
63 /* Determine whether a ledger entry exists and has been initialized and active */
64 #define ENTRY_VALID(l, e) \
65 (((l) != NULL) && ((e) >= 0) && ((e) < (l)->l_size) && \
66 (((l)->l_entries[e].le_flags & LF_ENTRY_ACTIVE) == LF_ENTRY_ACTIVE))
67
68 #define ASSERT(a) assert(a)
69
70 #ifdef LEDGER_DEBUG
71 int ledger_debug = 0;
72
73 #define lprintf(a) if (ledger_debug) { \
74 printf("%lld ", abstime_to_nsecs(mach_absolute_time() / 1000000)); \
75 printf a ; \
76 }
77 #else
78 #define lprintf(a)
79 #endif
80
81 struct ledger_callback {
82 ledger_callback_t lc_func;
83 const void *lc_param0;
84 const void *lc_param1;
85 };
86
87 struct entry_template {
88 char et_key[LEDGER_NAME_MAX];
89 char et_group[LEDGER_NAME_MAX];
90 char et_units[LEDGER_NAME_MAX];
91 uint32_t et_flags;
92 struct ledger_callback *et_callback;
93 };
94
95 lck_grp_t ledger_lck_grp;
96
97 /*
98 * Modifying the reference count, table size, or table contents requires
99 * holding the lt_lock. Modfying the table address requires both lt_lock
100 * and setting the inuse bit. This means that the lt_entries field can be
101 * safely dereferenced if you hold either the lock or the inuse bit. The
102 * inuse bit exists solely to allow us to swap in a new, larger entries
103 * table without requiring a full lock to be acquired on each lookup.
104 * Accordingly, the inuse bit should never be held for longer than it takes
105 * to extract a value from the table - i.e., 2 or 3 memory references.
106 */
107 struct ledger_template {
108 const char *lt_name;
109 int lt_refs;
110 int lt_cnt;
111 int lt_table_size;
112 volatile uint32_t lt_inuse;
113 lck_mtx_t lt_lock;
114 struct entry_template *lt_entries;
115 };
116
117 #define template_lock(template) lck_mtx_lock(&(template)->lt_lock)
118 #define template_unlock(template) lck_mtx_unlock(&(template)->lt_lock)
119
120 #define TEMPLATE_INUSE(s, t) { \
121 s = splsched(); \
122 while (OSCompareAndSwap(0, 1, &((t)->lt_inuse))) \
123 ; \
124 }
125
126 #define TEMPLATE_IDLE(s, t) { \
127 (t)->lt_inuse = 0; \
128 splx(s); \
129 }
130
131 /*
132 * Use 2 "tocks" to track the rolling maximum balance of a ledger entry.
133 */
134 #define NTOCKS 2
135 /*
136 * The explicit alignment is to ensure that atomic operations don't panic
137 * on ARM.
138 */
139 struct ledger_entry {
140 volatile uint32_t le_flags;
141 ledger_amount_t le_limit;
142 ledger_amount_t le_warn_level;
143 volatile ledger_amount_t le_credit __attribute__((aligned(8)));
144 volatile ledger_amount_t le_debit __attribute__((aligned(8)));
145 union {
146 struct {
147 /*
148 * XXX - the following two fields can go away if we move all of
149 * the refill logic into process policy
150 */
151 uint64_t le_refill_period;
152 uint64_t le_last_refill;
153 } le_refill;
154 struct _le_peak {
155 uint32_t le_max; /* Lower 32-bits of observed max balance */
156 uint32_t le_time; /* time when this peak was observed */
157 } le_peaks[NTOCKS];
158 } _le;
159 } __attribute__((aligned(8)));
160
161 struct ledger {
162 uint64_t l_id;
163 int32_t l_refs;
164 int32_t l_size;
165 struct ledger_template *l_template;
166 struct ledger_entry l_entries[0] __attribute__((aligned(8)));
167 };
168
169 static int ledger_cnt = 0;
170 /* ledger ast helper functions */
171 static uint32_t ledger_check_needblock(ledger_t l, uint64_t now);
172 static kern_return_t ledger_perform_blocking(ledger_t l);
173 static uint32_t flag_set(volatile uint32_t *flags, uint32_t bit);
174 static uint32_t flag_clear(volatile uint32_t *flags, uint32_t bit);
175
176 static void ledger_entry_check_new_balance(ledger_t ledger, int entry,
177 struct ledger_entry *le);
178
179 #if 0
180 static void
181 debug_callback(const void *p0, __unused const void *p1)
182 {
183 printf("ledger: resource exhausted [%s] for task %p\n",
184 (const char *)p0, p1);
185 }
186 #endif
187
188 /************************************/
189
190 static uint64_t
191 abstime_to_nsecs(uint64_t abstime)
192 {
193 uint64_t nsecs;
194
195 absolutetime_to_nanoseconds(abstime, &nsecs);
196 return (nsecs);
197 }
198
199 static uint64_t
200 nsecs_to_abstime(uint64_t nsecs)
201 {
202 uint64_t abstime;
203
204 nanoseconds_to_absolutetime(nsecs, &abstime);
205 return (abstime);
206 }
207
208 void
209 ledger_init(void)
210 {
211 lck_grp_init(&ledger_lck_grp, "ledger", LCK_GRP_ATTR_NULL);
212 }
213
214 ledger_template_t
215 ledger_template_create(const char *name)
216 {
217 ledger_template_t template;
218
219 template = (ledger_template_t)kalloc(sizeof (*template));
220 if (template == NULL)
221 return (NULL);
222
223 template->lt_name = name;
224 template->lt_refs = 1;
225 template->lt_cnt = 0;
226 template->lt_table_size = 1;
227 template->lt_inuse = 0;
228 lck_mtx_init(&template->lt_lock, &ledger_lck_grp, LCK_ATTR_NULL);
229
230 template->lt_entries = (struct entry_template *)
231 kalloc(sizeof (struct entry_template) * template->lt_table_size);
232 if (template->lt_entries == NULL) {
233 kfree(template, sizeof (*template));
234 template = NULL;
235 }
236
237 return (template);
238 }
239
240 void
241 ledger_template_dereference(ledger_template_t template)
242 {
243 template_lock(template);
244 template->lt_refs--;
245 template_unlock(template);
246
247 if (template->lt_refs == 0)
248 kfree(template, sizeof (*template));
249 }
250
251 /*
252 * Add a new entry to the list of entries in a ledger template. There is
253 * currently no mechanism to remove an entry. Implementing such a mechanism
254 * would require us to maintain per-entry reference counts, which we would
255 * prefer to avoid if possible.
256 */
257 int
258 ledger_entry_add(ledger_template_t template, const char *key,
259 const char *group, const char *units)
260 {
261 int idx;
262 struct entry_template *et;
263
264 if ((key == NULL) || (strlen(key) >= LEDGER_NAME_MAX))
265 return (-1);
266
267 template_lock(template);
268
269 /* If the table is full, attempt to double its size */
270 if (template->lt_cnt == template->lt_table_size) {
271 struct entry_template *new_entries, *old_entries;
272 int old_cnt, old_sz;
273 spl_t s;
274
275 old_cnt = template->lt_table_size;
276 old_sz = (int)(old_cnt * sizeof (struct entry_template));
277 new_entries = kalloc(old_sz * 2);
278 if (new_entries == NULL) {
279 template_unlock(template);
280 return (-1);
281 }
282 memcpy(new_entries, template->lt_entries, old_sz);
283 memset(((char *)new_entries) + old_sz, 0, old_sz);
284 template->lt_table_size = old_cnt * 2;
285
286 old_entries = template->lt_entries;
287
288 TEMPLATE_INUSE(s, template);
289 template->lt_entries = new_entries;
290 TEMPLATE_IDLE(s, template);
291
292 kfree(old_entries, old_sz);
293 }
294
295 et = &template->lt_entries[template->lt_cnt];
296 strlcpy(et->et_key, key, LEDGER_NAME_MAX);
297 strlcpy(et->et_group, group, LEDGER_NAME_MAX);
298 strlcpy(et->et_units, units, LEDGER_NAME_MAX);
299 et->et_flags = LF_ENTRY_ACTIVE;
300 et->et_callback = NULL;
301
302 idx = template->lt_cnt++;
303 template_unlock(template);
304
305 return (idx);
306 }
307
308
309 kern_return_t
310 ledger_entry_setactive(ledger_t ledger, int entry)
311 {
312 struct ledger_entry *le;
313
314 if ((ledger == NULL) || (entry < 0) || (entry >= ledger->l_size))
315 return (KERN_INVALID_ARGUMENT);
316
317 le = &ledger->l_entries[entry];
318 if ((le->le_flags & LF_ENTRY_ACTIVE) == 0) {
319 flag_set(&le->le_flags, LF_ENTRY_ACTIVE);
320 }
321 return (KERN_SUCCESS);
322 }
323
324
325 int
326 ledger_key_lookup(ledger_template_t template, const char *key)
327 {
328 int idx;
329
330 template_lock(template);
331 for (idx = 0; idx < template->lt_cnt; idx++)
332 if (template->lt_entries != NULL &&
333 (strcmp(key, template->lt_entries[idx].et_key) == 0))
334 break;
335
336 if (idx >= template->lt_cnt)
337 idx = -1;
338 template_unlock(template);
339
340 return (idx);
341 }
342
343 /*
344 * Create a new ledger based on the specified template. As part of the
345 * ledger creation we need to allocate space for a table of ledger entries.
346 * The size of the table is based on the size of the template at the time
347 * the ledger is created. If additional entries are added to the template
348 * after the ledger is created, they will not be tracked in this ledger.
349 */
350 ledger_t
351 ledger_instantiate(ledger_template_t template, int entry_type)
352 {
353 ledger_t ledger;
354 size_t cnt, sz;
355 int i;
356
357 template_lock(template);
358 template->lt_refs++;
359 cnt = template->lt_cnt;
360 template_unlock(template);
361
362 sz = sizeof(*ledger) + (cnt * sizeof(struct ledger_entry));
363
364 ledger = (ledger_t)kalloc(sz);
365 if (ledger == NULL) {
366 ledger_template_dereference(template);
367 return LEDGER_NULL;
368 }
369
370 ledger->l_template = template;
371 ledger->l_id = ledger_cnt++;
372 ledger->l_refs = 1;
373 ledger->l_size = (int32_t)cnt;
374
375 template_lock(template);
376 assert(ledger->l_size <= template->lt_cnt);
377 for (i = 0; i < ledger->l_size; i++) {
378 struct ledger_entry *le = &ledger->l_entries[i];
379 struct entry_template *et = &template->lt_entries[i];
380
381 le->le_flags = et->et_flags;
382 /* make entry inactive by removing active bit */
383 if (entry_type == LEDGER_CREATE_INACTIVE_ENTRIES)
384 flag_clear(&le->le_flags, LF_ENTRY_ACTIVE);
385 /*
386 * If template has a callback, this entry is opted-in,
387 * by default.
388 */
389 if (et->et_callback != NULL)
390 flag_set(&le->le_flags, LEDGER_ACTION_CALLBACK);
391 le->le_credit = 0;
392 le->le_debit = 0;
393 le->le_limit = LEDGER_LIMIT_INFINITY;
394 le->le_warn_level = LEDGER_LIMIT_INFINITY;
395 le->_le.le_refill.le_refill_period = 0;
396 le->_le.le_refill.le_last_refill = 0;
397 }
398 template_unlock(template);
399
400 return (ledger);
401 }
402
403 static uint32_t
404 flag_set(volatile uint32_t *flags, uint32_t bit)
405 {
406 return (OSBitOrAtomic(bit, flags));
407 }
408
409 static uint32_t
410 flag_clear(volatile uint32_t *flags, uint32_t bit)
411 {
412 return (OSBitAndAtomic(~bit, flags));
413 }
414
415 /*
416 * Take a reference on a ledger
417 */
418 kern_return_t
419 ledger_reference(ledger_t ledger)
420 {
421 if (!LEDGER_VALID(ledger))
422 return (KERN_INVALID_ARGUMENT);
423 OSIncrementAtomic(&ledger->l_refs);
424 return (KERN_SUCCESS);
425 }
426
427 int
428 ledger_reference_count(ledger_t ledger)
429 {
430 if (!LEDGER_VALID(ledger))
431 return (-1);
432
433 return (ledger->l_refs);
434 }
435
436 /*
437 * Remove a reference on a ledger. If this is the last reference,
438 * deallocate the unused ledger.
439 */
440 kern_return_t
441 ledger_dereference(ledger_t ledger)
442 {
443 int v;
444
445 if (!LEDGER_VALID(ledger))
446 return (KERN_INVALID_ARGUMENT);
447
448 v = OSDecrementAtomic(&ledger->l_refs);
449 ASSERT(v >= 1);
450
451 /* Just released the last reference. Free it. */
452 if (v == 1) {
453 kfree(ledger,
454 sizeof(*ledger) + ledger->l_size * sizeof(struct ledger_entry));
455 }
456
457 return (KERN_SUCCESS);
458 }
459
460 /*
461 * Determine whether an entry has exceeded its warning level.
462 */
463 static inline int
464 warn_level_exceeded(struct ledger_entry *le)
465 {
466 ledger_amount_t balance;
467
468 if (le->le_flags & LF_TRACK_CREDIT_ONLY) {
469 assert(le->le_debit == 0);
470 } else {
471 assert((le->le_credit >= 0) && (le->le_debit >= 0));
472 }
473
474 /*
475 * XXX - Currently, we only support warnings for ledgers which
476 * use positive limits.
477 */
478 balance = le->le_credit - le->le_debit;
479 if ((le->le_warn_level != LEDGER_LIMIT_INFINITY) && (balance > le->le_warn_level))
480 return (1);
481 return (0);
482 }
483
484 /*
485 * Determine whether an entry has exceeded its limit.
486 */
487 static inline int
488 limit_exceeded(struct ledger_entry *le)
489 {
490 ledger_amount_t balance;
491
492 if (le->le_flags & LF_TRACK_CREDIT_ONLY) {
493 assert(le->le_debit == 0);
494 } else {
495 assert((le->le_credit >= 0) && (le->le_debit >= 0));
496 }
497
498 balance = le->le_credit - le->le_debit;
499 if ((le->le_limit <= 0) && (balance < le->le_limit))
500 return (1);
501
502 if ((le->le_limit > 0) && (balance > le->le_limit))
503 return (1);
504 return (0);
505 }
506
507 static inline struct ledger_callback *
508 entry_get_callback(ledger_t ledger, int entry)
509 {
510 struct ledger_callback *callback;
511 spl_t s;
512
513 TEMPLATE_INUSE(s, ledger->l_template);
514 callback = ledger->l_template->lt_entries[entry].et_callback;
515 TEMPLATE_IDLE(s, ledger->l_template);
516
517 return (callback);
518 }
519
520 /*
521 * If the ledger value is positive, wake up anybody waiting on it.
522 */
523 static inline void
524 ledger_limit_entry_wakeup(struct ledger_entry *le)
525 {
526 uint32_t flags;
527
528 if (!limit_exceeded(le)) {
529 flags = flag_clear(&le->le_flags, LF_CALLED_BACK);
530
531 while (le->le_flags & LF_WAKE_NEEDED) {
532 flag_clear(&le->le_flags, LF_WAKE_NEEDED);
533 thread_wakeup((event_t)le);
534 }
535 }
536 }
537
538 /*
539 * Refill the coffers.
540 */
541 static void
542 ledger_refill(uint64_t now, ledger_t ledger, int entry)
543 {
544 uint64_t elapsed, period, periods;
545 struct ledger_entry *le;
546 ledger_amount_t balance, due;
547
548 assert(entry >= 0 && entry < ledger->l_size);
549
550 le = &ledger->l_entries[entry];
551
552 assert(le->le_limit != LEDGER_LIMIT_INFINITY);
553
554 if (le->le_flags & LF_TRACK_CREDIT_ONLY) {
555 assert(le->le_debit == 0);
556 return;
557 }
558
559 /*
560 * If another thread is handling the refill already, we're not
561 * needed.
562 */
563 if (flag_set(&le->le_flags, LF_REFILL_INPROGRESS) & LF_REFILL_INPROGRESS) {
564 return;
565 }
566
567 /*
568 * If the timestamp we're about to use to refill is older than the
569 * last refill, then someone else has already refilled this ledger
570 * and there's nothing for us to do here.
571 */
572 if (now <= le->_le.le_refill.le_last_refill) {
573 flag_clear(&le->le_flags, LF_REFILL_INPROGRESS);
574 return;
575 }
576
577 /*
578 * See how many refill periods have passed since we last
579 * did a refill.
580 */
581 period = le->_le.le_refill.le_refill_period;
582 elapsed = now - le->_le.le_refill.le_last_refill;
583 if ((period == 0) || (elapsed < period)) {
584 flag_clear(&le->le_flags, LF_REFILL_INPROGRESS);
585 return;
586 }
587
588 /*
589 * Optimize for the most common case of only one or two
590 * periods elapsing.
591 */
592 periods = 0;
593 while ((periods < 2) && (elapsed > 0)) {
594 periods++;
595 elapsed -= period;
596 }
597
598 /*
599 * OK, it's been a long time. Do a divide to figure out
600 * how long.
601 */
602 if (elapsed > 0)
603 periods = (now - le->_le.le_refill.le_last_refill) / period;
604
605 balance = le->le_credit - le->le_debit;
606 due = periods * le->le_limit;
607 if (balance - due < 0)
608 due = balance;
609
610 assert(due >= 0);
611
612 OSAddAtomic64(due, &le->le_debit);
613
614 assert(le->le_debit >= 0);
615
616 /*
617 * If we've completely refilled the pool, set the refill time to now.
618 * Otherwise set it to the time at which it last should have been
619 * fully refilled.
620 */
621 if (balance == due)
622 le->_le.le_refill.le_last_refill = now;
623 else
624 le->_le.le_refill.le_last_refill += (le->_le.le_refill.le_refill_period * periods);
625
626 flag_clear(&le->le_flags, LF_REFILL_INPROGRESS);
627
628 lprintf(("Refill %lld %lld->%lld\n", periods, balance, balance - due));
629 if (!limit_exceeded(le))
630 ledger_limit_entry_wakeup(le);
631 }
632
633 /*
634 * In tenths of a second, the length of one lookback period (a "tock") for
635 * ledger rolling maximum calculations. The effective lookback window will be this times
636 * NTOCKS.
637 *
638 * Use a tock length of 2.5 seconds to get a total lookback period of 5 seconds.
639 *
640 * XXX Could make this caller-definable, at the point that rolling max tracking
641 * is enabled for the entry.
642 */
643 #define TOCKLEN 25
644
645 /*
646 * How many sched_tick's are there in one tock (one of our lookback periods)?
647 *
648 * X sched_ticks 2.5 sec N sched_ticks
649 * --------------- = ---------- * -------------
650 * tock tock sec
651 *
652 * where N sched_ticks/sec is calculated via 1 << SCHED_TICK_SHIFT (see sched_prim.h)
653 *
654 * This should give us 20 sched_tick's in one 2.5 second-long tock.
655 */
656 #define SCHED_TICKS_PER_TOCK ((TOCKLEN * (1 << SCHED_TICK_SHIFT)) / 10)
657
658 /*
659 * Rolling max timestamps use their own unit (let's call this a "tock"). One tock is the
660 * length of one lookback period that we use for our rolling max calculation.
661 *
662 * Calculate the current time in tocks from sched_tick (which runs at a some
663 * fixed rate).
664 */
665 #define CURRENT_TOCKSTAMP() (sched_tick / SCHED_TICKS_PER_TOCK)
666
667 /*
668 * Does the given tockstamp fall in either the current or the previous tocks?
669 */
670 #define TOCKSTAMP_IS_STALE(now, tock) ((((now) - (tock)) < NTOCKS) ? FALSE : TRUE)
671
672 void
673 ledger_entry_check_new_balance(ledger_t ledger, int entry, struct ledger_entry *le)
674 {
675 ledger_amount_t credit, debit;
676
677 if (le->le_flags & LF_TRACKING_MAX) {
678 ledger_amount_t balance = le->le_credit - le->le_debit;
679 uint32_t now = CURRENT_TOCKSTAMP();
680 struct _le_peak *p = &le->_le.le_peaks[now % NTOCKS];
681
682 if (!TOCKSTAMP_IS_STALE(now, p->le_time) || (balance > p->le_max)) {
683 /*
684 * The current balance is greater than the previously
685 * observed peak for the current time block, *or* we
686 * haven't yet recorded a peak for the current time block --
687 * so this is our new peak.
688 *
689 * (We only track the lower 32-bits of a balance for rolling
690 * max purposes.)
691 */
692 p->le_max = (uint32_t)balance;
693 p->le_time = now;
694 }
695 }
696
697 /* Check to see whether we're due a refill */
698 if (le->le_flags & LF_REFILL_SCHEDULED) {
699 uint64_t now = mach_absolute_time();
700 if ((now - le->_le.le_refill.le_last_refill) > le->_le.le_refill.le_refill_period)
701 ledger_refill(now, ledger, entry);
702 }
703
704 if (limit_exceeded(le)) {
705 /*
706 * We've exceeded the limit for this entry. There
707 * are several possible ways to handle it. We can block,
708 * we can execute a callback, or we can ignore it. In
709 * either of the first two cases, we want to set the AST
710 * flag so we can take the appropriate action just before
711 * leaving the kernel. The one caveat is that if we have
712 * already called the callback, we don't want to do it
713 * again until it gets rearmed.
714 */
715 if ((le->le_flags & LEDGER_ACTION_BLOCK) ||
716 (!(le->le_flags & LF_CALLED_BACK) &&
717 entry_get_callback(ledger, entry))) {
718 set_astledger(current_thread());
719 }
720 } else {
721 /*
722 * The balance on the account is below the limit.
723 *
724 * If there are any threads blocked on this entry, now would
725 * be a good time to wake them up.
726 */
727 if (le->le_flags & LF_WAKE_NEEDED)
728 ledger_limit_entry_wakeup(le);
729
730 if (le->le_flags & LEDGER_ACTION_CALLBACK) {
731 /*
732 * Client has requested that a callback be invoked whenever
733 * the ledger's balance crosses into or out of the warning
734 * level.
735 */
736 if (warn_level_exceeded(le)) {
737 /*
738 * This ledger's balance is above the warning level.
739 */
740 if ((le->le_flags & LF_WARNED) == 0) {
741 /*
742 * If we are above the warning level and
743 * have not yet invoked the callback,
744 * set the AST so it can be done before returning
745 * to userland.
746 */
747 set_astledger(current_thread());
748 }
749 } else {
750 /*
751 * This ledger's balance is below the warning level.
752 */
753 if (le->le_flags & LF_WARNED) {
754 /*
755 * If we are below the warning level and
756 * the LF_WARNED flag is still set, we need
757 * to invoke the callback to let the client
758 * know the ledger balance is now back below
759 * the warning level.
760 */
761 set_astledger(current_thread());
762 }
763 }
764 }
765 }
766
767 credit = le->le_credit;
768 debit = le->le_debit;
769 if ((le->le_flags & LF_PANIC_ON_NEGATIVE) &&
770 ((credit < debit) ||
771 (le->le_credit < le->le_debit))) {
772 panic("ledger_entry_check_new_balance(%p,%d): negative ledger %p credit:%lld/%lld debit:%lld/%lld balance:%lld/%lld\n",
773 ledger, entry, le,
774 credit, le->le_credit,
775 debit, le->le_debit,
776 credit - debit, le->le_credit - le->le_debit);
777 }
778 }
779
780 void
781 ledger_check_new_balance(ledger_t ledger, int entry)
782 {
783 struct ledger_entry *le;
784 assert(entry > 0 && entry <= ledger->l_size);
785 le = &ledger->l_entries[entry];
786 ledger_entry_check_new_balance(ledger, entry, le);
787 }
788
789
790 /*
791 * Add value to an entry in a ledger.
792 */
793 kern_return_t
794 ledger_credit(ledger_t ledger, int entry, ledger_amount_t amount)
795 {
796 ledger_amount_t old, new;
797 struct ledger_entry *le;
798
799 if (!ENTRY_VALID(ledger, entry) || (amount < 0))
800 return (KERN_INVALID_VALUE);
801
802 if (amount == 0)
803 return (KERN_SUCCESS);
804
805 le = &ledger->l_entries[entry];
806
807 old = OSAddAtomic64(amount, &le->le_credit);
808 new = old + amount;
809 lprintf(("%p Credit %lld->%lld\n", current_thread(), old, new));
810 ledger_entry_check_new_balance(ledger, entry, le);
811
812 return (KERN_SUCCESS);
813 }
814
815 /* Add all of one ledger's values into another.
816 * They must have been created from the same template.
817 * This is not done atomically. Another thread (if not otherwise synchronized)
818 * may see bogus values when comparing one entry to another.
819 * As each entry's credit & debit are modified one at a time, the warning/limit
820 * may spuriously trip, or spuriously fail to trip, or another thread (if not
821 * otherwise synchronized) may see a bogus balance.
822 */
823 kern_return_t
824 ledger_rollup(ledger_t to_ledger, ledger_t from_ledger)
825 {
826 int i;
827 struct ledger_entry *from_le, *to_le;
828
829 assert(to_ledger->l_template == from_ledger->l_template);
830
831 for (i = 0; i < to_ledger->l_size; i++) {
832 if (ENTRY_VALID(from_ledger, i) && ENTRY_VALID(to_ledger, i)) {
833 from_le = &from_ledger->l_entries[i];
834 to_le = &to_ledger->l_entries[i];
835 OSAddAtomic64(from_le->le_credit, &to_le->le_credit);
836 OSAddAtomic64(from_le->le_debit, &to_le->le_debit);
837 }
838 }
839
840 return (KERN_SUCCESS);
841 }
842
843 /*
844 * Zero the balance of a ledger by adding to its credit or debit, whichever is smaller.
845 * Note that some clients of ledgers (notably, task wakeup statistics) require that
846 * le_credit only ever increase as a function of ledger_credit().
847 */
848 kern_return_t
849 ledger_zero_balance(ledger_t ledger, int entry)
850 {
851 struct ledger_entry *le;
852
853 if (!ENTRY_VALID(ledger, entry))
854 return (KERN_INVALID_VALUE);
855
856 le = &ledger->l_entries[entry];
857
858 top:
859 if (le->le_flags & LF_TRACK_CREDIT_ONLY) {
860 assert(le->le_debit == 0);
861 if (!OSCompareAndSwap64(le->le_credit, 0, &le->le_credit)) {
862 goto top;
863 }
864 lprintf(("%p zeroed %lld->%lld\n", current_thread(), le->le_credit, 0));
865 } else if (le->le_credit > le->le_debit) {
866 if (!OSCompareAndSwap64(le->le_debit, le->le_credit, &le->le_debit))
867 goto top;
868 lprintf(("%p zeroed %lld->%lld\n", current_thread(), le->le_debit, le->le_credit));
869 } else if (le->le_credit < le->le_debit) {
870 if (!OSCompareAndSwap64(le->le_credit, le->le_debit, &le->le_credit))
871 goto top;
872 lprintf(("%p zeroed %lld->%lld\n", current_thread(), le->le_credit, le->le_debit));
873 }
874
875 return (KERN_SUCCESS);
876 }
877
878 kern_return_t
879 ledger_get_limit(ledger_t ledger, int entry, ledger_amount_t *limit)
880 {
881 struct ledger_entry *le;
882
883 if (!ENTRY_VALID(ledger, entry))
884 return (KERN_INVALID_VALUE);
885
886 le = &ledger->l_entries[entry];
887 *limit = le->le_limit;
888
889 lprintf(("ledger_get_limit: %lld\n", *limit));
890
891 return (KERN_SUCCESS);
892 }
893
894 /*
895 * Adjust the limit of a limited resource. This does not affect the
896 * current balance, so the change doesn't affect the thread until the
897 * next refill.
898 *
899 * warn_level: If non-zero, causes the callback to be invoked when
900 * the balance exceeds this level. Specified as a percentage [of the limit].
901 */
902 kern_return_t
903 ledger_set_limit(ledger_t ledger, int entry, ledger_amount_t limit,
904 uint8_t warn_level_percentage)
905 {
906 struct ledger_entry *le;
907
908 if (!ENTRY_VALID(ledger, entry))
909 return (KERN_INVALID_VALUE);
910
911 lprintf(("ledger_set_limit: %lld\n", limit));
912 le = &ledger->l_entries[entry];
913
914 if (limit == LEDGER_LIMIT_INFINITY) {
915 /*
916 * Caller wishes to disable the limit. This will implicitly
917 * disable automatic refill, as refills implicitly depend
918 * on the limit.
919 */
920 ledger_disable_refill(ledger, entry);
921 }
922
923 le->le_limit = limit;
924 le->_le.le_refill.le_last_refill = 0;
925 flag_clear(&le->le_flags, LF_CALLED_BACK);
926 flag_clear(&le->le_flags, LF_WARNED);
927 ledger_limit_entry_wakeup(le);
928
929 if (warn_level_percentage != 0) {
930 assert(warn_level_percentage <= 100);
931 assert(limit > 0); /* no negative limit support for warnings */
932 assert(limit != LEDGER_LIMIT_INFINITY); /* warn % without limit makes no sense */
933 le->le_warn_level = (le->le_limit * warn_level_percentage) / 100;
934 } else {
935 le->le_warn_level = LEDGER_LIMIT_INFINITY;
936 }
937
938 return (KERN_SUCCESS);
939 }
940
941 kern_return_t
942 ledger_get_maximum(ledger_t ledger, int entry,
943 ledger_amount_t *max_observed_balance)
944 {
945 struct ledger_entry *le;
946 uint32_t now = CURRENT_TOCKSTAMP();
947 int i;
948
949 le = &ledger->l_entries[entry];
950
951 if (!ENTRY_VALID(ledger, entry) || !(le->le_flags & LF_TRACKING_MAX)) {
952 return (KERN_INVALID_VALUE);
953 }
954
955 /*
956 * Start with the current balance; if neither of the recorded peaks are
957 * within recent history, we use this.
958 */
959 *max_observed_balance = le->le_credit - le->le_debit;
960
961 for (i = 0; i < NTOCKS; i++) {
962 if (!TOCKSTAMP_IS_STALE(now, le->_le.le_peaks[i].le_time) &&
963 (le->_le.le_peaks[i].le_max > *max_observed_balance)) {
964 /*
965 * The peak for this time block isn't stale, and it
966 * is greater than the current balance -- so use it.
967 */
968 *max_observed_balance = le->_le.le_peaks[i].le_max;
969 }
970 }
971
972 lprintf(("ledger_get_maximum: %lld\n", *max_observed_balance));
973
974 return (KERN_SUCCESS);
975 }
976
977 /*
978 * Enable tracking of periodic maximums for this ledger entry.
979 */
980 kern_return_t
981 ledger_track_maximum(ledger_template_t template, int entry,
982 __unused int period_in_secs)
983 {
984 template_lock(template);
985
986 if ((entry < 0) || (entry >= template->lt_cnt)) {
987 template_unlock(template);
988 return (KERN_INVALID_VALUE);
989 }
990
991 template->lt_entries[entry].et_flags |= LF_TRACKING_MAX;
992 template_unlock(template);
993
994 return (KERN_SUCCESS);
995 }
996
997 kern_return_t
998 ledger_panic_on_negative(ledger_template_t template, int entry)
999 {
1000 template_lock(template);
1001
1002 if ((entry < 0) || (entry >= template->lt_cnt)) {
1003 template_unlock(template);
1004 return (KERN_INVALID_VALUE);
1005 }
1006
1007 template->lt_entries[entry].et_flags |= LF_PANIC_ON_NEGATIVE;
1008
1009 template_unlock(template);
1010
1011 return (KERN_SUCCESS);
1012 }
1013
1014 kern_return_t
1015 ledger_track_credit_only(ledger_template_t template, int entry)
1016 {
1017 template_lock(template);
1018
1019 if ((entry < 0) || (entry >= template->lt_cnt)) {
1020 template_unlock(template);
1021 return (KERN_INVALID_VALUE);
1022 }
1023
1024 template->lt_entries[entry].et_flags |= LF_TRACK_CREDIT_ONLY;
1025
1026 template_unlock(template);
1027
1028 return (KERN_SUCCESS);
1029 }
1030
1031 /*
1032 * Add a callback to be executed when the resource goes into deficit.
1033 */
1034 kern_return_t
1035 ledger_set_callback(ledger_template_t template, int entry,
1036 ledger_callback_t func, const void *param0, const void *param1)
1037 {
1038 struct entry_template *et;
1039 struct ledger_callback *old_cb, *new_cb;
1040
1041 if ((entry < 0) || (entry >= template->lt_cnt))
1042 return (KERN_INVALID_VALUE);
1043
1044 if (func) {
1045 new_cb = (struct ledger_callback *)kalloc(sizeof (*new_cb));
1046 new_cb->lc_func = func;
1047 new_cb->lc_param0 = param0;
1048 new_cb->lc_param1 = param1;
1049 } else {
1050 new_cb = NULL;
1051 }
1052
1053 template_lock(template);
1054 et = &template->lt_entries[entry];
1055 old_cb = et->et_callback;
1056 et->et_callback = new_cb;
1057 template_unlock(template);
1058 if (old_cb)
1059 kfree(old_cb, sizeof (*old_cb));
1060
1061 return (KERN_SUCCESS);
1062 }
1063
1064 /*
1065 * Disable callback notification for a specific ledger entry.
1066 *
1067 * Otherwise, if using a ledger template which specified a
1068 * callback function (ledger_set_callback()), it will be invoked when
1069 * the resource goes into deficit.
1070 */
1071 kern_return_t
1072 ledger_disable_callback(ledger_t ledger, int entry)
1073 {
1074 if (!ENTRY_VALID(ledger, entry))
1075 return (KERN_INVALID_VALUE);
1076
1077 /*
1078 * le_warn_level is used to indicate *if* this ledger has a warning configured,
1079 * in addition to what that warning level is set to.
1080 * This means a side-effect of ledger_disable_callback() is that the
1081 * warning level is forgotten.
1082 */
1083 ledger->l_entries[entry].le_warn_level = LEDGER_LIMIT_INFINITY;
1084 flag_clear(&ledger->l_entries[entry].le_flags, LEDGER_ACTION_CALLBACK);
1085 return (KERN_SUCCESS);
1086 }
1087
1088 /*
1089 * Enable callback notification for a specific ledger entry.
1090 *
1091 * This is only needed if ledger_disable_callback() has previously
1092 * been invoked against an entry; there must already be a callback
1093 * configured.
1094 */
1095 kern_return_t
1096 ledger_enable_callback(ledger_t ledger, int entry)
1097 {
1098 if (!ENTRY_VALID(ledger, entry))
1099 return (KERN_INVALID_VALUE);
1100
1101 assert(entry_get_callback(ledger, entry) != NULL);
1102
1103 flag_set(&ledger->l_entries[entry].le_flags, LEDGER_ACTION_CALLBACK);
1104 return (KERN_SUCCESS);
1105 }
1106
1107 /*
1108 * Query the automatic refill period for this ledger entry.
1109 *
1110 * A period of 0 means this entry has none configured.
1111 */
1112 kern_return_t
1113 ledger_get_period(ledger_t ledger, int entry, uint64_t *period)
1114 {
1115 struct ledger_entry *le;
1116
1117 if (!ENTRY_VALID(ledger, entry))
1118 return (KERN_INVALID_VALUE);
1119
1120 le = &ledger->l_entries[entry];
1121 *period = abstime_to_nsecs(le->_le.le_refill.le_refill_period);
1122 lprintf(("ledger_get_period: %llx\n", *period));
1123 return (KERN_SUCCESS);
1124 }
1125
1126 /*
1127 * Adjust the automatic refill period.
1128 */
1129 kern_return_t
1130 ledger_set_period(ledger_t ledger, int entry, uint64_t period)
1131 {
1132 struct ledger_entry *le;
1133
1134 lprintf(("ledger_set_period: %llx\n", period));
1135 if (!ENTRY_VALID(ledger, entry))
1136 return (KERN_INVALID_VALUE);
1137
1138 le = &ledger->l_entries[entry];
1139
1140 /*
1141 * A refill period refills the ledger in multiples of the limit,
1142 * so if you haven't set one yet, you need a lesson on ledgers.
1143 */
1144 assert(le->le_limit != LEDGER_LIMIT_INFINITY);
1145
1146 if (le->le_flags & LF_TRACKING_MAX) {
1147 /*
1148 * Refill is incompatible with rolling max tracking.
1149 */
1150 return (KERN_INVALID_VALUE);
1151 }
1152
1153 le->_le.le_refill.le_refill_period = nsecs_to_abstime(period);
1154
1155 /*
1156 * Set the 'starting time' for the next refill to now. Since
1157 * we're resetting the balance to zero here, we consider this
1158 * moment the starting time for accumulating a balance that
1159 * counts towards the limit.
1160 */
1161 le->_le.le_refill.le_last_refill = mach_absolute_time();
1162 ledger_zero_balance(ledger, entry);
1163
1164 flag_set(&le->le_flags, LF_REFILL_SCHEDULED);
1165
1166 return (KERN_SUCCESS);
1167 }
1168
1169 /*
1170 * Disable automatic refill.
1171 */
1172 kern_return_t
1173 ledger_disable_refill(ledger_t ledger, int entry)
1174 {
1175 struct ledger_entry *le;
1176
1177 if (!ENTRY_VALID(ledger, entry))
1178 return (KERN_INVALID_VALUE);
1179
1180 le = &ledger->l_entries[entry];
1181
1182 flag_clear(&le->le_flags, LF_REFILL_SCHEDULED);
1183
1184 return (KERN_SUCCESS);
1185 }
1186
1187 kern_return_t
1188 ledger_get_actions(ledger_t ledger, int entry, int *actions)
1189 {
1190 if (!ENTRY_VALID(ledger, entry))
1191 return (KERN_INVALID_VALUE);
1192
1193 *actions = ledger->l_entries[entry].le_flags & LEDGER_ACTION_MASK;
1194 lprintf(("ledger_get_actions: %#x\n", *actions));
1195 return (KERN_SUCCESS);
1196 }
1197
1198 kern_return_t
1199 ledger_set_action(ledger_t ledger, int entry, int action)
1200 {
1201 lprintf(("ledger_set_action: %#x\n", action));
1202 if (!ENTRY_VALID(ledger, entry))
1203 return (KERN_INVALID_VALUE);
1204
1205 flag_set(&ledger->l_entries[entry].le_flags, action);
1206 return (KERN_SUCCESS);
1207 }
1208
1209 kern_return_t
1210 ledger_debit(ledger_t ledger, int entry, ledger_amount_t amount)
1211 {
1212 struct ledger_entry *le;
1213 ledger_amount_t old, new;
1214
1215 if (!ENTRY_VALID(ledger, entry) || (amount < 0))
1216 return (KERN_INVALID_ARGUMENT);
1217
1218 if (amount == 0)
1219 return (KERN_SUCCESS);
1220
1221 le = &ledger->l_entries[entry];
1222
1223 if (le->le_flags & LF_TRACK_CREDIT_ONLY) {
1224 assert(le->le_debit == 0);
1225 old = OSAddAtomic64(-amount, &le->le_credit);
1226 new = old - amount;
1227 } else {
1228 old = OSAddAtomic64(amount, &le->le_debit);
1229 new = old + amount;
1230 }
1231 lprintf(("%p Debit %lld->%lld\n", thread, old, new));
1232
1233 ledger_entry_check_new_balance(ledger, entry, le);
1234 return (KERN_SUCCESS);
1235
1236 }
1237
1238 void
1239 ledger_ast(thread_t thread)
1240 {
1241 struct ledger *l = thread->t_ledger;
1242 struct ledger *thl;
1243 uint32_t block;
1244 uint64_t now;
1245 uint8_t task_flags;
1246 uint8_t task_percentage;
1247 uint64_t task_interval;
1248
1249 kern_return_t ret;
1250 task_t task = thread->task;
1251
1252 lprintf(("Ledger AST for %p\n", thread));
1253
1254 ASSERT(task != NULL);
1255 ASSERT(thread == current_thread());
1256
1257 top:
1258 /*
1259 * Take a self-consistent snapshot of the CPU usage monitor parameters. The task
1260 * can change them at any point (with the task locked).
1261 */
1262 task_lock(task);
1263 task_flags = task->rusage_cpu_flags;
1264 task_percentage = task->rusage_cpu_perthr_percentage;
1265 task_interval = task->rusage_cpu_perthr_interval;
1266 task_unlock(task);
1267
1268 /*
1269 * Make sure this thread is up to date with regards to any task-wide per-thread
1270 * CPU limit, but only if it doesn't have a thread-private blocking CPU limit.
1271 */
1272 if (((task_flags & TASK_RUSECPU_FLAGS_PERTHR_LIMIT) != 0) &&
1273 ((thread->options & TH_OPT_PRVT_CPULIMIT) == 0)) {
1274 uint8_t percentage;
1275 uint64_t interval;
1276 int action;
1277
1278 thread_get_cpulimit(&action, &percentage, &interval);
1279
1280 /*
1281 * If the thread's CPU limits no longer match the task's, or the
1282 * task has a limit but the thread doesn't, update the limit.
1283 */
1284 if (((thread->options & TH_OPT_PROC_CPULIMIT) == 0) ||
1285 (interval != task_interval) || (percentage != task_percentage)) {
1286 thread_set_cpulimit(THREAD_CPULIMIT_EXCEPTION, task_percentage, task_interval);
1287 assert((thread->options & TH_OPT_PROC_CPULIMIT) != 0);
1288 }
1289 } else if (((task_flags & TASK_RUSECPU_FLAGS_PERTHR_LIMIT) == 0) &&
1290 (thread->options & TH_OPT_PROC_CPULIMIT)) {
1291 assert((thread->options & TH_OPT_PRVT_CPULIMIT) == 0);
1292
1293 /*
1294 * Task no longer has a per-thread CPU limit; remove this thread's
1295 * corresponding CPU limit.
1296 */
1297 thread_set_cpulimit(THREAD_CPULIMIT_DISABLE, 0, 0);
1298 assert((thread->options & TH_OPT_PROC_CPULIMIT) == 0);
1299 }
1300
1301 /*
1302 * If the task or thread is being terminated, let's just get on with it
1303 */
1304 if ((l == NULL) || !task->active || task->halting || !thread->active)
1305 return;
1306
1307 /*
1308 * Examine all entries in deficit to see which might be eligble for
1309 * an automatic refill, which require callbacks to be issued, and
1310 * which require blocking.
1311 */
1312 block = 0;
1313 now = mach_absolute_time();
1314
1315 /*
1316 * Note that thread->t_threadledger may have been changed by the
1317 * thread_set_cpulimit() call above - so don't examine it until afterwards.
1318 */
1319 thl = thread->t_threadledger;
1320 if (LEDGER_VALID(thl)) {
1321 block |= ledger_check_needblock(thl, now);
1322 }
1323 block |= ledger_check_needblock(l, now);
1324
1325 /*
1326 * If we are supposed to block on the availability of one or more
1327 * resources, find the first entry in deficit for which we should wait.
1328 * Schedule a refill if necessary and then sleep until the resource
1329 * becomes available.
1330 */
1331 if (block) {
1332 if (LEDGER_VALID(thl)) {
1333 ret = ledger_perform_blocking(thl);
1334 if (ret != KERN_SUCCESS)
1335 goto top;
1336 }
1337 ret = ledger_perform_blocking(l);
1338 if (ret != KERN_SUCCESS)
1339 goto top;
1340 } /* block */
1341 }
1342
1343 static uint32_t
1344 ledger_check_needblock(ledger_t l, uint64_t now)
1345 {
1346 int i;
1347 uint32_t flags, block = 0;
1348 struct ledger_entry *le;
1349 struct ledger_callback *lc;
1350
1351
1352 for (i = 0; i < l->l_size; i++) {
1353 le = &l->l_entries[i];
1354
1355 lc = entry_get_callback(l, i);
1356
1357 if (limit_exceeded(le) == FALSE) {
1358 if (le->le_flags & LEDGER_ACTION_CALLBACK) {
1359 /*
1360 * If needed, invoke the callback as a warning.
1361 * This needs to happen both when the balance rises above
1362 * the warning level, and also when it dips back below it.
1363 */
1364 assert(lc != NULL);
1365 /*
1366 * See comments for matching logic in ledger_check_new_balance().
1367 */
1368 if (warn_level_exceeded(le)) {
1369 flags = flag_set(&le->le_flags, LF_WARNED);
1370 if ((flags & LF_WARNED) == 0) {
1371 lc->lc_func(LEDGER_WARNING_ROSE_ABOVE, lc->lc_param0, lc->lc_param1);
1372 }
1373 } else {
1374 flags = flag_clear(&le->le_flags, LF_WARNED);
1375 if (flags & LF_WARNED) {
1376 lc->lc_func(LEDGER_WARNING_DIPPED_BELOW, lc->lc_param0, lc->lc_param1);
1377 }
1378 }
1379 }
1380
1381 continue;
1382 }
1383
1384 /* We're over the limit, so refill if we are eligible and past due. */
1385 if (le->le_flags & LF_REFILL_SCHEDULED) {
1386 if ((le->_le.le_refill.le_last_refill + le->_le.le_refill.le_refill_period) > now) {
1387 ledger_refill(now, l, i);
1388 if (limit_exceeded(le) == FALSE)
1389 continue;
1390 }
1391 }
1392
1393 if (le->le_flags & LEDGER_ACTION_BLOCK)
1394 block = 1;
1395 if ((le->le_flags & LEDGER_ACTION_CALLBACK) == 0)
1396 continue;
1397
1398 /*
1399 * If the LEDGER_ACTION_CALLBACK flag is on, we expect there to
1400 * be a registered callback.
1401 */
1402 assert(lc != NULL);
1403 flags = flag_set(&le->le_flags, LF_CALLED_BACK);
1404 /* Callback has already been called */
1405 if (flags & LF_CALLED_BACK)
1406 continue;
1407 lc->lc_func(FALSE, lc->lc_param0, lc->lc_param1);
1408 }
1409 return(block);
1410 }
1411
1412
1413 /* return KERN_SUCCESS to continue, KERN_FAILURE to restart */
1414 static kern_return_t
1415 ledger_perform_blocking(ledger_t l)
1416 {
1417 int i;
1418 kern_return_t ret;
1419 struct ledger_entry *le;
1420
1421 for (i = 0; i < l->l_size; i++) {
1422 le = &l->l_entries[i];
1423 if ((!limit_exceeded(le)) ||
1424 ((le->le_flags & LEDGER_ACTION_BLOCK) == 0))
1425 continue;
1426
1427 /* Prepare to sleep until the resource is refilled */
1428 ret = assert_wait_deadline(le, TRUE,
1429 le->_le.le_refill.le_last_refill + le->_le.le_refill.le_refill_period);
1430 if (ret != THREAD_WAITING)
1431 return(KERN_SUCCESS);
1432
1433 /* Mark that somebody is waiting on this entry */
1434 flag_set(&le->le_flags, LF_WAKE_NEEDED);
1435
1436 ret = thread_block_reason(THREAD_CONTINUE_NULL, NULL,
1437 AST_LEDGER);
1438 if (ret != THREAD_AWAKENED)
1439 return(KERN_SUCCESS);
1440
1441 /*
1442 * The world may have changed while we were asleep.
1443 * Some other resource we need may have gone into
1444 * deficit. Or maybe we're supposed to die now.
1445 * Go back to the top and reevaluate.
1446 */
1447 return(KERN_FAILURE);
1448 }
1449 return(KERN_SUCCESS);
1450 }
1451
1452
1453 kern_return_t
1454 ledger_get_entries(ledger_t ledger, int entry, ledger_amount_t *credit,
1455 ledger_amount_t *debit)
1456 {
1457 struct ledger_entry *le;
1458
1459 if (!ENTRY_VALID(ledger, entry))
1460 return (KERN_INVALID_ARGUMENT);
1461
1462 le = &ledger->l_entries[entry];
1463
1464 *credit = le->le_credit;
1465 *debit = le->le_debit;
1466
1467 return (KERN_SUCCESS);
1468 }
1469
1470 kern_return_t
1471 ledger_reset_callback_state(ledger_t ledger, int entry)
1472 {
1473 struct ledger_entry *le;
1474
1475 if (!ENTRY_VALID(ledger, entry))
1476 return (KERN_INVALID_ARGUMENT);
1477
1478 le = &ledger->l_entries[entry];
1479
1480 flag_clear(&le->le_flags, LF_CALLED_BACK);
1481
1482 return (KERN_SUCCESS);
1483 }
1484
1485 kern_return_t
1486 ledger_disable_panic_on_negative(ledger_t ledger, int entry)
1487 {
1488 struct ledger_entry *le;
1489
1490 if (!ENTRY_VALID(ledger, entry))
1491 return (KERN_INVALID_ARGUMENT);
1492
1493 le = &ledger->l_entries[entry];
1494
1495 flag_clear(&le->le_flags, LF_PANIC_ON_NEGATIVE);
1496
1497 return (KERN_SUCCESS);
1498 }
1499
1500 kern_return_t
1501 ledger_get_balance(ledger_t ledger, int entry, ledger_amount_t *balance)
1502 {
1503 struct ledger_entry *le;
1504
1505 if (!ENTRY_VALID(ledger, entry))
1506 return (KERN_INVALID_ARGUMENT);
1507
1508 le = &ledger->l_entries[entry];
1509
1510 if (le->le_flags & LF_TRACK_CREDIT_ONLY) {
1511 assert(le->le_debit == 0);
1512 } else {
1513 assert((le->le_credit >= 0) && (le->le_debit >= 0));
1514 }
1515
1516 *balance = le->le_credit - le->le_debit;
1517
1518 return (KERN_SUCCESS);
1519 }
1520
1521 int
1522 ledger_template_info(void **buf, int *len)
1523 {
1524 struct ledger_template_info *lti;
1525 struct entry_template *et;
1526 int i;
1527 ledger_t l;
1528
1529 /*
1530 * Since all tasks share a ledger template, we'll just use the
1531 * caller's as the source.
1532 */
1533 l = current_task()->ledger;
1534 if ((*len < 0) || (l == NULL))
1535 return (EINVAL);
1536
1537 if (*len > l->l_size)
1538 *len = l->l_size;
1539 lti = kalloc((*len) * sizeof (struct ledger_template_info));
1540 if (lti == NULL)
1541 return (ENOMEM);
1542 *buf = lti;
1543
1544 template_lock(l->l_template);
1545 et = l->l_template->lt_entries;
1546
1547 for (i = 0; i < *len; i++) {
1548 memset(lti, 0, sizeof (*lti));
1549 strlcpy(lti->lti_name, et->et_key, LEDGER_NAME_MAX);
1550 strlcpy(lti->lti_group, et->et_group, LEDGER_NAME_MAX);
1551 strlcpy(lti->lti_units, et->et_units, LEDGER_NAME_MAX);
1552 et++;
1553 lti++;
1554 }
1555 template_unlock(l->l_template);
1556
1557 return (0);
1558 }
1559
1560 static void
1561 ledger_fill_entry_info(struct ledger_entry *le,
1562 struct ledger_entry_info *lei,
1563 uint64_t now)
1564 {
1565 assert(le != NULL);
1566 assert(lei != NULL);
1567
1568 memset(lei, 0, sizeof (*lei));
1569
1570 lei->lei_limit = le->le_limit;
1571 lei->lei_credit = le->le_credit;
1572 lei->lei_debit = le->le_debit;
1573 lei->lei_balance = lei->lei_credit - lei->lei_debit;
1574 lei->lei_refill_period = (le->le_flags & LF_REFILL_SCHEDULED) ?
1575 abstime_to_nsecs(le->_le.le_refill.le_refill_period) : 0;
1576 lei->lei_last_refill = abstime_to_nsecs(now - le->_le.le_refill.le_last_refill);
1577 }
1578
1579 int
1580 ledger_get_task_entry_info_multiple(task_t task, void **buf, int *len)
1581 {
1582 struct ledger_entry_info *lei;
1583 struct ledger_entry *le;
1584 uint64_t now = mach_absolute_time();
1585 int i;
1586 ledger_t l;
1587
1588 if ((*len < 0) || ((l = task->ledger) == NULL))
1589 return (EINVAL);
1590
1591 if (*len > l->l_size)
1592 *len = l->l_size;
1593 lei = kalloc((*len) * sizeof (struct ledger_entry_info));
1594 if (lei == NULL)
1595 return (ENOMEM);
1596 *buf = lei;
1597
1598 le = l->l_entries;
1599
1600 for (i = 0; i < *len; i++) {
1601 ledger_fill_entry_info(le, lei, now);
1602 le++;
1603 lei++;
1604 }
1605
1606 return (0);
1607 }
1608
1609 void
1610 ledger_get_entry_info(ledger_t ledger,
1611 int entry,
1612 struct ledger_entry_info *lei)
1613 {
1614 uint64_t now = mach_absolute_time();
1615
1616 assert(ledger != NULL);
1617 assert(lei != NULL);
1618
1619 if (entry >= 0 && entry < ledger->l_size) {
1620 struct ledger_entry *le = &ledger->l_entries[entry];
1621 ledger_fill_entry_info(le, lei, now);
1622 }
1623 }
1624
1625 int
1626 ledger_info(task_t task, struct ledger_info *info)
1627 {
1628 ledger_t l;
1629
1630 if ((l = task->ledger) == NULL)
1631 return (ENOENT);
1632
1633 memset(info, 0, sizeof (*info));
1634
1635 strlcpy(info->li_name, l->l_template->lt_name, LEDGER_NAME_MAX);
1636 info->li_id = l->l_id;
1637 info->li_entries = l->l_size;
1638 return (0);
1639 }
1640
1641 #ifdef LEDGER_DEBUG
1642 int
1643 ledger_limit(task_t task, struct ledger_limit_args *args)
1644 {
1645 ledger_t l;
1646 int64_t limit;
1647 int idx;
1648
1649 if ((l = task->ledger) == NULL)
1650 return (EINVAL);
1651
1652 idx = ledger_key_lookup(l->l_template, args->lla_name);
1653 if ((idx < 0) || (idx >= l->l_size))
1654 return (EINVAL);
1655
1656 /*
1657 * XXX - this doesn't really seem like the right place to have
1658 * a context-sensitive conversion of userspace units into kernel
1659 * units. For now I'll handwave and say that the ledger() system
1660 * call isn't meant for civilians to use - they should be using
1661 * the process policy interfaces.
1662 */
1663 if (idx == task_ledgers.cpu_time) {
1664 int64_t nsecs;
1665
1666 if (args->lla_refill_period) {
1667 /*
1668 * If a refill is scheduled, then the limit is
1669 * specified as a percentage of one CPU. The
1670 * syscall specifies the refill period in terms of
1671 * milliseconds, so we need to convert to nsecs.
1672 */
1673 args->lla_refill_period *= 1000000;
1674 nsecs = args->lla_limit *
1675 (args->lla_refill_period / 100);
1676 lprintf(("CPU limited to %lld nsecs per second\n",
1677 nsecs));
1678 } else {
1679 /*
1680 * If no refill is scheduled, then this is a
1681 * fixed amount of CPU time (in nsecs) that can
1682 * be consumed.
1683 */
1684 nsecs = args->lla_limit;
1685 lprintf(("CPU limited to %lld nsecs\n", nsecs));
1686 }
1687 limit = nsecs_to_abstime(nsecs);
1688 } else {
1689 limit = args->lla_limit;
1690 lprintf(("%s limited to %lld\n", args->lla_name, limit));
1691 }
1692
1693 if (args->lla_refill_period > 0)
1694 ledger_set_period(l, idx, args->lla_refill_period);
1695
1696 ledger_set_limit(l, idx, limit);
1697 flag_set(&l->l_entries[idx].le_flags, LEDGER_ACTION_BLOCK);
1698 return (0);
1699 }
1700 #endif