kernel - Implement CPU localization hinting for low level page allocations
[dragonfly.git] / sys / vm / vm_swapcache.c
1 /*
2  * (MPSAFE)
3  *
4  * Copyright (c) 2010 The DragonFly Project.  All rights reserved.
5  *
6  * This code is derived from software contributed to The DragonFly Project
7  * by Matthew Dillon <dillon@backplane.com>
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  * 3. Neither the name of The DragonFly Project nor the names of its
20  *    contributors may be used to endorse or promote products derived
21  *    from this software without specific, prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
27  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
29  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
31  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
33  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36
37 /*
38  * Implement the swapcache daemon.  When enabled swap is assumed to be
39  * configured on a fast storage device such as a SSD.  Swap is assigned
40  * to clean vnode-backed pages in the inactive queue, clustered by object
41  * if possible, and written out.  The swap assignment sticks around even
42  * after the underlying pages have been recycled.
43  *
44  * The daemon manages write bandwidth based on sysctl settings to control
45  * wear on the SSD.
46  *
47  * The vnode strategy code will check for the swap assignments and divert
48  * reads to the swap device when the data is present in the swapcache.
49  *
50  * This operates on both regular files and the block device vnodes used by
51  * filesystems to manage meta-data.
52  */
53
54 #include "opt_vm.h"
55 #include <sys/param.h>
56 #include <sys/systm.h>
57 #include <sys/kernel.h>
58 #include <sys/proc.h>
59 #include <sys/kthread.h>
60 #include <sys/resourcevar.h>
61 #include <sys/signalvar.h>
62 #include <sys/vnode.h>
63 #include <sys/vmmeter.h>
64 #include <sys/sysctl.h>
65 #include <sys/eventhandler.h>
66
67 #include <vm/vm.h>
68 #include <vm/vm_param.h>
69 #include <sys/lock.h>
70 #include <vm/vm_object.h>
71 #include <vm/vm_page.h>
72 #include <vm/vm_map.h>
73 #include <vm/vm_pageout.h>
74 #include <vm/vm_pager.h>
75 #include <vm/swap_pager.h>
76 #include <vm/vm_extern.h>
77
78 #include <sys/thread2.h>
79 #include <sys/spinlock2.h>
80 #include <vm/vm_page2.h>
81
82 /* the kernel process "vm_pageout"*/
83 static int vm_swapcached_flush (vm_page_t m, int isblkdev);
84 static int vm_swapcache_test(vm_page_t m);
85 static int vm_swapcache_writing_heuristic(void);
86 static int vm_swapcache_writing(vm_page_t marker, int count, int scount);
87 static void vm_swapcache_cleaning(vm_object_t marker,
88                         struct vm_object_hash **swindexp);
89 static void vm_swapcache_movemarker(vm_object_t marker,
90                         struct vm_object_hash *swindex, vm_object_t object);
91 struct thread *swapcached_thread;
92
93 SYSCTL_NODE(_vm, OID_AUTO, swapcache, CTLFLAG_RW, NULL, NULL);
94
95 int vm_swapcache_read_enable;
96 int vm_swapcache_inactive_heuristic;
97 static int vm_swapcache_sleep;
98 static int vm_swapcache_maxscan = PQ_L2_SIZE * 8;
99 static int vm_swapcache_maxlaunder = PQ_L2_SIZE * 4;
100 static int vm_swapcache_data_enable = 0;
101 static int vm_swapcache_meta_enable = 0;
102 static int vm_swapcache_maxswappct = 75;
103 static int vm_swapcache_hysteresis;
104 static int vm_swapcache_min_hysteresis;
105 int vm_swapcache_use_chflags = 1;       /* require chflags cache */
106 static int64_t vm_swapcache_minburst = 10000000LL;      /* 10MB */
107 static int64_t vm_swapcache_curburst = 4000000000LL;    /* 4G after boot */
108 static int64_t vm_swapcache_maxburst = 2000000000LL;    /* 2G nominal max */
109 static int64_t vm_swapcache_accrate = 100000LL;         /* 100K/s */
110 static int64_t vm_swapcache_write_count;
111 static int64_t vm_swapcache_maxfilesize;
112 static int64_t vm_swapcache_cleanperobj = 16*1024*1024;
113
114 SYSCTL_INT(_vm_swapcache, OID_AUTO, maxlaunder,
115         CTLFLAG_RW, &vm_swapcache_maxlaunder, 0, "");
116 SYSCTL_INT(_vm_swapcache, OID_AUTO, maxscan,
117         CTLFLAG_RW, &vm_swapcache_maxscan, 0, "");
118
119 SYSCTL_INT(_vm_swapcache, OID_AUTO, data_enable,
120         CTLFLAG_RW, &vm_swapcache_data_enable, 0, "");
121 SYSCTL_INT(_vm_swapcache, OID_AUTO, meta_enable,
122         CTLFLAG_RW, &vm_swapcache_meta_enable, 0, "");
123 SYSCTL_INT(_vm_swapcache, OID_AUTO, read_enable,
124         CTLFLAG_RW, &vm_swapcache_read_enable, 0, "");
125 SYSCTL_INT(_vm_swapcache, OID_AUTO, maxswappct,
126         CTLFLAG_RW, &vm_swapcache_maxswappct, 0, "");
127 SYSCTL_INT(_vm_swapcache, OID_AUTO, hysteresis,
128         CTLFLAG_RD, &vm_swapcache_hysteresis, 0, "");
129 SYSCTL_INT(_vm_swapcache, OID_AUTO, min_hysteresis,
130         CTLFLAG_RW, &vm_swapcache_min_hysteresis, 0, "");
131 SYSCTL_INT(_vm_swapcache, OID_AUTO, use_chflags,
132         CTLFLAG_RW, &vm_swapcache_use_chflags, 0, "");
133
134 SYSCTL_QUAD(_vm_swapcache, OID_AUTO, minburst,
135         CTLFLAG_RW, &vm_swapcache_minburst, 0, "");
136 SYSCTL_QUAD(_vm_swapcache, OID_AUTO, curburst,
137         CTLFLAG_RW, &vm_swapcache_curburst, 0, "");
138 SYSCTL_QUAD(_vm_swapcache, OID_AUTO, maxburst,
139         CTLFLAG_RW, &vm_swapcache_maxburst, 0, "");
140 SYSCTL_QUAD(_vm_swapcache, OID_AUTO, maxfilesize,
141         CTLFLAG_RW, &vm_swapcache_maxfilesize, 0, "");
142 SYSCTL_QUAD(_vm_swapcache, OID_AUTO, accrate,
143         CTLFLAG_RW, &vm_swapcache_accrate, 0, "");
144 SYSCTL_QUAD(_vm_swapcache, OID_AUTO, write_count,
145         CTLFLAG_RW, &vm_swapcache_write_count, 0, "");
146 SYSCTL_QUAD(_vm_swapcache, OID_AUTO, cleanperobj,
147         CTLFLAG_RW, &vm_swapcache_cleanperobj, 0, "");
148
149 #define SWAPMAX(adj)    \
150         ((int64_t)vm_swap_max * (vm_swapcache_maxswappct + (adj)) / 100)
151
152 /*
153  * When shutting down the machine we want to stop swapcache operation
154  * immediately so swap is not accessed after devices have been shuttered.
155  */
156 static void
157 shutdown_swapcache(void *arg __unused)
158 {
159         vm_swapcache_read_enable = 0;
160         vm_swapcache_data_enable = 0;
161         vm_swapcache_meta_enable = 0;
162         wakeup(&vm_swapcache_sleep);    /* shortcut 5-second wait */
163 }
164
165 /*
166  * vm_swapcached is the high level pageout daemon.
167  *
168  * No requirements.
169  */
170 static void
171 vm_swapcached_thread(void)
172 {
173         enum { SWAPC_WRITING, SWAPC_CLEANING } state = SWAPC_WRITING;
174         enum { SWAPB_BURSTING, SWAPB_RECOVERING } burst = SWAPB_BURSTING;
175         static struct vm_page page_marker[PQ_L2_SIZE];
176         static struct vm_object swmarker;
177         static struct vm_object_hash *swindex;
178         int q;
179
180         /*
181          * Thread setup
182          */
183         curthread->td_flags |= TDF_SYSTHREAD;
184         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
185                               swapcached_thread, SHUTDOWN_PRI_FIRST);
186         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_swapcache,
187                               NULL, SHUTDOWN_PRI_SECOND);
188
189         /*
190          * Initialize our marker for the inactive scan (SWAPC_WRITING)
191          */
192         bzero(&page_marker, sizeof(page_marker));
193         for (q = 0; q < PQ_L2_SIZE; ++q) {
194                 page_marker[q].flags = PG_BUSY | PG_FICTITIOUS | PG_MARKER;
195                 page_marker[q].queue = PQ_INACTIVE + q;
196                 page_marker[q].pc = q;
197                 page_marker[q].wire_count = 1;
198                 vm_page_queues_spin_lock(PQ_INACTIVE + q);
199                 TAILQ_INSERT_HEAD(
200                         &vm_page_queues[PQ_INACTIVE + q].pl,
201                         &page_marker[q], pageq);
202                 vm_page_queues_spin_unlock(PQ_INACTIVE + q);
203         }
204
205         vm_swapcache_min_hysteresis = 1024;
206         vm_swapcache_hysteresis = vm_swapcache_min_hysteresis;
207         vm_swapcache_inactive_heuristic = -vm_swapcache_hysteresis;
208
209         /*
210          * Initialize our marker for the vm_object scan (SWAPC_CLEANING)
211          */
212         bzero(&swmarker, sizeof(swmarker));
213         swmarker.type = OBJT_MARKER;
214         swindex = &vm_object_hash[0];
215         lwkt_gettoken(&swindex->token);
216         TAILQ_INSERT_HEAD(&swindex->list, &swmarker, object_list);
217         lwkt_reltoken(&swindex->token);
218
219         for (;;) {
220                 int reached_end;
221                 int scount;
222                 int count;
223
224                 /*
225                  * Handle shutdown
226                  */
227                 kproc_suspend_loop();
228
229                 /*
230                  * Check every 5 seconds when not enabled or if no swap
231                  * is present.
232                  */
233                 if ((vm_swapcache_data_enable == 0 &&
234                      vm_swapcache_meta_enable == 0 &&
235                      vm_swap_cache_use <= SWAPMAX(0)) ||
236                     vm_swap_max == 0) {
237                         tsleep(&vm_swapcache_sleep, 0, "csleep", hz * 5);
238                         continue;
239                 }
240
241                 /*
242                  * Polling rate when enabled is approximately 10 hz.
243                  */
244                 tsleep(&vm_swapcache_sleep, 0, "csleep", hz / 10);
245
246                 /*
247                  * State hysteresis.  Generate write activity up to 75% of
248                  * swap, then clean out swap assignments down to 70%, then
249                  * repeat.
250                  */
251                 if (state == SWAPC_WRITING) {
252                         if (vm_swap_cache_use > SWAPMAX(0))
253                                 state = SWAPC_CLEANING;
254                 } else {
255                         if (vm_swap_cache_use < SWAPMAX(-10))
256                                 state = SWAPC_WRITING;
257                 }
258
259                 /*
260                  * We are allowed to continue accumulating burst value
261                  * in either state.  Allow the user to set curburst > maxburst
262                  * for the initial load-in.
263                  */
264                 if (vm_swapcache_curburst < vm_swapcache_maxburst) {
265                         vm_swapcache_curburst += vm_swapcache_accrate / 10;
266                         if (vm_swapcache_curburst > vm_swapcache_maxburst)
267                                 vm_swapcache_curburst = vm_swapcache_maxburst;
268                 }
269
270                 /*
271                  * We don't want to nickle-and-dime the scan as that will
272                  * create unnecessary fragmentation.  The minimum burst
273                  * is one-seconds worth of accumulation.
274                  */
275                 if (state != SWAPC_WRITING) {
276                         vm_swapcache_cleaning(&swmarker, &swindex);
277                         continue;
278                 }
279                 if (vm_swapcache_curburst < vm_swapcache_accrate)
280                         continue;
281
282                 reached_end = 0;
283                 count = vm_swapcache_maxlaunder / PQ_L2_SIZE + 2;
284                 scount = vm_swapcache_maxscan / PQ_L2_SIZE + 2;
285
286                 if (burst == SWAPB_BURSTING) {
287                         if (vm_swapcache_writing_heuristic()) {
288                                 for (q = 0; q < PQ_L2_SIZE; ++q) {
289                                         reached_end +=
290                                                 vm_swapcache_writing(
291                                                         &page_marker[q],
292                                                         count,
293                                                         scount);
294                                 }
295                         }
296                         if (vm_swapcache_curburst <= 0)
297                                 burst = SWAPB_RECOVERING;
298                 } else if (vm_swapcache_curburst > vm_swapcache_minburst) {
299                         if (vm_swapcache_writing_heuristic()) {
300                                 for (q = 0; q < PQ_L2_SIZE; ++q) {
301                                         reached_end +=
302                                                 vm_swapcache_writing(
303                                                         &page_marker[q],
304                                                         count,
305                                                         scount);
306                                 }
307                         }
308                         burst = SWAPB_BURSTING;
309                 }
310                 if (reached_end == PQ_L2_SIZE) {
311                         vm_swapcache_inactive_heuristic =
312                                 -vm_swapcache_hysteresis;
313                 }
314         }
315
316         /*
317          * Cleanup (NOT REACHED)
318          */
319         for (q = 0; q < PQ_L2_SIZE; ++q) {
320                 vm_page_queues_spin_lock(PQ_INACTIVE + q);
321                 TAILQ_REMOVE(
322                         &vm_page_queues[PQ_INACTIVE + q].pl,
323                         &page_marker[q], pageq);
324                 vm_page_queues_spin_unlock(PQ_INACTIVE + q);
325         }
326
327         lwkt_gettoken(&swindex->token);
328         TAILQ_REMOVE(&swindex->list, &swmarker, object_list);
329         lwkt_reltoken(&swindex->token);
330 }
331
332 static struct kproc_desc swpc_kp = {
333         "swapcached",
334         vm_swapcached_thread,
335         &swapcached_thread
336 };
337 SYSINIT(swapcached, SI_SUB_KTHREAD_PAGE, SI_ORDER_SECOND, kproc_start, &swpc_kp);
338
339 /*
340  * Deal with an overflow of the heuristic counter or if the user
341  * manually changes the hysteresis.
342  *
343  * Try to avoid small incremental pageouts by waiting for enough
344  * pages to buildup in the inactive queue to hopefully get a good
345  * burst in.  This heuristic is bumped by the VM system and reset
346  * when our scan hits the end of the queue.
347  *
348  * Return TRUE if we need to take a writing pass.
349  */
350 static int
351 vm_swapcache_writing_heuristic(void)
352 {
353         int hyst;
354
355         hyst = vmstats.v_inactive_count / 4;
356         if (hyst < vm_swapcache_min_hysteresis)
357                 hyst = vm_swapcache_min_hysteresis;
358         cpu_ccfence();
359         vm_swapcache_hysteresis = hyst;
360
361         if (vm_swapcache_inactive_heuristic < -hyst)
362                 vm_swapcache_inactive_heuristic = -hyst;
363
364         return (vm_swapcache_inactive_heuristic >= 0);
365 }
366
367 /*
368  * Take a writing pass on one of the inactive queues, return non-zero if
369  * we hit the end of the queue.
370  */
371 static int
372 vm_swapcache_writing(vm_page_t marker, int count, int scount)
373 {
374         vm_object_t object;
375         struct vnode *vp;
376         vm_page_t m;
377         int isblkdev;
378
379         /*
380          * Scan the inactive queue from our marker to locate
381          * suitable pages to push to the swap cache.
382          *
383          * We are looking for clean vnode-backed pages.
384          */
385         vm_page_queues_spin_lock(marker->queue);
386         while ((m = TAILQ_NEXT(marker, pageq)) != NULL &&
387                count > 0 && scount-- > 0) {
388                 KKASSERT(m->queue == marker->queue);
389
390                 /*
391                  * Stop using swap if paniced, dumping, or dumped.
392                  * Don't try to write if our curburst has been exhausted.
393                  */
394                 if (panicstr || dumping)
395                         break;
396                 if (vm_swapcache_curburst < 0)
397                         break;
398
399                 /*
400                  * Move marker
401                  */
402                 TAILQ_REMOVE(
403                         &vm_page_queues[marker->queue].pl, marker, pageq);
404                 TAILQ_INSERT_AFTER(
405                         &vm_page_queues[marker->queue].pl, m, marker, pageq);
406
407                 /*
408                  * Ignore markers and ignore pages that already have a swap
409                  * assignment.
410                  */
411                 if (m->flags & (PG_MARKER | PG_SWAPPED))
412                         continue;
413                 if (vm_page_busy_try(m, TRUE))
414                         continue;
415                 vm_page_queues_spin_unlock(marker->queue);
416
417                 if ((object = m->object) == NULL) {
418                         vm_page_wakeup(m);
419                         vm_page_queues_spin_lock(marker->queue);
420                         continue;
421                 }
422                 vm_object_hold(object);
423                 if (m->object != object) {
424                         vm_object_drop(object);
425                         vm_page_wakeup(m);
426                         vm_page_queues_spin_lock(marker->queue);
427                         continue;
428                 }
429                 if (vm_swapcache_test(m)) {
430                         vm_object_drop(object);
431                         vm_page_wakeup(m);
432                         vm_page_queues_spin_lock(marker->queue);
433                         continue;
434                 }
435
436                 vp = object->handle;
437                 if (vp == NULL) {
438                         vm_object_drop(object);
439                         vm_page_wakeup(m);
440                         vm_page_queues_spin_lock(marker->queue);
441                         continue;
442                 }
443
444                 switch(vp->v_type) {
445                 case VREG:
446                         /*
447                          * PG_NOTMETA generically means 'don't swapcache this',
448                          * and HAMMER will set this for regular data buffers
449                          * (and leave it unset for meta-data buffers) as
450                          * appropriate when double buffering is enabled.
451                          */
452                         if (m->flags & PG_NOTMETA) {
453                                 vm_object_drop(object);
454                                 vm_page_wakeup(m);
455                                 vm_page_queues_spin_lock(marker->queue);
456                                 continue;
457                         }
458
459                         /*
460                          * If data_enable is 0 do not try to swapcache data.
461                          * If use_chflags is set then only swapcache data for
462                          * VSWAPCACHE marked vnodes, otherwise any vnode.
463                          */
464                         if (vm_swapcache_data_enable == 0 ||
465                             ((vp->v_flag & VSWAPCACHE) == 0 &&
466                              vm_swapcache_use_chflags)) {
467                                 vm_object_drop(object);
468                                 vm_page_wakeup(m);
469                                 vm_page_queues_spin_lock(marker->queue);
470                                 continue;
471                         }
472                         if (vm_swapcache_maxfilesize &&
473                             object->size >
474                             (vm_swapcache_maxfilesize >> PAGE_SHIFT)) {
475                                 vm_object_drop(object);
476                                 vm_page_wakeup(m);
477                                 vm_page_queues_spin_lock(marker->queue);
478                                 continue;
479                         }
480                         isblkdev = 0;
481                         break;
482                 case VCHR:
483                         /*
484                          * PG_NOTMETA generically means 'don't swapcache this',
485                          * and HAMMER will set this for regular data buffers
486                          * (and leave it unset for meta-data buffers) as
487                          * appropriate when double buffering is enabled.
488                          */
489                         if (m->flags & PG_NOTMETA) {
490                                 vm_object_drop(object);
491                                 vm_page_wakeup(m);
492                                 vm_page_queues_spin_lock(marker->queue);
493                                 continue;
494                         }
495                         if (vm_swapcache_meta_enable == 0) {
496                                 vm_object_drop(object);
497                                 vm_page_wakeup(m);
498                                 vm_page_queues_spin_lock(marker->queue);
499                                 continue;
500                         }
501                         isblkdev = 1;
502                         break;
503                 default:
504                         vm_object_drop(object);
505                         vm_page_wakeup(m);
506                         vm_page_queues_spin_lock(marker->queue);
507                         continue;
508                 }
509
510
511                 /*
512                  * Assign swap and initiate I/O.
513                  *
514                  * (adjust for the --count which also occurs in the loop)
515                  */
516                 count -= vm_swapcached_flush(m, isblkdev);
517
518                 /*
519                  * Setup for next loop using marker.
520                  */
521                 vm_object_drop(object);
522                 vm_page_queues_spin_lock(marker->queue);
523         }
524
525         /*
526          * The marker could wind up at the end, which is ok.  If we hit the
527          * end of the list adjust the heuristic.
528          *
529          * Earlier inactive pages that were dirty and become clean
530          * are typically moved to the end of PQ_INACTIVE by virtue
531          * of vfs_vmio_release() when they become unwired from the
532          * buffer cache.
533          */
534         vm_page_queues_spin_unlock(marker->queue);
535
536         /*
537          * m invalid but can be used to test for NULL
538          */
539         return (m == NULL);
540 }
541
542 /*
543  * Flush the specified page using the swap_pager.  The page
544  * must be busied by the caller and its disposition will become
545  * the responsibility of this function.
546  *
547  * Try to collect surrounding pages, including pages which may
548  * have already been assigned swap.  Try to cluster within a
549  * contiguous aligned SMAP_META_PAGES (typ 16 x PAGE_SIZE) block
550  * to match what swap_pager_putpages() can do.
551  *
552  * We also want to try to match against the buffer cache blocksize
553  * but we don't really know what it is here.  Since the buffer cache
554  * wires and unwires pages in groups the fact that we skip wired pages
555  * should be sufficient.
556  *
557  * Returns a count of pages we might have flushed (minimum 1)
558  */
559 static
560 int
561 vm_swapcached_flush(vm_page_t m, int isblkdev)
562 {
563         vm_object_t object;
564         vm_page_t marray[SWAP_META_PAGES];
565         vm_pindex_t basei;
566         int rtvals[SWAP_META_PAGES];
567         int x;
568         int i;
569         int j;
570         int count;
571         int error;
572
573         vm_page_io_start(m);
574         vm_page_protect(m, VM_PROT_READ);
575         object = m->object;
576         vm_object_hold(object);
577
578         /*
579          * Try to cluster around (m), keeping in mind that the swap pager
580          * can only do SMAP_META_PAGES worth of continguous write.
581          */
582         x = (int)m->pindex & SWAP_META_MASK;
583         marray[x] = m;
584         basei = m->pindex;
585         vm_page_wakeup(m);
586
587         for (i = x - 1; i >= 0; --i) {
588                 m = vm_page_lookup_busy_try(object, basei - x + i,
589                                             TRUE, &error);
590                 if (error || m == NULL)
591                         break;
592                 if (vm_swapcache_test(m)) {
593                         vm_page_wakeup(m);
594                         break;
595                 }
596                 if (isblkdev && (m->flags & PG_NOTMETA)) {
597                         vm_page_wakeup(m);
598                         break;
599                 }
600                 vm_page_io_start(m);
601                 vm_page_protect(m, VM_PROT_READ);
602                 if (m->queue - m->pc == PQ_CACHE) {
603                         vm_page_unqueue_nowakeup(m);
604                         vm_page_deactivate(m);
605                 }
606                 marray[i] = m;
607                 vm_page_wakeup(m);
608         }
609         ++i;
610
611         for (j = x + 1; j < SWAP_META_PAGES; ++j) {
612                 m = vm_page_lookup_busy_try(object, basei - x + j,
613                                             TRUE, &error);
614                 if (error || m == NULL)
615                         break;
616                 if (vm_swapcache_test(m)) {
617                         vm_page_wakeup(m);
618                         break;
619                 }
620                 if (isblkdev && (m->flags & PG_NOTMETA)) {
621                         vm_page_wakeup(m);
622                         break;
623                 }
624                 vm_page_io_start(m);
625                 vm_page_protect(m, VM_PROT_READ);
626                 if (m->queue - m->pc == PQ_CACHE) {
627                         vm_page_unqueue_nowakeup(m);
628                         vm_page_deactivate(m);
629                 }
630                 marray[j] = m;
631                 vm_page_wakeup(m);
632         }
633
634         count = j - i;
635         vm_object_pip_add(object, count);
636         swap_pager_putpages(object, marray + i, count, FALSE, rtvals + i);
637         vm_swapcache_write_count += count * PAGE_SIZE;
638         vm_swapcache_curburst -= count * PAGE_SIZE;
639
640         while (i < j) {
641                 if (rtvals[i] != VM_PAGER_PEND) {
642                         vm_page_busy_wait(marray[i], FALSE, "swppgfd");
643                         vm_page_io_finish(marray[i]);
644                         vm_page_wakeup(marray[i]);
645                         vm_object_pip_wakeup(object);
646                 }
647                 ++i;
648         }
649         vm_object_drop(object);
650         return(count);
651 }
652
653 /*
654  * Test whether a VM page is suitable for writing to the swapcache.
655  * Does not test m->queue, PG_MARKER, or PG_SWAPPED.
656  *
657  * Returns 0 on success, 1 on failure
658  */
659 static int
660 vm_swapcache_test(vm_page_t m)
661 {
662         vm_object_t object;
663
664         if (m->flags & PG_UNMANAGED)
665                 return(1);
666         if (m->hold_count || m->wire_count)
667                 return(1);
668         if (m->valid != VM_PAGE_BITS_ALL)
669                 return(1);
670         if (m->dirty & m->valid)
671                 return(1);
672         if ((object = m->object) == NULL)
673                 return(1);
674         if (object->type != OBJT_VNODE ||
675             (object->flags & OBJ_DEAD)) {
676                 return(1);
677         }
678         vm_page_test_dirty(m);
679         if (m->dirty & m->valid)
680                 return(1);
681         return(0);
682 }
683
684 /*
685  * Cleaning pass.
686  *
687  * We clean whole objects up to 16MB
688  */
689 static
690 void
691 vm_swapcache_cleaning(vm_object_t marker, struct vm_object_hash **swindexp)
692 {
693         vm_object_t object;
694         struct vnode *vp;
695         int count;
696         int scount;
697         int n;
698
699         count = vm_swapcache_maxlaunder;
700         scount = vm_swapcache_maxscan;
701
702         /*
703          * Look for vnode objects
704          */
705         lwkt_gettoken(&(*swindexp)->token);
706
707 outerloop:
708         while ((object = TAILQ_NEXT(marker, object_list)) != NULL) {
709                 /*
710                  * We have to skip markers.  We cannot hold/drop marker
711                  * objects!
712                  */
713                 if (object->type == OBJT_MARKER) {
714                         vm_swapcache_movemarker(marker, *swindexp, object);
715                         continue;
716                 }
717
718                 /*
719                  * Safety, or in case there are millions of VM objects
720                  * without swapcache backing.
721                  */
722                 if (--scount <= 0)
723                         goto breakout;
724
725                 /*
726                  * We must hold the object before potentially yielding.
727                  */
728                 vm_object_hold(object);
729                 lwkt_yield();
730
731                 /* 
732                  * Only operate on live VNODE objects that are either
733                  * VREG or VCHR (VCHR for meta-data).
734                  */
735                 if ((object->type != OBJT_VNODE) ||
736                     ((object->flags & OBJ_DEAD) ||
737                      object->swblock_count == 0) ||
738                     ((vp = object->handle) == NULL) ||
739                     (vp->v_type != VREG && vp->v_type != VCHR)) {
740                         vm_object_drop(object);
741                         /* object may be invalid now */
742                         vm_swapcache_movemarker(marker, *swindexp, object);
743                         continue;
744                 }
745
746                 /*
747                  * Reset the object pindex stored in the marker if the
748                  * working object has changed.
749                  */
750                 if (marker->backing_object != object) {
751                         marker->size = 0;
752                         marker->backing_object_offset = 0;
753                         marker->backing_object = object;
754                 }
755
756                 /*
757                  * Look for swblocks starting at our iterator.
758                  *
759                  * The swap_pager_condfree() function attempts to free
760                  * swap space starting at the specified index.  The index
761                  * will be updated on return.  The function will return
762                  * a scan factor (NOT the number of blocks freed).
763                  *
764                  * If it must cut its scan of the object short due to an
765                  * excessive number of swblocks, or is able to free the
766                  * requested number of blocks, it will return n >= count
767                  * and we break and pick it back up on a future attempt.
768                  *
769                  * Scan the object linearly and try to batch large sets of
770                  * blocks that are likely to clean out entire swap radix
771                  * tree leafs.
772                  */
773                 lwkt_token_swap();
774                 lwkt_reltoken(&(*swindexp)->token);
775
776                 n = swap_pager_condfree(object, &marker->size,
777                                     (count + SWAP_META_MASK) & ~SWAP_META_MASK);
778
779                 vm_object_drop(object);         /* object may be invalid now */
780                 lwkt_gettoken(&(*swindexp)->token);
781
782                 /*
783                  * If we have exhausted the object or deleted our per-pass
784                  * page limit then move us to the next object.  Note that
785                  * the current object may no longer be on the vm_object_list.
786                  */
787                 if (n <= 0 ||
788                     marker->backing_object_offset > vm_swapcache_cleanperobj) {
789                         vm_swapcache_movemarker(marker, *swindexp, object);
790                 }
791
792                 /*
793                  * If we have exhausted our max-launder stop for now.
794                  */
795                 count -= n;
796                 marker->backing_object_offset += n * PAGE_SIZE;
797                 if (count < 0)
798                         goto breakout;
799         }
800
801         /*
802          * Iterate vm_object_lists[] hash table
803          */
804         TAILQ_REMOVE(&(*swindexp)->list, marker, object_list);
805         lwkt_reltoken(&(*swindexp)->token);
806         if (++*swindexp >= &vm_object_hash[VMOBJ_HSIZE])
807                 *swindexp = &vm_object_hash[0];
808         lwkt_gettoken(&(*swindexp)->token);
809         TAILQ_INSERT_HEAD(&(*swindexp)->list, marker, object_list);
810
811         if (*swindexp != &vm_object_hash[0])
812                 goto outerloop;
813
814 breakout:
815         lwkt_reltoken(&(*swindexp)->token);
816 }
817
818 /*
819  * Move the marker past the current object.  Object can be stale, but we
820  * still need it to determine if the marker has to be moved.  If the object
821  * is still the 'current object' (object after the marker), we hop-scotch
822  * the marker past it.
823  */
824 static void
825 vm_swapcache_movemarker(vm_object_t marker, struct vm_object_hash *swindex,
826                         vm_object_t object)
827 {
828         if (TAILQ_NEXT(marker, object_list) == object) {
829                 TAILQ_REMOVE(&swindex->list, marker, object_list);
830                 TAILQ_INSERT_AFTER(&swindex->list, object, marker, object_list);
831         }
832 }