Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * ratelimit.c - Do something with rate limit.
0004  *
0005  * Isolated from kernel/printk.c by Dave Young <hidave.darkstar@gmail.com>
0006  *
0007  * 2008-05-01 rewrite the function and use a ratelimit_state data struct as
0008  * parameter. Now every user can use their own standalone ratelimit_state.
0009  */
0010 
0011 #include <linux/ratelimit.h>
0012 #include <linux/jiffies.h>
0013 #include <linux/export.h>
0014 
0015 /*
0016  * __ratelimit - rate limiting
0017  * @rs: ratelimit_state data
0018  * @func: name of calling function
0019  *
0020  * This enforces a rate limit: not more than @rs->burst callbacks
0021  * in every @rs->interval
0022  *
0023  * RETURNS:
0024  * 0 means callbacks will be suppressed.
0025  * 1 means go ahead and do it.
0026  */
0027 int ___ratelimit(struct ratelimit_state *rs, const char *func)
0028 {
0029     /* Paired with WRITE_ONCE() in .proc_handler().
0030      * Changing two values seperately could be inconsistent
0031      * and some message could be lost.  (See: net_ratelimit_state).
0032      */
0033     int interval = READ_ONCE(rs->interval);
0034     int burst = READ_ONCE(rs->burst);
0035     unsigned long flags;
0036     int ret;
0037 
0038     if (!interval)
0039         return 1;
0040 
0041     /*
0042      * If we contend on this state's lock then almost
0043      * by definition we are too busy to print a message,
0044      * in addition to the one that will be printed by
0045      * the entity that is holding the lock already:
0046      */
0047     if (!raw_spin_trylock_irqsave(&rs->lock, flags))
0048         return 0;
0049 
0050     if (!rs->begin)
0051         rs->begin = jiffies;
0052 
0053     if (time_is_before_jiffies(rs->begin + interval)) {
0054         if (rs->missed) {
0055             if (!(rs->flags & RATELIMIT_MSG_ON_RELEASE)) {
0056                 printk_deferred(KERN_WARNING
0057                         "%s: %d callbacks suppressed\n",
0058                         func, rs->missed);
0059                 rs->missed = 0;
0060             }
0061         }
0062         rs->begin   = jiffies;
0063         rs->printed = 0;
0064     }
0065     if (burst && burst > rs->printed) {
0066         rs->printed++;
0067         ret = 1;
0068     } else {
0069         rs->missed++;
0070         ret = 0;
0071     }
0072     raw_spin_unlock_irqrestore(&rs->lock, flags);
0073 
0074     return ret;
0075 }
0076 EXPORT_SYMBOL(___ratelimit);