1 // SPDX-License-Identifier: CDDL-1.0 2 /* 3 * CDDL HEADER START 4 * 5 * The contents of this file are subject to the terms of the 6 * Common Development and Distribution License (the "License"). 7 * You may not use this file except in compliance with the License. 8 * 9 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE 10 * or https://opensource.org/licenses/CDDL-1.0. 11 * See the License for the specific language governing permissions 12 * and limitations under the License. 13 * 14 * When distributing Covered Code, include this CDDL HEADER in each 15 * file and include the License file at usr/src/OPENSOLARIS.LICENSE. 16 * If applicable, add the following below this CDDL HEADER, with the 17 * fields enclosed by brackets "[]" replaced with your own identifying 18 * information: Portions Copyright [yyyy] [name of copyright owner] 19 * 20 * CDDL HEADER END 21 */ 22 23 /* 24 * Copyright (c) 2017, Lawrence Livermore National Security, LLC. 25 */ 26 27 #include <sys/zfs_ratelimit.h> 28 29 /* 30 * Initialize rate limit struct 31 * 32 * rl: zfs_ratelimit_t struct 33 * burst: Number to allow in an interval before rate limiting 34 * interval: Interval time in seconds 35 */ 36 void 37 zfs_ratelimit_init(zfs_ratelimit_t *rl, unsigned int *burst, 38 unsigned int interval) 39 { 40 rl->count = 0; 41 rl->start = 0; 42 rl->interval = interval; 43 rl->burst = burst; 44 mutex_init(&rl->lock, NULL, MUTEX_DEFAULT, NULL); 45 } 46 47 /* 48 * Finalize rate limit struct 49 * 50 * rl: zfs_ratelimit_t struct 51 */ 52 void 53 zfs_ratelimit_fini(zfs_ratelimit_t *rl) 54 { 55 mutex_destroy(&rl->lock); 56 } 57 58 /* 59 * Re-implementation of the kernel's __ratelimit() function 60 * 61 * We had to write our own rate limiter because the kernel's __ratelimit() 62 * function annoyingly prints out how many times it rate limited to the kernel 63 * logs (and there's no way to turn it off): 64 * 65 * __ratelimit: 59 callbacks suppressed 66 * 67 * If the kernel ever allows us to disable these prints, we should go back to 68 * using __ratelimit() instead. 69 * 70 * Return values are the same as __ratelimit(): 71 * 72 * 0: If we're rate limiting 73 * 1: If we're not rate limiting. 74 */ 75 int 76 zfs_ratelimit(zfs_ratelimit_t *rl) 77 { 78 hrtime_t now; 79 80 hrtime_t elapsed; 81 int error = 1; 82 83 mutex_enter(&rl->lock); 84 85 now = gethrtime(); 86 elapsed = now - rl->start; 87 88 rl->count++; 89 if (NSEC2SEC(elapsed) >= rl->interval) { 90 rl->start = now; 91 rl->count = 0; 92 } else { 93 if (rl->count >= *rl->burst) { 94 error = 0; /* We're ratelimiting */ 95 } 96 } 97 mutex_exit(&rl->lock); 98 99 return (error); 100 } 101