1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (c) 2009 Isilon Inc http://www.isilon.com/
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 */
27 /**
28 * @file
29 *
30 * fail(9) Facility.
31 *
32 * @ingroup failpoint_private
33 */
34 /**
35 * @defgroup failpoint fail(9) Facility
36 *
37 * Failpoints allow for injecting fake errors into running code on the fly,
38 * without modifying code or recompiling with flags. Failpoints are always
39 * present, and are very efficient when disabled. Failpoints are described
40 * in man fail(9).
41 */
42 /**
43 * @defgroup failpoint_private Private fail(9) Implementation functions
44 *
45 * Private implementations for the actual failpoint code.
46 *
47 * @ingroup failpoint
48 */
49 /**
50 * @addtogroup failpoint_private
51 * @{
52 */
53
54 #include <sys/cdefs.h>
55 #include "opt_stack.h"
56
57 #include <sys/ctype.h>
58 #include <sys/errno.h>
59 #include <sys/fail.h>
60 #include <sys/kernel.h>
61 #include <sys/libkern.h>
62 #include <sys/limits.h>
63 #include <sys/lock.h>
64 #include <sys/malloc.h>
65 #include <sys/mutex.h>
66 #include <sys/proc.h>
67 #include <sys/sbuf.h>
68 #include <sys/sleepqueue.h>
69 #include <sys/stdarg.h>
70 #include <sys/sx.h>
71 #include <sys/sysctl.h>
72 #include <sys/types.h>
73
74 #include <machine/atomic.h>
75
76 #ifdef ILOG_DEFINE_FOR_FILE
77 ILOG_DEFINE_FOR_FILE(L_ISI_FAIL_POINT, L_ILOG, fail_point);
78 #endif
79
80 static MALLOC_DEFINE(M_FAIL_POINT, "Fail Points", "fail points system");
81 #define fp_free(ptr) free(ptr, M_FAIL_POINT)
82 #define fp_malloc(size, flags) malloc((size), M_FAIL_POINT, (flags))
83 #define fs_free(ptr) fp_free(ptr)
84 #define fs_malloc() fp_malloc(sizeof(struct fail_point_setting), \
85 M_WAITOK | M_ZERO)
86
87 /**
88 * These define the wchans that are used for sleeping, pausing respectively.
89 * They are chosen arbitrarily but need to be distinct to the failpoint and
90 * the sleep/pause distinction.
91 */
92 #define FP_SLEEP_CHANNEL(fp) (void*)(fp)
93 #define FP_PAUSE_CHANNEL(fp) __DEVOLATILE(void*, &fp->fp_setting)
94
95 /**
96 * Don't allow more than this many entries in a fail point set by sysctl.
97 * The 99.99...% case is to have 1 entry. I can't imagine having this many
98 * entries, so it should not limit us. Saves on re-mallocs while holding
99 * a non-sleepable lock.
100 */
101 #define FP_MAX_ENTRY_COUNT 20
102
103 /* Used to drain sbufs to the sysctl output */
104 int fail_sysctl_drain_func(void *, const char *, int);
105
106 /* Head of tailq of struct fail_point_entry */
107 TAILQ_HEAD(fail_point_entry_queue, fail_point_entry);
108
109 /**
110 * fp entries garbage list; outstanding entries are cleaned up in the
111 * garbage collector
112 */
113 STAILQ_HEAD(fail_point_setting_garbage, fail_point_setting);
114 static struct fail_point_setting_garbage fp_setting_garbage =
115 STAILQ_HEAD_INITIALIZER(fp_setting_garbage);
116 static struct mtx mtx_garbage_list;
117 MTX_SYSINIT(mtx_garbage_list, &mtx_garbage_list, "fail point garbage mtx",
118 MTX_SPIN);
119
120 static struct sx sx_fp_set;
121 SX_SYSINIT(sx_fp_set, &sx_fp_set, "fail point set sx");
122
123 /**
124 * Failpoint types.
125 * Don't change these without changing fail_type_strings in fail.c.
126 * @ingroup failpoint_private
127 */
128 enum fail_point_t {
129 FAIL_POINT_OFF, /**< don't fail */
130 FAIL_POINT_PANIC, /**< panic */
131 FAIL_POINT_RETURN, /**< return an errorcode */
132 FAIL_POINT_BREAK, /**< break into the debugger */
133 FAIL_POINT_PRINT, /**< print a message */
134 FAIL_POINT_SLEEP, /**< sleep for some msecs */
135 FAIL_POINT_PAUSE, /**< sleep until failpoint is set to off */
136 FAIL_POINT_YIELD, /**< yield the cpu */
137 FAIL_POINT_DELAY, /**< busy wait the cpu */
138 FAIL_POINT_NUMTYPES,
139 FAIL_POINT_INVALID = -1
140 };
141
142 static struct {
143 const char *name;
144 int nmlen;
145 } fail_type_strings[] = {
146 #define FP_TYPE_NM_LEN(s) { s, sizeof(s) - 1 }
147 [FAIL_POINT_OFF] = FP_TYPE_NM_LEN("off"),
148 [FAIL_POINT_PANIC] = FP_TYPE_NM_LEN("panic"),
149 [FAIL_POINT_RETURN] = FP_TYPE_NM_LEN("return"),
150 [FAIL_POINT_BREAK] = FP_TYPE_NM_LEN("break"),
151 [FAIL_POINT_PRINT] = FP_TYPE_NM_LEN("print"),
152 [FAIL_POINT_SLEEP] = FP_TYPE_NM_LEN("sleep"),
153 [FAIL_POINT_PAUSE] = FP_TYPE_NM_LEN("pause"),
154 [FAIL_POINT_YIELD] = FP_TYPE_NM_LEN("yield"),
155 [FAIL_POINT_DELAY] = FP_TYPE_NM_LEN("delay"),
156 };
157
158 #define FE_COUNT_UNTRACKED (INT_MIN)
159
160 /**
161 * Internal structure tracking a single term of a complete failpoint.
162 * @ingroup failpoint_private
163 */
164 struct fail_point_entry {
165 volatile bool fe_stale;
166 enum fail_point_t fe_type; /**< type of entry */
167 int fe_arg; /**< argument to type (e.g. return value) */
168 int fe_prob; /**< likelihood of firing in millionths */
169 int32_t fe_count; /**< number of times to fire, -1 means infinite */
170 pid_t fe_pid; /**< only fail for this process */
171 struct fail_point *fe_parent; /**< backpointer to fp */
172 TAILQ_ENTRY(fail_point_entry) fe_entries; /**< next entry ptr */
173 };
174
175 struct fail_point_setting {
176 STAILQ_ENTRY(fail_point_setting) fs_garbage_link;
177 struct fail_point_entry_queue fp_entry_queue;
178 struct fail_point * fs_parent;
179 };
180
181 /**
182 * Defines stating the equivalent of probablilty one (100%)
183 */
184 enum {
185 PROB_MAX = 1000000, /* probability between zero and this number */
186 PROB_DIGITS = 6 /* number of zero's in above number */
187 };
188
189 /* Get a ref on an fp's fp_setting */
190 static inline struct fail_point_setting *fail_point_setting_get_ref(
191 struct fail_point *fp);
192 /* Release a ref on an fp_setting */
193 static inline void fail_point_setting_release_ref(struct fail_point *fp);
194 /* Allocate and initialize a struct fail_point_setting */
195 static struct fail_point_setting *fail_point_setting_new(struct
196 fail_point *);
197 /* Free a struct fail_point_setting */
198 static void fail_point_setting_destroy(struct fail_point_setting *fp_setting);
199 /* Allocate and initialize a struct fail_point_entry */
200 static struct fail_point_entry *fail_point_entry_new(struct
201 fail_point_setting *);
202 /* Free a struct fail_point_entry */
203 static void fail_point_entry_destroy(struct fail_point_entry *fp_entry);
204 /* Append fp setting to garbage list */
205 static inline void fail_point_setting_garbage_append(
206 struct fail_point_setting *fp_setting);
207 /* Swap fp's setting with fp_setting_new */
208 static inline struct fail_point_setting *
209 fail_point_swap_settings(struct fail_point *fp,
210 struct fail_point_setting *fp_setting_new);
211 /* Free up any zero-ref setting in the garbage queue */
212 static void fail_point_garbage_collect(void);
213 /* If this fail point's setting are empty, then swap it out to NULL. */
214 static inline void fail_point_eval_swap_out(struct fail_point *fp,
215 struct fail_point_setting *fp_setting);
216
217 bool
fail_point_is_off(struct fail_point * fp)218 fail_point_is_off(struct fail_point *fp)
219 {
220 bool return_val;
221 struct fail_point_setting *fp_setting;
222 struct fail_point_entry *ent;
223
224 return_val = true;
225
226 fp_setting = fail_point_setting_get_ref(fp);
227 if (fp_setting != NULL) {
228 TAILQ_FOREACH(ent, &fp_setting->fp_entry_queue,
229 fe_entries) {
230 if (!ent->fe_stale) {
231 return_val = false;
232 break;
233 }
234 }
235 }
236 fail_point_setting_release_ref(fp);
237
238 return (return_val);
239 }
240
241 /* Allocate and initialize a struct fail_point_setting */
242 static struct fail_point_setting *
fail_point_setting_new(struct fail_point * fp)243 fail_point_setting_new(struct fail_point *fp)
244 {
245 struct fail_point_setting *fs_new;
246
247 fs_new = fs_malloc();
248 fs_new->fs_parent = fp;
249 TAILQ_INIT(&fs_new->fp_entry_queue);
250
251 fail_point_setting_garbage_append(fs_new);
252
253 return (fs_new);
254 }
255
256 /* Free a struct fail_point_setting */
257 static void
fail_point_setting_destroy(struct fail_point_setting * fp_setting)258 fail_point_setting_destroy(struct fail_point_setting *fp_setting)
259 {
260 struct fail_point_entry *ent;
261
262 while (!TAILQ_EMPTY(&fp_setting->fp_entry_queue)) {
263 ent = TAILQ_FIRST(&fp_setting->fp_entry_queue);
264 TAILQ_REMOVE(&fp_setting->fp_entry_queue, ent, fe_entries);
265 fail_point_entry_destroy(ent);
266 }
267
268 fs_free(fp_setting);
269 }
270
271 /* Allocate and initialize a struct fail_point_entry */
272 static struct fail_point_entry *
fail_point_entry_new(struct fail_point_setting * fp_setting)273 fail_point_entry_new(struct fail_point_setting *fp_setting)
274 {
275 struct fail_point_entry *fp_entry;
276
277 fp_entry = fp_malloc(sizeof(struct fail_point_entry),
278 M_WAITOK | M_ZERO);
279 fp_entry->fe_parent = fp_setting->fs_parent;
280 fp_entry->fe_prob = PROB_MAX;
281 fp_entry->fe_pid = NO_PID;
282 fp_entry->fe_count = FE_COUNT_UNTRACKED;
283 TAILQ_INSERT_TAIL(&fp_setting->fp_entry_queue, fp_entry,
284 fe_entries);
285
286 return (fp_entry);
287 }
288
289 /* Free a struct fail_point_entry */
290 static void
fail_point_entry_destroy(struct fail_point_entry * fp_entry)291 fail_point_entry_destroy(struct fail_point_entry *fp_entry)
292 {
293
294 fp_free(fp_entry);
295 }
296
297 /* Get a ref on an fp's fp_setting */
298 static inline struct fail_point_setting *
fail_point_setting_get_ref(struct fail_point * fp)299 fail_point_setting_get_ref(struct fail_point *fp)
300 {
301 struct fail_point_setting *fp_setting;
302
303 /* Invariant: if we have a ref, our pointer to fp_setting is safe */
304 atomic_add_acq_32(&fp->fp_ref_cnt, 1);
305 fp_setting = fp->fp_setting;
306
307 return (fp_setting);
308 }
309
310 /* Release a ref on an fp_setting */
311 static inline void
fail_point_setting_release_ref(struct fail_point * fp)312 fail_point_setting_release_ref(struct fail_point *fp)
313 {
314
315 KASSERT(&fp->fp_ref_cnt > 0, ("Attempting to deref w/no refs"));
316 atomic_subtract_rel_32(&fp->fp_ref_cnt, 1);
317 }
318
319 /* Append fp entries to fp garbage list */
320 static inline void
fail_point_setting_garbage_append(struct fail_point_setting * fp_setting)321 fail_point_setting_garbage_append(struct fail_point_setting *fp_setting)
322 {
323
324 mtx_lock_spin(&mtx_garbage_list);
325 STAILQ_INSERT_TAIL(&fp_setting_garbage, fp_setting,
326 fs_garbage_link);
327 mtx_unlock_spin(&mtx_garbage_list);
328 }
329
330 /* Swap fp's entries with fp_setting_new */
331 static struct fail_point_setting *
fail_point_swap_settings(struct fail_point * fp,struct fail_point_setting * fp_setting_new)332 fail_point_swap_settings(struct fail_point *fp,
333 struct fail_point_setting *fp_setting_new)
334 {
335 struct fail_point_setting *fp_setting_old;
336
337 fp_setting_old = fp->fp_setting;
338 fp->fp_setting = fp_setting_new;
339
340 return (fp_setting_old);
341 }
342
343 static inline void
fail_point_eval_swap_out(struct fail_point * fp,struct fail_point_setting * fp_setting)344 fail_point_eval_swap_out(struct fail_point *fp,
345 struct fail_point_setting *fp_setting)
346 {
347
348 /* We may have already been swapped out and replaced; ignore. */
349 if (fp->fp_setting == fp_setting)
350 fail_point_swap_settings(fp, NULL);
351 }
352
353 /* Free up any zero-ref entries in the garbage queue */
354 static void
fail_point_garbage_collect(void)355 fail_point_garbage_collect(void)
356 {
357 struct fail_point_setting *fs_current, *fs_next;
358 struct fail_point_setting_garbage fp_ents_free_list;
359
360 /**
361 * We will transfer the entries to free to fp_ents_free_list while holding
362 * the spin mutex, then free it after we drop the lock. This avoids
363 * triggering witness due to sleepable mutexes in the memory
364 * allocator.
365 */
366 STAILQ_INIT(&fp_ents_free_list);
367
368 mtx_lock_spin(&mtx_garbage_list);
369 STAILQ_FOREACH_SAFE(fs_current, &fp_setting_garbage, fs_garbage_link,
370 fs_next) {
371 if (fs_current->fs_parent->fp_setting != fs_current &&
372 fs_current->fs_parent->fp_ref_cnt == 0) {
373 STAILQ_REMOVE(&fp_setting_garbage, fs_current,
374 fail_point_setting, fs_garbage_link);
375 STAILQ_INSERT_HEAD(&fp_ents_free_list, fs_current,
376 fs_garbage_link);
377 }
378 }
379 mtx_unlock_spin(&mtx_garbage_list);
380
381 STAILQ_FOREACH_SAFE(fs_current, &fp_ents_free_list, fs_garbage_link,
382 fs_next)
383 fail_point_setting_destroy(fs_current);
384 }
385
386 /* Drain out all refs from this fail point */
387 static inline void
fail_point_drain(struct fail_point * fp,int expected_ref)388 fail_point_drain(struct fail_point *fp, int expected_ref)
389 {
390 struct fail_point_setting *entries;
391
392 entries = fail_point_swap_settings(fp, NULL);
393 /**
394 * We have unpaused all threads; so we will wait no longer
395 * than the time taken for the longest remaining sleep, or
396 * the length of time of a long-running code block.
397 */
398 while (fp->fp_ref_cnt > expected_ref) {
399 wakeup(FP_PAUSE_CHANNEL(fp));
400 tsleep(&fp, PWAIT, "fail_point_drain", hz / 100);
401 }
402 if (fp->fp_callout)
403 callout_drain(fp->fp_callout);
404 fail_point_swap_settings(fp, entries);
405 }
406
407 static inline void
fail_point_pause(struct fail_point * fp,enum fail_point_return_code * pret)408 fail_point_pause(struct fail_point *fp, enum fail_point_return_code *pret)
409 {
410
411 if (fp->fp_pre_sleep_fn)
412 fp->fp_pre_sleep_fn(fp->fp_pre_sleep_arg);
413
414 tsleep(FP_PAUSE_CHANNEL(fp), 0, "failpt", 0);
415
416 if (fp->fp_post_sleep_fn)
417 fp->fp_post_sleep_fn(fp->fp_post_sleep_arg);
418 }
419
420 static inline void
fail_point_sleep(struct fail_point * fp,int msecs,enum fail_point_return_code * pret)421 fail_point_sleep(struct fail_point *fp, int msecs,
422 enum fail_point_return_code *pret)
423 {
424 int timo;
425
426 /* Convert from millisecs to ticks, rounding up */
427 timo = howmany((int64_t)msecs * hz, 1000L);
428
429 if (timo > 0) {
430 if (!(fp->fp_flags & FAIL_POINT_USE_TIMEOUT_PATH)) {
431 if (fp->fp_pre_sleep_fn)
432 fp->fp_pre_sleep_fn(fp->fp_pre_sleep_arg);
433
434 tsleep(FP_SLEEP_CHANNEL(fp), PWAIT, "failpt", timo);
435
436 if (fp->fp_post_sleep_fn)
437 fp->fp_post_sleep_fn(fp->fp_post_sleep_arg);
438 } else {
439 if (fp->fp_pre_sleep_fn)
440 fp->fp_pre_sleep_fn(fp->fp_pre_sleep_arg);
441
442 callout_reset(fp->fp_callout, timo,
443 fp->fp_post_sleep_fn, fp->fp_post_sleep_arg);
444 *pret = FAIL_POINT_RC_QUEUED;
445 }
446 }
447 }
448
449 static char *parse_fail_point(struct fail_point_setting *, char *);
450 static char *parse_term(struct fail_point_setting *, char *);
451 static char *parse_number(int *out_units, int *out_decimal, char *);
452 static char *parse_type(struct fail_point_entry *, char *);
453
454 /**
455 * Initialize a fail_point. The name is formed in a printf-like fashion
456 * from "fmt" and subsequent arguments. This function is generally used
457 * for custom failpoints located at odd places in the sysctl tree, and is
458 * not explicitly needed for standard in-line-declared failpoints.
459 *
460 * @ingroup failpoint
461 */
462 void
fail_point_init(struct fail_point * fp,const char * fmt,...)463 fail_point_init(struct fail_point *fp, const char *fmt, ...)
464 {
465 va_list ap;
466 char *name;
467 int n;
468
469 fp->fp_setting = NULL;
470 fp->fp_flags = 0;
471
472 /* Figure out the size of the name. */
473 va_start(ap, fmt);
474 n = vsnprintf(NULL, 0, fmt, ap);
475 va_end(ap);
476
477 /* Allocate the name and fill it in. */
478 name = fp_malloc(n + 1, M_WAITOK);
479 va_start(ap, fmt);
480 vsnprintf(name, n + 1, fmt, ap);
481 va_end(ap);
482
483 fp->fp_name = name;
484 fp->fp_location = "";
485 fp->fp_flags |= FAIL_POINT_DYNAMIC_NAME;
486 fp->fp_pre_sleep_fn = NULL;
487 fp->fp_pre_sleep_arg = NULL;
488 fp->fp_post_sleep_fn = NULL;
489 fp->fp_post_sleep_arg = NULL;
490 }
491
492 void
fail_point_alloc_callout(struct fail_point * fp)493 fail_point_alloc_callout(struct fail_point *fp)
494 {
495
496 /**
497 * This assumes that calls to fail_point_use_timeout_path()
498 * will not race.
499 */
500 if (fp->fp_callout != NULL)
501 return;
502 fp->fp_callout = fp_malloc(sizeof(*fp->fp_callout), M_WAITOK);
503 callout_init(fp->fp_callout, CALLOUT_MPSAFE);
504 }
505
506 /**
507 * Free the resources held by a fail_point, and wake any paused threads.
508 * Thou shalt not allow threads to hit this fail point after you enter this
509 * function, nor shall you call this multiple times for a given fp.
510 * @ingroup failpoint
511 */
512 void
fail_point_destroy(struct fail_point * fp)513 fail_point_destroy(struct fail_point *fp)
514 {
515
516 fail_point_drain(fp, 0);
517
518 if ((fp->fp_flags & FAIL_POINT_DYNAMIC_NAME) != 0) {
519 fp_free(__DECONST(void *, fp->fp_name));
520 fp->fp_name = NULL;
521 }
522 fp->fp_flags = 0;
523 if (fp->fp_callout) {
524 fp_free(fp->fp_callout);
525 fp->fp_callout = NULL;
526 }
527
528 sx_xlock(&sx_fp_set);
529 fail_point_garbage_collect();
530 sx_xunlock(&sx_fp_set);
531 }
532
533 /**
534 * This does the real work of evaluating a fail point. If the fail point tells
535 * us to return a value, this function returns 1 and fills in 'return_value'
536 * (return_value is allowed to be null). If the fail point tells us to panic,
537 * we never return. Otherwise we just return 0 after doing some work, which
538 * means "keep going".
539 */
540 enum fail_point_return_code
fail_point_eval_nontrivial(struct fail_point * fp,int * return_value)541 fail_point_eval_nontrivial(struct fail_point *fp, int *return_value)
542 {
543 bool execute = false;
544 struct fail_point_entry *ent;
545 struct fail_point_setting *fp_setting;
546 enum fail_point_return_code ret;
547 int cont;
548 int count;
549 int msecs;
550 int usecs;
551
552 ret = FAIL_POINT_RC_CONTINUE;
553 cont = 0; /* don't continue by default */
554
555 fp_setting = fail_point_setting_get_ref(fp);
556 if (fp_setting == NULL)
557 goto abort;
558
559 TAILQ_FOREACH(ent, &fp_setting->fp_entry_queue, fe_entries) {
560 if (ent->fe_stale)
561 continue;
562
563 if (ent->fe_prob < PROB_MAX &&
564 ent->fe_prob < random() % PROB_MAX)
565 continue;
566
567 if (ent->fe_pid != NO_PID && ent->fe_pid != curproc->p_pid)
568 continue;
569
570 if (ent->fe_count != FE_COUNT_UNTRACKED) {
571 count = ent->fe_count;
572 while (count > 0) {
573 if (atomic_cmpset_32(&ent->fe_count, count, count - 1)) {
574 count--;
575 execute = true;
576 break;
577 }
578 count = ent->fe_count;
579 }
580 if (execute == false)
581 /* We lost the race; consider the entry stale and bail now */
582 continue;
583 if (count == 0)
584 ent->fe_stale = true;
585 }
586
587 switch (ent->fe_type) {
588 case FAIL_POINT_PANIC:
589 panic("fail point %s panicking", fp->fp_name);
590 /* NOTREACHED */
591
592 case FAIL_POINT_RETURN:
593 if (return_value != NULL)
594 *return_value = ent->fe_arg;
595 ret = FAIL_POINT_RC_RETURN;
596 break;
597
598 case FAIL_POINT_BREAK:
599 printf("fail point %s breaking to debugger\n",
600 fp->fp_name);
601 breakpoint();
602 break;
603
604 case FAIL_POINT_PRINT:
605 printf("fail point %s executing\n", fp->fp_name);
606 cont = ent->fe_arg;
607 break;
608
609 case FAIL_POINT_SLEEP:
610 msecs = ent->fe_arg;
611 if (msecs)
612 fail_point_sleep(fp, msecs, &ret);
613 break;
614
615 case FAIL_POINT_PAUSE:
616 /**
617 * Pausing is inherently strange with multiple
618 * entries given our design. That is because some
619 * entries could be unreachable, for instance in cases like:
620 * pause->return. We can never reach the return entry.
621 * The sysctl layer actually truncates all entries after
622 * a pause for this reason.
623 */
624 fail_point_pause(fp, &ret);
625 break;
626
627 case FAIL_POINT_YIELD:
628 kern_yield(PRI_UNCHANGED);
629 break;
630
631 case FAIL_POINT_DELAY:
632 usecs = ent->fe_arg;
633 DELAY(usecs);
634 break;
635
636 default:
637 break;
638 }
639
640 if (cont == 0)
641 break;
642 }
643
644 if (fail_point_is_off(fp))
645 fail_point_eval_swap_out(fp, fp_setting);
646
647 abort:
648 fail_point_setting_release_ref(fp);
649
650 return (ret);
651 }
652
653 /**
654 * Translate internal fail_point structure into human-readable text.
655 */
656 static void
fail_point_get(struct fail_point * fp,struct sbuf * sb,bool verbose)657 fail_point_get(struct fail_point *fp, struct sbuf *sb,
658 bool verbose)
659 {
660 struct fail_point_entry *ent;
661 struct fail_point_setting *fp_setting;
662 struct fail_point_entry *fp_entry_cpy;
663 int cnt_sleeping;
664 int idx;
665 int printed_entry_count;
666
667 cnt_sleeping = 0;
668 idx = 0;
669 printed_entry_count = 0;
670
671 fp_entry_cpy = fp_malloc(sizeof(struct fail_point_entry) *
672 (FP_MAX_ENTRY_COUNT + 1), M_WAITOK);
673
674 fp_setting = fail_point_setting_get_ref(fp);
675
676 if (fp_setting != NULL) {
677 TAILQ_FOREACH(ent, &fp_setting->fp_entry_queue, fe_entries) {
678 if (ent->fe_stale)
679 continue;
680
681 KASSERT(printed_entry_count < FP_MAX_ENTRY_COUNT,
682 ("FP entry list larger than allowed"));
683
684 fp_entry_cpy[printed_entry_count] = *ent;
685 ++printed_entry_count;
686 }
687 }
688 fail_point_setting_release_ref(fp);
689
690 /* This is our equivalent of a NULL terminator */
691 fp_entry_cpy[printed_entry_count].fe_type = FAIL_POINT_INVALID;
692
693 while (idx < printed_entry_count) {
694 ent = &fp_entry_cpy[idx];
695 ++idx;
696 if (ent->fe_prob < PROB_MAX) {
697 int decimal = ent->fe_prob % (PROB_MAX / 100);
698 int units = ent->fe_prob / (PROB_MAX / 100);
699 sbuf_printf(sb, "%d", units);
700 if (decimal) {
701 int digits = PROB_DIGITS - 2;
702 while (!(decimal % 10)) {
703 digits--;
704 decimal /= 10;
705 }
706 sbuf_printf(sb, ".%0*d", digits, decimal);
707 }
708 sbuf_printf(sb, "%%");
709 }
710 if (ent->fe_count >= 0)
711 sbuf_printf(sb, "%d*", ent->fe_count);
712 sbuf_printf(sb, "%s", fail_type_strings[ent->fe_type].name);
713 if (ent->fe_arg)
714 sbuf_printf(sb, "(%d)", ent->fe_arg);
715 if (ent->fe_pid != NO_PID)
716 sbuf_printf(sb, "[pid %d]", ent->fe_pid);
717 if (TAILQ_NEXT(ent, fe_entries))
718 sbuf_cat(sb, "->");
719 }
720 if (!printed_entry_count)
721 sbuf_cat(sb, "off");
722
723 fp_free(fp_entry_cpy);
724 if (verbose) {
725 #ifdef STACK
726 /* Print number of sleeping threads. queue=0 is the argument
727 * used by msleep when sending our threads to sleep. */
728 sbuf_cat(sb, "\nsleeping_thread_stacks = {\n");
729 sleepq_sbuf_print_stacks(sb, FP_SLEEP_CHANNEL(fp), 0,
730 &cnt_sleeping);
731
732 sbuf_cat(sb, "},\n");
733 #endif
734 sbuf_printf(sb, "sleeping_thread_count = %d,\n",
735 cnt_sleeping);
736
737 #ifdef STACK
738 sbuf_cat(sb, "paused_thread_stacks = {\n");
739 sleepq_sbuf_print_stacks(sb, FP_PAUSE_CHANNEL(fp), 0,
740 &cnt_sleeping);
741
742 sbuf_cat(sb, "},\n");
743 #endif
744 sbuf_printf(sb, "paused_thread_count = %d\n",
745 cnt_sleeping);
746 }
747 }
748
749 /**
750 * Set an internal fail_point structure from a human-readable failpoint string
751 * in a lock-safe manner.
752 */
753 static int
fail_point_set(struct fail_point * fp,char * buf)754 fail_point_set(struct fail_point *fp, char *buf)
755 {
756 struct fail_point_entry *ent, *ent_next;
757 struct fail_point_setting *entries;
758 bool should_wake_paused;
759 bool should_truncate;
760 int error;
761
762 error = 0;
763 should_wake_paused = false;
764 should_truncate = false;
765
766 /* Parse new entries. */
767 /**
768 * ref protects our new malloc'd stuff from being garbage collected
769 * before we link it.
770 */
771 fail_point_setting_get_ref(fp);
772 entries = fail_point_setting_new(fp);
773 if (parse_fail_point(entries, buf) == NULL) {
774 STAILQ_REMOVE(&fp_setting_garbage, entries,
775 fail_point_setting, fs_garbage_link);
776 fail_point_setting_destroy(entries);
777 error = EINVAL;
778 goto end;
779 }
780
781 /**
782 * Transfer the entries we are going to keep to a new list.
783 * Get rid of useless zero probability entries, and entries with hit
784 * count 0.
785 * If 'off' is present, and it has no hit count set, then all entries
786 * after it are discarded since they are unreachable.
787 */
788 TAILQ_FOREACH_SAFE(ent, &entries->fp_entry_queue, fe_entries, ent_next) {
789 if (ent->fe_prob == 0 || ent->fe_count == 0) {
790 printf("Discarding entry which cannot execute %s\n",
791 fail_type_strings[ent->fe_type].name);
792 TAILQ_REMOVE(&entries->fp_entry_queue, ent,
793 fe_entries);
794 fp_free(ent);
795 continue;
796 } else if (should_truncate) {
797 printf("Discarding unreachable entry %s\n",
798 fail_type_strings[ent->fe_type].name);
799 TAILQ_REMOVE(&entries->fp_entry_queue, ent,
800 fe_entries);
801 fp_free(ent);
802 continue;
803 }
804
805 if (ent->fe_type == FAIL_POINT_OFF) {
806 should_wake_paused = true;
807 if (ent->fe_count == FE_COUNT_UNTRACKED) {
808 should_truncate = true;
809 TAILQ_REMOVE(&entries->fp_entry_queue, ent,
810 fe_entries);
811 fp_free(ent);
812 }
813 } else if (ent->fe_type == FAIL_POINT_PAUSE) {
814 should_truncate = true;
815 } else if (ent->fe_type == FAIL_POINT_SLEEP && (fp->fp_flags &
816 FAIL_POINT_NONSLEEPABLE)) {
817 /**
818 * If this fail point is annotated as being in a
819 * non-sleepable ctx, convert sleep to delay and
820 * convert the msec argument to usecs.
821 */
822 printf("Sleep call request on fail point in "
823 "non-sleepable context; using delay instead "
824 "of sleep\n");
825 ent->fe_type = FAIL_POINT_DELAY;
826 ent->fe_arg *= 1000;
827 }
828 }
829
830 if (TAILQ_EMPTY(&entries->fp_entry_queue)) {
831 entries = fail_point_swap_settings(fp, NULL);
832 if (entries != NULL)
833 wakeup(FP_PAUSE_CHANNEL(fp));
834 } else {
835 if (should_wake_paused)
836 wakeup(FP_PAUSE_CHANNEL(fp));
837 fail_point_swap_settings(fp, entries);
838 }
839
840 end:
841 #ifdef IWARNING
842 if (error)
843 IWARNING("Failed to set %s %s to %s",
844 fp->fp_name, fp->fp_location, buf);
845 else
846 INOTICE("Set %s %s to %s",
847 fp->fp_name, fp->fp_location, buf);
848 #endif /* IWARNING */
849
850 fail_point_setting_release_ref(fp);
851 return (error);
852 }
853
854 #define MAX_FAIL_POINT_BUF 1023
855
856 /**
857 * Handle kernel failpoint set/get.
858 */
859 int
fail_point_sysctl(SYSCTL_HANDLER_ARGS)860 fail_point_sysctl(SYSCTL_HANDLER_ARGS)
861 {
862 struct fail_point *fp;
863 char *buf;
864 struct sbuf sb, *sb_check;
865 int error;
866
867 buf = NULL;
868 error = 0;
869 fp = arg1;
870
871 sb_check = sbuf_new(&sb, NULL, 1024, SBUF_AUTOEXTEND);
872 if (sb_check != &sb)
873 return (ENOMEM);
874
875 sbuf_set_drain(&sb, (sbuf_drain_func *)fail_sysctl_drain_func, req);
876
877 /* Setting */
878 /**
879 * Lock protects any new entries from being garbage collected before we
880 * can link them to the fail point.
881 */
882 sx_xlock(&sx_fp_set);
883 if (req->newptr) {
884 if (req->newlen > MAX_FAIL_POINT_BUF) {
885 error = EINVAL;
886 goto out;
887 }
888
889 buf = fp_malloc(req->newlen + 1, M_WAITOK);
890
891 error = SYSCTL_IN(req, buf, req->newlen);
892 if (error)
893 goto out;
894 buf[req->newlen] = '\0';
895
896 error = fail_point_set(fp, buf);
897 }
898
899 fail_point_garbage_collect();
900 sx_xunlock(&sx_fp_set);
901
902 /* Retrieving. */
903 fail_point_get(fp, &sb, false);
904
905 out:
906 sbuf_finish(&sb);
907 sbuf_delete(&sb);
908
909 if (buf)
910 fp_free(buf);
911
912 return (error);
913 }
914
915 int
fail_point_sysctl_status(SYSCTL_HANDLER_ARGS)916 fail_point_sysctl_status(SYSCTL_HANDLER_ARGS)
917 {
918 struct fail_point *fp;
919 struct sbuf sb, *sb_check;
920
921 fp = arg1;
922
923 sb_check = sbuf_new(&sb, NULL, 1024, SBUF_AUTOEXTEND);
924 if (sb_check != &sb)
925 return (ENOMEM);
926
927 sbuf_set_drain(&sb, (sbuf_drain_func *)fail_sysctl_drain_func, req);
928
929 /* Retrieving. */
930 fail_point_get(fp, &sb, true);
931
932 sbuf_finish(&sb);
933 sbuf_delete(&sb);
934
935 /**
936 * Lock protects any new entries from being garbage collected before we
937 * can link them to the fail point.
938 */
939 sx_xlock(&sx_fp_set);
940 fail_point_garbage_collect();
941 sx_xunlock(&sx_fp_set);
942
943 return (0);
944 }
945
946 int
fail_sysctl_drain_func(void * sysctl_args,const char * buf,int len)947 fail_sysctl_drain_func(void *sysctl_args, const char *buf, int len)
948 {
949 struct sysctl_req *sa;
950 int error;
951
952 sa = sysctl_args;
953
954 error = SYSCTL_OUT(sa, buf, len);
955
956 if (error == ENOMEM)
957 return (-1);
958 else
959 return (len);
960 }
961
962 /**
963 * Internal helper function to translate a human-readable failpoint string
964 * into a internally-parsable fail_point structure.
965 */
966 static char *
parse_fail_point(struct fail_point_setting * ents,char * p)967 parse_fail_point(struct fail_point_setting *ents, char *p)
968 {
969 /* <fail_point> ::
970 * <term> ( "->" <term> )*
971 */
972 uint8_t term_count;
973
974 term_count = 1;
975
976 p = parse_term(ents, p);
977 if (p == NULL)
978 return (NULL);
979
980 while (*p != '\0') {
981 term_count++;
982 if (p[0] != '-' || p[1] != '>' ||
983 (p = parse_term(ents, p+2)) == NULL ||
984 term_count > FP_MAX_ENTRY_COUNT)
985 return (NULL);
986 }
987 return (p);
988 }
989
990 /**
991 * Internal helper function to parse an individual term from a failpoint.
992 */
993 static char *
parse_term(struct fail_point_setting * ents,char * p)994 parse_term(struct fail_point_setting *ents, char *p)
995 {
996 struct fail_point_entry *ent;
997
998 ent = fail_point_entry_new(ents);
999
1000 /*
1001 * <term> ::
1002 * ( (<float> "%") | (<integer> "*" ) )*
1003 * <type>
1004 * [ "(" <integer> ")" ]
1005 * [ "[pid " <integer> "]" ]
1006 */
1007
1008 /* ( (<float> "%") | (<integer> "*" ) )* */
1009 while (isdigit(*p) || *p == '.') {
1010 int units, decimal;
1011
1012 p = parse_number(&units, &decimal, p);
1013 if (p == NULL)
1014 return (NULL);
1015
1016 if (*p == '%') {
1017 if (units > 100) /* prevent overflow early */
1018 units = 100;
1019 ent->fe_prob = units * (PROB_MAX / 100) + decimal;
1020 if (ent->fe_prob > PROB_MAX)
1021 ent->fe_prob = PROB_MAX;
1022 } else if (*p == '*') {
1023 if (!units || units < 0 || decimal)
1024 return (NULL);
1025 ent->fe_count = units;
1026 } else
1027 return (NULL);
1028 p++;
1029 }
1030
1031 /* <type> */
1032 p = parse_type(ent, p);
1033 if (p == NULL)
1034 return (NULL);
1035 if (*p == '\0')
1036 return (p);
1037
1038 /* [ "(" <integer> ")" ] */
1039 if (*p != '(')
1040 return (p);
1041 p++;
1042 if (!isdigit(*p) && *p != '-')
1043 return (NULL);
1044 ent->fe_arg = strtol(p, &p, 0);
1045 if (*p++ != ')')
1046 return (NULL);
1047
1048 /* [ "[pid " <integer> "]" ] */
1049 #define PID_STRING "[pid "
1050 if (strncmp(p, PID_STRING, sizeof(PID_STRING) - 1) != 0)
1051 return (p);
1052 p += sizeof(PID_STRING) - 1;
1053 if (!isdigit(*p))
1054 return (NULL);
1055 ent->fe_pid = strtol(p, &p, 0);
1056 if (*p++ != ']')
1057 return (NULL);
1058
1059 return (p);
1060 }
1061
1062 /**
1063 * Internal helper function to parse a numeric for a failpoint term.
1064 */
1065 static char *
parse_number(int * out_units,int * out_decimal,char * p)1066 parse_number(int *out_units, int *out_decimal, char *p)
1067 {
1068 char *old_p;
1069
1070 /**
1071 * <number> ::
1072 * <integer> [ "." <integer> ] |
1073 * "." <integer>
1074 */
1075
1076 /* whole part */
1077 old_p = p;
1078 *out_units = strtol(p, &p, 10);
1079 if (p == old_p && *p != '.')
1080 return (NULL);
1081
1082 /* fractional part */
1083 *out_decimal = 0;
1084 if (*p == '.') {
1085 int digits = 0;
1086 p++;
1087 while (isdigit(*p)) {
1088 int digit = *p - '0';
1089 if (digits < PROB_DIGITS - 2)
1090 *out_decimal = *out_decimal * 10 + digit;
1091 else if (digits == PROB_DIGITS - 2 && digit >= 5)
1092 (*out_decimal)++;
1093 digits++;
1094 p++;
1095 }
1096 if (!digits) /* need at least one digit after '.' */
1097 return (NULL);
1098 while (digits++ < PROB_DIGITS - 2) /* add implicit zeros */
1099 *out_decimal *= 10;
1100 }
1101
1102 return (p); /* success */
1103 }
1104
1105 /**
1106 * Internal helper function to parse an individual type for a failpoint term.
1107 */
1108 static char *
parse_type(struct fail_point_entry * ent,char * beg)1109 parse_type(struct fail_point_entry *ent, char *beg)
1110 {
1111 enum fail_point_t type;
1112 int len;
1113
1114 for (type = FAIL_POINT_OFF; type < FAIL_POINT_NUMTYPES; type++) {
1115 len = fail_type_strings[type].nmlen;
1116 if (strncmp(fail_type_strings[type].name, beg, len) == 0) {
1117 ent->fe_type = type;
1118 return (beg + len);
1119 }
1120 }
1121 return (NULL);
1122 }
1123
1124 /* The fail point sysctl tree. */
1125 SYSCTL_NODE(_debug, OID_AUTO, fail_point, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1126 "fail points");
1127
1128 /* Debugging/testing stuff for fail point */
1129 static int
sysctl_test_fail_point(SYSCTL_HANDLER_ARGS)1130 sysctl_test_fail_point(SYSCTL_HANDLER_ARGS)
1131 {
1132
1133 KFAIL_POINT_RETURN(DEBUG_FP, test_fail_point);
1134 return (0);
1135 }
1136 SYSCTL_OID(_debug_fail_point, OID_AUTO, test_trigger_fail_point,
1137 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT, NULL, 0,
1138 sysctl_test_fail_point, "A",
1139 "Trigger test fail points");
1140