kernel - unwind kthread_create() mplock
[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
66 #include <vm/vm.h>
67 #include <vm/vm_param.h>
68 #include <sys/lock.h>
69 #include <vm/vm_object.h>
70 #include <vm/vm_page.h>
71 #include <vm/vm_map.h>
72 #include <vm/vm_pageout.h>
73 #include <vm/vm_pager.h>
74 #include <vm/swap_pager.h>
75 #include <vm/vm_extern.h>
76
77 #include <sys/thread2.h>
78 #include <sys/mplock2.h>
79 #include <vm/vm_page2.h>
80
81 #define INACTIVE_LIST   (&vm_page_queues[PQ_INACTIVE].pl)
82
83 /* the kernel process "vm_pageout"*/
84 static int vm_swapcached_flush (vm_page_t m, int isblkdev);
85 static int vm_swapcache_test(vm_page_t m);
86 static void vm_swapcache_writing(vm_page_t marker);
87 static void vm_swapcache_cleaning(vm_object_t marker);
88 struct thread *swapcached_thread;
89
90 SYSCTL_NODE(_vm, OID_AUTO, swapcache, CTLFLAG_RW, NULL, NULL);
91
92 int vm_swapcache_read_enable;
93 int vm_swapcache_inactive_heuristic;
94 static int vm_swapcache_sleep;
95 static int vm_swapcache_maxlaunder = 256;
96 static int vm_swapcache_data_enable = 0;
97 static int vm_swapcache_meta_enable = 0;
98 static int vm_swapcache_maxswappct = 75;
99 static int vm_swapcache_hysteresis;
100 static int vm_swapcache_use_chflags = 1;        /* require chflags cache */
101 static int64_t vm_swapcache_minburst = 10000000LL;      /* 10MB */
102 static int64_t vm_swapcache_curburst = 4000000000LL;    /* 4G after boot */
103 static int64_t vm_swapcache_maxburst = 2000000000LL;    /* 2G nominal max */
104 static int64_t vm_swapcache_accrate = 100000LL;         /* 100K/s */
105 static int64_t vm_swapcache_write_count;
106 static int64_t vm_swapcache_maxfilesize;
107
108 SYSCTL_INT(_vm_swapcache, OID_AUTO, maxlaunder,
109         CTLFLAG_RW, &vm_swapcache_maxlaunder, 0, "");
110
111 SYSCTL_INT(_vm_swapcache, OID_AUTO, data_enable,
112         CTLFLAG_RW, &vm_swapcache_data_enable, 0, "");
113 SYSCTL_INT(_vm_swapcache, OID_AUTO, meta_enable,
114         CTLFLAG_RW, &vm_swapcache_meta_enable, 0, "");
115 SYSCTL_INT(_vm_swapcache, OID_AUTO, read_enable,
116         CTLFLAG_RW, &vm_swapcache_read_enable, 0, "");
117 SYSCTL_INT(_vm_swapcache, OID_AUTO, maxswappct,
118         CTLFLAG_RW, &vm_swapcache_maxswappct, 0, "");
119 SYSCTL_INT(_vm_swapcache, OID_AUTO, hysteresis,
120         CTLFLAG_RW, &vm_swapcache_hysteresis, 0, "");
121 SYSCTL_INT(_vm_swapcache, OID_AUTO, use_chflags,
122         CTLFLAG_RW, &vm_swapcache_use_chflags, 0, "");
123
124 SYSCTL_QUAD(_vm_swapcache, OID_AUTO, minburst,
125         CTLFLAG_RW, &vm_swapcache_minburst, 0, "");
126 SYSCTL_QUAD(_vm_swapcache, OID_AUTO, curburst,
127         CTLFLAG_RW, &vm_swapcache_curburst, 0, "");
128 SYSCTL_QUAD(_vm_swapcache, OID_AUTO, maxburst,
129         CTLFLAG_RW, &vm_swapcache_maxburst, 0, "");
130 SYSCTL_QUAD(_vm_swapcache, OID_AUTO, maxfilesize,
131         CTLFLAG_RW, &vm_swapcache_maxfilesize, 0, "");
132 SYSCTL_QUAD(_vm_swapcache, OID_AUTO, accrate,
133         CTLFLAG_RW, &vm_swapcache_accrate, 0, "");
134 SYSCTL_QUAD(_vm_swapcache, OID_AUTO, write_count,
135         CTLFLAG_RW, &vm_swapcache_write_count, 0, "");
136
137 #define SWAPMAX(adj)    \
138         ((int64_t)vm_swap_max * (vm_swapcache_maxswappct + (adj)) / 100)
139
140 /*
141  * vm_swapcached is the high level pageout daemon.
142  *
143  * No requirements.
144  */
145 static void
146 vm_swapcached_thread(void)
147 {
148         enum { SWAPC_WRITING, SWAPC_CLEANING } state = SWAPC_WRITING;
149         enum { SWAPB_BURSTING, SWAPB_RECOVERING } burst = SWAPB_BURSTING;
150         struct vm_page page_marker;
151         struct vm_object object_marker;
152
153         /*
154          * Thread setup
155          */
156         curthread->td_flags |= TDF_SYSTHREAD;
157
158         get_mplock();
159         crit_enter();
160         lwkt_gettoken(&vm_token);
161
162         /*
163          * Initialize our marker for the inactive scan (SWAPC_WRITING)
164          */
165         bzero(&page_marker, sizeof(page_marker));
166         page_marker.flags = PG_BUSY | PG_FICTITIOUS | PG_MARKER;
167         page_marker.queue = PQ_INACTIVE;
168         page_marker.wire_count = 1;
169         TAILQ_INSERT_HEAD(INACTIVE_LIST, &page_marker, pageq);
170         vm_swapcache_hysteresis = vmstats.v_inactive_target / 2;
171         vm_swapcache_inactive_heuristic = -vm_swapcache_hysteresis;
172
173         /*
174          * Initialize our marker for the vm_object scan (SWAPC_CLEANING)
175          */
176         bzero(&object_marker, sizeof(object_marker));
177         object_marker.type = OBJT_MARKER;
178         lwkt_gettoken(&vmobj_token);
179         TAILQ_INSERT_HEAD(&vm_object_list, &object_marker, object_list);
180         lwkt_reltoken(&vmobj_token);
181
182         for (;;) {
183                 /*
184                  * Check every 5 seconds when not enabled or if no swap
185                  * is present.
186                  */
187                 if ((vm_swapcache_data_enable == 0 &&
188                      vm_swapcache_meta_enable == 0) ||
189                     vm_swap_max == 0) {
190                         tsleep(&vm_swapcache_sleep, 0, "csleep", hz * 5);
191                         continue;
192                 }
193
194                 /*
195                  * Polling rate when enabled is approximately 10 hz.
196                  */
197                 tsleep(&vm_swapcache_sleep, 0, "csleep", hz / 10);
198
199                 /*
200                  * State hysteresis.  Generate write activity up to 75% of
201                  * swap, then clean out swap assignments down to 70%, then
202                  * repeat.
203                  */
204                 if (state == SWAPC_WRITING) {
205                         if (vm_swap_cache_use > SWAPMAX(0))
206                                 state = SWAPC_CLEANING;
207                 } else {
208                         if (vm_swap_cache_use < SWAPMAX(-5))
209                                 state = SWAPC_WRITING;
210                 }
211
212                 /*
213                  * We are allowed to continue accumulating burst value
214                  * in either state.  Allow the user to set curburst > maxburst
215                  * for the initial load-in.
216                  */
217                 if (vm_swapcache_curburst < vm_swapcache_maxburst) {
218                         vm_swapcache_curburst += vm_swapcache_accrate / 10;
219                         if (vm_swapcache_curburst > vm_swapcache_maxburst)
220                                 vm_swapcache_curburst = vm_swapcache_maxburst;
221                 }
222
223                 /*
224                  * We don't want to nickle-and-dime the scan as that will
225                  * create unnecessary fragmentation.  The minimum burst
226                  * is one-seconds worth of accumulation.
227                  */
228                 if (state == SWAPC_WRITING) {
229                         if (vm_swapcache_curburst >= vm_swapcache_accrate) {
230                                 if (burst == SWAPB_BURSTING) {
231                                         vm_swapcache_writing(&page_marker);
232                                         if (vm_swapcache_curburst <= 0)
233                                                 burst = SWAPB_RECOVERING;
234                                 } else if (vm_swapcache_curburst >
235                                            vm_swapcache_minburst) {
236                                         vm_swapcache_writing(&page_marker);
237                                         burst = SWAPB_BURSTING;
238                                 }
239                         }
240                 } else {
241                         vm_swapcache_cleaning(&object_marker);
242                 }
243         }
244         TAILQ_REMOVE(INACTIVE_LIST, &page_marker, pageq);
245         lwkt_gettoken(&vmobj_token);
246         TAILQ_REMOVE(&vm_object_list, &object_marker, object_list);
247         lwkt_reltoken(&vmobj_token);
248         lwkt_reltoken(&vm_token);
249         crit_exit();
250 }
251
252 static struct kproc_desc swpc_kp = {
253         "swapcached",
254         vm_swapcached_thread,
255         &swapcached_thread
256 };
257 SYSINIT(swapcached, SI_SUB_KTHREAD_PAGE, SI_ORDER_SECOND, kproc_start, &swpc_kp)
258
259 /*
260  * The caller must hold vm_token.
261  */
262 static void
263 vm_swapcache_writing(vm_page_t marker)
264 {
265         vm_object_t object;
266         struct vnode *vp;
267         vm_page_t m;
268         int count;
269         int isblkdev;
270
271         /*
272          * Deal with an overflow of the heuristic counter or if the user
273          * manually changes the hysteresis.
274          *
275          * Try to avoid small incremental pageouts by waiting for enough
276          * pages to buildup in the inactive queue to hopefully get a good
277          * burst in.  This heuristic is bumped by the VM system and reset
278          * when our scan hits the end of the queue.
279          */
280         if (vm_swapcache_inactive_heuristic < -vm_swapcache_hysteresis)
281                 vm_swapcache_inactive_heuristic = -vm_swapcache_hysteresis;
282         if (vm_swapcache_inactive_heuristic < 0)
283                 return;
284
285         /*
286          * Scan the inactive queue from our marker to locate
287          * suitable pages to push to the swap cache.
288          *
289          * We are looking for clean vnode-backed pages.
290          *
291          * NOTE: PG_SWAPPED pages in particular are not part of
292          *       our count because once the cache stabilizes we
293          *       can end up with a very high datarate of VM pages
294          *       cycling from it.
295          */
296         m = marker;
297         count = vm_swapcache_maxlaunder;
298
299         while ((m = TAILQ_NEXT(m, pageq)) != NULL && count--) {
300                 if (m->flags & (PG_MARKER | PG_SWAPPED)) {
301                         ++count;
302                         continue;
303                 }
304                 if (vm_swapcache_curburst < 0)
305                         break;
306                 if (vm_swapcache_test(m))
307                         continue;
308                 object = m->object;
309                 vp = object->handle;
310                 if (vp == NULL)
311                         continue;
312
313                 switch(vp->v_type) {
314                 case VREG:
315                         /*
316                          * If data_enable is 0 do not try to swapcache data.
317                          * If use_chflags is set then only swapcache data for
318                          * VSWAPCACHE marked vnodes, otherwise any vnode.
319                          */
320                         if (vm_swapcache_data_enable == 0 ||
321                             ((vp->v_flag & VSWAPCACHE) == 0 &&
322                              vm_swapcache_use_chflags)) {
323                                 continue;
324                         }
325                         if (vm_swapcache_maxfilesize &&
326                             object->size >
327                             (vm_swapcache_maxfilesize >> PAGE_SHIFT)) {
328                                 continue;
329                         }
330                         isblkdev = 0;
331                         break;
332                 case VCHR:
333                         /*
334                          * The PG_NOTMETA flag only applies to pages
335                          * associated with block devices.
336                          */
337                         if (m->flags & PG_NOTMETA)
338                                 continue;
339                         if (vm_swapcache_meta_enable == 0)
340                                 continue;
341                         isblkdev = 1;
342                         break;
343                 default:
344                         continue;
345                 }
346
347                 /*
348                  * Ok, move the marker and soft-busy the page.
349                  */
350                 TAILQ_REMOVE(INACTIVE_LIST, marker, pageq);
351                 TAILQ_INSERT_AFTER(INACTIVE_LIST, m, marker, pageq);
352
353                 /*
354                  * Assign swap and initiate I/O.
355                  *
356                  * (adjust for the --count which also occurs in the loop)
357                  */
358                 count -= vm_swapcached_flush(m, isblkdev) - 1;
359
360                 /*
361                  * Setup for next loop using marker.
362                  */
363                 m = marker;
364         }
365
366         /*
367          * Cleanup marker position.  If we hit the end of the
368          * list the marker is placed at the tail.  Newly deactivated
369          * pages will be placed after it.
370          *
371          * Earlier inactive pages that were dirty and become clean
372          * are typically moved to the end of PQ_INACTIVE by virtue
373          * of vfs_vmio_release() when they become unwired from the
374          * buffer cache.
375          */
376         TAILQ_REMOVE(INACTIVE_LIST, marker, pageq);
377         if (m) {
378                 TAILQ_INSERT_BEFORE(m, marker, pageq);
379         } else {
380                 TAILQ_INSERT_TAIL(INACTIVE_LIST, marker, pageq);
381                 vm_swapcache_inactive_heuristic = -vm_swapcache_hysteresis;
382         }
383 }
384
385 /*
386  * Flush the specified page using the swap_pager.
387  *
388  * Try to collect surrounding pages, including pages which may
389  * have already been assigned swap.  Try to cluster within a
390  * contiguous aligned SMAP_META_PAGES (typ 16 x PAGE_SIZE) block
391  * to match what swap_pager_putpages() can do.
392  *
393  * We also want to try to match against the buffer cache blocksize
394  * but we don't really know what it is here.  Since the buffer cache
395  * wires and unwires pages in groups the fact that we skip wired pages
396  * should be sufficient.
397  *
398  * Returns a count of pages we might have flushed (minimum 1)
399  *
400  * The caller must hold vm_token.
401  */
402 static
403 int
404 vm_swapcached_flush(vm_page_t m, int isblkdev)
405 {
406         vm_object_t object;
407         vm_page_t marray[SWAP_META_PAGES];
408         vm_pindex_t basei;
409         int rtvals[SWAP_META_PAGES];
410         int x;
411         int i;
412         int j;
413         int count;
414
415         vm_page_io_start(m);
416         vm_page_protect(m, VM_PROT_READ);
417         object = m->object;
418
419         /*
420          * Try to cluster around (m), keeping in mind that the swap pager
421          * can only do SMAP_META_PAGES worth of continguous write.
422          */
423         x = (int)m->pindex & SWAP_META_MASK;
424         marray[x] = m;
425         basei = m->pindex;
426
427         for (i = x - 1; i >= 0; --i) {
428                 m = vm_page_lookup(object, basei - x + i);
429                 if (m == NULL)
430                         break;
431                 if (vm_swapcache_test(m))
432                         break;
433                 if (isblkdev && (m->flags & PG_NOTMETA))
434                         break;
435                 vm_page_io_start(m);
436                 vm_page_protect(m, VM_PROT_READ);
437                 if (m->queue - m->pc == PQ_CACHE) {
438                         vm_page_unqueue_nowakeup(m);
439                         vm_page_deactivate(m);
440                 }
441                 marray[i] = m;
442         }
443         ++i;
444
445         for (j = x + 1; j < SWAP_META_PAGES; ++j) {
446                 m = vm_page_lookup(object, basei - x + j);
447                 if (m == NULL)
448                         break;
449                 if (vm_swapcache_test(m))
450                         break;
451                 if (isblkdev && (m->flags & PG_NOTMETA))
452                         break;
453                 vm_page_io_start(m);
454                 vm_page_protect(m, VM_PROT_READ);
455                 if (m->queue - m->pc == PQ_CACHE) {
456                         vm_page_unqueue_nowakeup(m);
457                         vm_page_deactivate(m);
458                 }
459                 marray[j] = m;
460         }
461
462         count = j - i;
463         vm_object_pip_add(object, count);
464         swap_pager_putpages(object, marray + i, count, FALSE, rtvals + i);
465         vm_swapcache_write_count += count * PAGE_SIZE;
466         vm_swapcache_curburst -= count * PAGE_SIZE;
467
468         while (i < j) {
469                 if (rtvals[i] != VM_PAGER_PEND) {
470                         vm_page_io_finish(marray[i]);
471                         vm_object_pip_wakeup(object);
472                 }
473                 ++i;
474         }
475         return(count);
476 }
477
478 /*
479  * Test whether a VM page is suitable for writing to the swapcache.
480  * Does not test m->queue, PG_MARKER, or PG_SWAPPED.
481  *
482  * Returns 0 on success, 1 on failure
483  *
484  * The caller must hold vm_token.
485  */
486 static int
487 vm_swapcache_test(vm_page_t m)
488 {
489         vm_object_t object;
490
491         if (m->flags & (PG_BUSY | PG_UNMANAGED))
492                 return(1);
493         if (m->busy || m->hold_count || m->wire_count)
494                 return(1);
495         if (m->valid != VM_PAGE_BITS_ALL)
496                 return(1);
497         if (m->dirty & m->valid)
498                 return(1);
499         if ((object = m->object) == NULL)
500                 return(1);
501         if (object->type != OBJT_VNODE ||
502             (object->flags & OBJ_DEAD)) {
503                 return(1);
504         }
505         vm_page_test_dirty(m);
506         if (m->dirty & m->valid)
507                 return(1);
508         return(0);
509 }
510
511 /*
512  * Cleaning pass
513  *
514  * The caller must hold vm_token.
515  */
516 static
517 void
518 vm_swapcache_cleaning(vm_object_t marker)
519 {
520         vm_object_t object;
521         struct vnode *vp;
522         int count;
523         int n;
524
525         object = marker;
526         count = vm_swapcache_maxlaunder;
527
528         /*
529          * Look for vnode objects
530          */
531         lwkt_gettoken(&vm_token);
532         lwkt_gettoken(&vmobj_token);
533
534         while ((object = TAILQ_NEXT(object, object_list)) != NULL && count--) {
535                 if (object->type != OBJT_VNODE)
536                         continue;
537                 if ((object->flags & OBJ_DEAD) || object->swblock_count == 0)
538                         continue;
539                 if ((vp = object->handle) == NULL)
540                         continue;
541                 if (vp->v_type != VREG && vp->v_type != VCHR)
542                         continue;
543
544                 /*
545                  * Adjust iterator.
546                  */
547                 if (marker->backing_object != object)
548                         marker->size = 0;
549
550                 /*
551                  * Move the marker so we can work on the VM object
552                  */
553                 TAILQ_REMOVE(&vm_object_list, marker, object_list);
554                 TAILQ_INSERT_AFTER(&vm_object_list, object,
555                                    marker, object_list);
556
557                 /*
558                  * Look for swblocks starting at our iterator.
559                  *
560                  * The swap_pager_condfree() function attempts to free
561                  * swap space starting at the specified index.  The index
562                  * will be updated on return.  The function will return
563                  * a scan factor (NOT the number of blocks freed).
564                  *
565                  * If it must cut its scan of the object short due to an
566                  * excessive number of swblocks, or is able to free the
567                  * requested number of blocks, it will return n >= count
568                  * and we break and pick it back up on a future attempt.
569                  */
570                 n = swap_pager_condfree(object, &marker->size, count);
571                 count -= n;
572                 if (count < 0)
573                         break;
574
575                 /*
576                  * Setup for loop.
577                  */
578                 marker->size = 0;
579                 object = marker;
580         }
581
582         /*
583          * Adjust marker so we continue the scan from where we left off.
584          * When we reach the end we start back at the beginning.
585          */
586         TAILQ_REMOVE(&vm_object_list, marker, object_list);
587         if (object)
588                 TAILQ_INSERT_BEFORE(object, marker, object_list);
589         else
590                 TAILQ_INSERT_HEAD(&vm_object_list, marker, object_list);
591         marker->backing_object = object;
592
593         lwkt_reltoken(&vmobj_token);
594         lwkt_reltoken(&vm_token);
595 }