* Corresponding ZRAM slot should be locked.
  */
 static int zram_recompress(struct zram *zram, u32 index, struct page *page,
-                          u32 threshold, u32 prio, u32 prio_max)
+                          u64 *num_recomp_pages, u32 threshold, u32 prio,
+                          u32 prio_max)
 {
        struct zcomp_strm *zstrm = NULL;
        unsigned long handle_old;
        if (!zstrm)
                return 0;
 
+       /*
+        * Decrement the limit (if set) on pages we can recompress, even
+        * when current recompression was unsuccessful or did not compress
+        * the page below the threshold, because we still spent resources
+        * on it.
+        */
+       if (*num_recomp_pages)
+               *num_recomp_pages -= 1;
+
        if (class_index_new >= class_index_old) {
                /*
                 * Secondary algorithms failed to re-compress the page
        struct zram *zram = dev_to_zram(dev);
        unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
        char *args, *param, *val, *algo = NULL;
+       u64 num_recomp_pages = ULLONG_MAX;
        u32 mode = 0, threshold = 0;
        unsigned long index;
        struct page *page;
                        continue;
                }
 
+               if (!strcmp(param, "max_pages")) {
+                       /*
+                        * Limit the number of entries (pages) we attempt to
+                        * recompress.
+                        */
+                       ret = kstrtoull(val, 10, &num_recomp_pages);
+                       if (ret)
+                               return ret;
+                       continue;
+               }
+
                if (!strcmp(param, "threshold")) {
                        /*
                         * We will re-compress only idle objects equal or
        for (index = 0; index < nr_pages; index++) {
                int err = 0;
 
+               if (!num_recomp_pages)
+                       break;
+
                zram_slot_lock(zram, index);
 
                if (!zram_allocated(zram, index))
                    zram_test_flag(zram, index, ZRAM_INCOMPRESSIBLE))
                        goto next;
 
-               err = zram_recompress(zram, index, page, threshold,
-                                     prio, prio_max);
+               err = zram_recompress(zram, index, page, &num_recomp_pages,
+                                     threshold, prio, prio_max);
 next:
                zram_slot_unlock(zram, index);
                if (err) {