Merge branch 'vendor/DIFFUTILS'
[dragonfly.git] / sys / vm / vm_swap.c
1 /*
2  * (MPSAFE)
3  *
4  * Copyright (c) 1982, 1986, 1989, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *      This product includes software developed by the University of
18  *      California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  *      @(#)vm_swap.c   8.5 (Berkeley) 2/17/94
36  * $FreeBSD: src/sys/vm/vm_swap.c,v 1.96.2.2 2001/10/14 18:46:47 iedowse Exp $
37  * $DragonFly: src/sys/vm/vm_swap.c,v 1.36 2007/07/20 17:21:54 dillon Exp $
38  */
39
40 #include "opt_swap.h"
41
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/sysproto.h>
45 #include <sys/buf.h>
46 #include <sys/proc.h>
47 #include <sys/priv.h>
48 #include <sys/nlookup.h>
49 #include <sys/sysctl.h>
50 #include <sys/dmap.h>           /* XXX */
51 #include <sys/vnode.h>
52 #include <sys/fcntl.h>
53 #include <sys/blist.h>
54 #include <sys/kernel.h>
55 #include <sys/lock.h>
56 #include <sys/conf.h>
57 #include <sys/stat.h>
58
59 #include <vm/vm.h>
60 #include <vm/vm_extern.h>
61 #include <vm/swap_pager.h>
62 #include <vm/vm_zone.h>
63 #include <vm/vm_param.h>
64
65 #include <sys/thread2.h>
66 #include <sys/mplock2.h>
67 #include <sys/mutex2.h>
68 #include <sys/spinlock2.h>
69
70 /*
71  * Indirect driver for multi-controller paging.
72  */
73
74 #ifndef NSWAPDEV
75 #define NSWAPDEV        4
76 #endif
77 static struct swdevt should_be_malloced[NSWAPDEV];
78 struct swdevt *swdevt = should_be_malloced;     /* exported to pstat/systat */
79 static swblk_t nswap;           /* first block after the interleaved devs */
80 static struct mtx swap_mtx = MTX_INITIALIZER;
81 int nswdev = NSWAPDEV;                          /* exported to pstat/systat */
82 int vm_swap_size;
83 int vm_swap_max;
84
85 static int swapoff_one(int index);
86 struct vnode *swapdev_vp;
87
88 /*
89  * (struct vnode *a_vp, struct bio *b_bio)
90  *
91  * vn_strategy() for swapdev_vp.  Perform swap strategy interleave device
92  * selection.
93  *
94  * No requirements.
95  */
96 static int
97 swapdev_strategy(struct vop_strategy_args *ap)
98 {
99         struct bio *bio = ap->a_bio;
100         struct bio *nbio;
101         struct buf *bp = bio->bio_buf;
102         int sz, off, seg, index, blkno, nblkno;
103         struct swdevt *sp;
104         struct vnode *vp;
105
106         vp = ap->a_vp;
107         sz = howmany(bp->b_bcount, PAGE_SIZE);
108         blkno = (int)(bio->bio_offset >> PAGE_SHIFT);
109
110         /*
111          * Convert interleaved swap into per-device swap.  Note that
112          * the block size is left in PAGE_SIZE'd chunks (for the newswap)
113          * here.
114          */
115         nbio = push_bio(bio);
116         if (nswdev > 1) {
117                 off = blkno % dmmax;
118                 if (off + sz > dmmax) {
119                         bp->b_error = EINVAL;
120                         bp->b_flags |= B_ERROR;
121                         biodone(bio);
122                         return 0;
123                 }
124                 seg = blkno / dmmax;
125                 index = seg % nswdev;
126                 seg /= nswdev;
127                 nbio->bio_offset = (off_t)(seg * dmmax + off) << PAGE_SHIFT;
128         } else {
129                 index = 0;
130                 nbio->bio_offset = bio->bio_offset;
131         }
132         nblkno = (int)(nbio->bio_offset >> PAGE_SHIFT);
133         sp = &swdevt[index];
134         if (nblkno + sz > sp->sw_nblks) {
135                 bp->b_error = EINVAL;
136                 bp->b_flags |= B_ERROR;
137                 /* I/O was never started on nbio, must biodone(bio) */
138                 biodone(bio);
139                 return 0;
140         }
141         if (sp->sw_vp == NULL) {
142                 bp->b_error = ENODEV;
143                 bp->b_flags |= B_ERROR;
144                 /* I/O was never started on nbio, must biodone(bio) */
145                 biodone(bio);
146                 return 0;
147         }
148
149         /*
150          * Issue a strategy call on the appropriate swap vnode.  Note that
151          * bp->b_vp is not modified.  Strategy code is always supposed to
152          * use the passed vp.
153          *
154          * We have to use vn_strategy() here even if we know we have a
155          * device in order to properly break up requests which exceed the
156          * device's DMA limits.
157          */
158         vn_strategy(sp->sw_vp, nbio);
159         return 0;
160 }
161
162 static int
163 swapdev_inactive(struct vop_inactive_args *ap)
164 {
165         vrecycle(ap->a_vp);
166         return(0);
167 }
168
169 static int
170 swapdev_reclaim(struct vop_reclaim_args *ap)
171 {
172         return(0);
173 }
174
175 /*
176  * Create a special vnode op vector for swapdev_vp - we only use
177  * vn_strategy(), everything else returns an error.
178  */
179 static struct vop_ops swapdev_vnode_vops = {
180         .vop_default =          vop_defaultop,
181         .vop_strategy =         swapdev_strategy,
182         .vop_inactive =         swapdev_inactive,
183         .vop_reclaim =          swapdev_reclaim
184 };
185 static struct vop_ops *swapdev_vnode_vops_p = &swapdev_vnode_vops;
186
187 VNODEOP_SET(swapdev_vnode_vops);
188
189 /*
190  * swapon_args(char *name)
191  *
192  * System call swapon(name) enables swapping on device name,
193  * which must be in the swdevsw.  Return EBUSY
194  * if already swapping on this device.
195  *
196  * No requirements.
197  */
198 int
199 sys_swapon(struct swapon_args *uap)
200 {
201         struct thread *td = curthread;
202         struct vattr attr;
203         struct vnode *vp;
204         struct nlookupdata nd;
205         int error;
206         struct ucred *cred;
207
208         cred = td->td_ucred;
209
210         error = priv_check(td, PRIV_ROOT);
211         if (error)
212                 return (error);
213
214         mtx_lock(&swap_mtx);
215         get_mplock();
216         vp = NULL;
217         error = nlookup_init(&nd, uap->name, UIO_USERSPACE, NLC_FOLLOW);
218         if (error == 0)
219                 error = nlookup(&nd);
220         if (error == 0)
221                 error = cache_vref(&nd.nl_nch, nd.nl_cred, &vp);
222         nlookup_done(&nd);
223         if (error) {
224                 rel_mplock();
225                 mtx_unlock(&swap_mtx);
226                 return (error);
227         }
228
229         if (vn_isdisk(vp, &error)) {
230                 error = swaponvp(td, vp, 0);
231         } else if (vp->v_type == VREG && vp->v_tag == VT_NFS &&
232                    (error = VOP_GETATTR(vp, &attr)) == 0) {
233                 /*
234                  * Allow direct swapping to NFS regular files in the same
235                  * way that nfs_mountroot() sets up diskless swapping.
236                  */
237                 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
238         }
239         if (error)
240                 vrele(vp);
241         rel_mplock();
242         mtx_unlock(&swap_mtx);
243
244         return (error);
245 }
246
247 /*
248  * Swfree(index) frees the index'th portion of the swap map.
249  * Each of the nswdev devices provides 1/nswdev'th of the swap
250  * space, which is laid out with blocks of dmmax pages circularly
251  * among the devices.
252  *
253  * The new swap code uses page-sized blocks.  The old swap code used
254  * DEV_BSIZE'd chunks.
255  *
256  * XXX locking when multiple swapon's run in parallel
257  */
258 int
259 swaponvp(struct thread *td, struct vnode *vp, u_quad_t nblks)
260 {
261         swblk_t aligned_nblks;
262         int64_t dpsize;
263         struct ucred *cred;
264         struct swdevt *sp;
265         swblk_t vsbase;
266         swblk_t dvbase;
267         cdev_t dev;
268         int index;
269         int error;
270         swblk_t blk;
271
272         cred = td->td_ucred;
273
274         mtx_lock(&swap_mtx);
275
276         if (!swapdev_vp) {
277                 error = getspecialvnode(VT_NON, NULL, &swapdev_vnode_vops_p,
278                                     &swapdev_vp, 0, 0);
279                 if (error)
280                         panic("Cannot get vnode for swapdev");
281                 swapdev_vp->v_type = VNON;      /* Untyped */
282                 vx_unlock(swapdev_vp);
283         }
284
285         for (sp = swdevt, index = 0 ; index < nswdev; index++, sp++) {
286                 if (sp->sw_vp == vp) {
287                         mtx_unlock(&swap_mtx);
288                         return EBUSY;
289                 }
290                 if (!sp->sw_vp)
291                         goto found;
292
293         }
294         mtx_unlock(&swap_mtx);
295         return EINVAL;
296     found:
297         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
298         error = VOP_OPEN(vp, FREAD | FWRITE, cred, NULL);
299         vn_unlock(vp);
300         if (error) {
301                 mtx_unlock(&swap_mtx);
302                 return (error);
303         }
304
305         /*
306          * v_rdev is not valid until after the VOP_OPEN() call.  dev_psize()
307          * must be supported if a character device has been specified.
308          */
309         if (vp->v_type == VCHR)
310                 dev = vp->v_rdev;
311         else
312                 dev = NULL;
313
314         if (nblks == 0 && dev != NULL) {
315                 dpsize = dev_dpsize(dev);
316                 if (dpsize == -1) {
317                         VOP_CLOSE(vp, FREAD | FWRITE);
318                         mtx_unlock(&swap_mtx);
319                         return (ENXIO);
320                 }
321                 nblks = (u_quad_t)dpsize;
322         }
323         if (nblks == 0) {
324                 VOP_CLOSE(vp, FREAD | FWRITE);
325                 mtx_unlock(&swap_mtx);
326                 return (ENXIO);
327         }
328
329         /*
330          * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
331          * First chop nblks off to page-align it, then convert.
332          * 
333          * sw->sw_nblks is in page-sized chunks now too.
334          */
335         nblks &= ~(u_quad_t)(ctodb(1) - 1);
336         nblks = dbtoc(nblks);
337
338         /*
339          * Post-conversion nblks must not be >= BLIST_MAXBLKS, and
340          * we impose a 4-swap-device limit so we have to divide it out
341          * further.  Going beyond this will result in overflows in the
342          * blist code.
343          *
344          * Post-conversion nblks must fit within a (swblk_t), which
345          * this test also ensures.
346          */
347         if (nblks > BLIST_MAXBLKS / nswdev) {
348                 kprintf("exceeded maximum of %d blocks per swap unit\n",
349                         (int)BLIST_MAXBLKS / nswdev);
350                 VOP_CLOSE(vp, FREAD | FWRITE);
351                 mtx_unlock(&swap_mtx);
352                 return (ENXIO);
353         }
354
355         sp->sw_vp = vp;
356         sp->sw_dev = dev2udev(dev);
357         sp->sw_device = dev;
358         sp->sw_flags = SW_FREED;
359         sp->sw_nused = 0;
360
361         /*
362          * nblks, nswap, and dmmax are PAGE_SIZE'd parameters now, not
363          * DEV_BSIZE'd.   aligned_nblks is used to calculate the
364          * size of the swap bitmap, taking into account the stripe size.
365          */
366         aligned_nblks = (swblk_t)((nblks + (dmmax - 1)) & ~(u_long)(dmmax - 1));
367         sp->sw_nblks = aligned_nblks;
368
369         if (aligned_nblks * nswdev > nswap)
370                 nswap = aligned_nblks * nswdev;
371
372         if (swapblist == NULL)
373                 swapblist = blist_create(nswap);
374         else
375                 blist_resize(&swapblist, nswap, 0);
376
377         for (dvbase = dmmax; dvbase < aligned_nblks; dvbase += dmmax) {
378                 blk = min(aligned_nblks - dvbase, dmmax);
379                 vsbase = index * dmmax + dvbase * nswdev;
380                 blist_free(swapblist, vsbase, blk);
381                 vm_swap_size += blk;
382                 vm_swap_max += blk;
383         }
384         swap_pager_newswap();
385
386         mtx_unlock(&swap_mtx);
387         return (0);
388 }
389
390 /*
391  * swapoff_args(char *name)
392  *
393  * System call swapoff(name) disables swapping on device name,
394  * which must be an active swap device. Return ENOMEM
395  * if there is not enough memory to page in the contents of
396  * the given device.
397  *
398  * No requirements.
399  */
400 int
401 sys_swapoff(struct swapoff_args *uap)
402 {
403         struct vnode *vp;
404         struct nlookupdata nd;
405         struct swdevt *sp;
406         int error, index;
407
408         error = priv_check(curthread, PRIV_ROOT);
409         if (error)
410                 return (error);
411
412         mtx_lock(&swap_mtx);
413         get_mplock();
414         vp = NULL;
415         error = nlookup_init(&nd, uap->name, UIO_USERSPACE, NLC_FOLLOW);
416         if (error == 0)
417                 error = nlookup(&nd);
418         if (error == 0)
419                 error = cache_vref(&nd.nl_nch, nd.nl_cred, &vp);
420         nlookup_done(&nd);
421         if (error)
422                 goto done;
423
424         for (sp = swdevt, index = 0; index < nswdev; index++, sp++) {
425                 if (sp->sw_vp == vp)
426                         goto found;
427         }
428         error = EINVAL;
429         goto done;
430 found:
431         error = swapoff_one(index);
432
433 done:
434         rel_mplock();
435         mtx_unlock(&swap_mtx);
436         return (error);
437 }
438
439 static int
440 swapoff_one(int index)
441 {
442         swblk_t blk, aligned_nblks;
443         swblk_t dvbase, vsbase;
444         u_int pq_active_clean, pq_inactive_clean;
445         struct swdevt *sp;
446         struct vm_page marker;
447         vm_page_t m;
448         int q;
449
450         mtx_lock(&swap_mtx);
451
452         sp = &swdevt[index];
453         aligned_nblks = sp->sw_nblks;
454         pq_active_clean = pq_inactive_clean = 0;
455
456         /*
457          * We can turn off this swap device safely only if the
458          * available virtual memory in the system will fit the amount
459          * of data we will have to page back in, plus an epsilon so
460          * the system doesn't become critically low on swap space.
461          */
462         for (q = 0; q < PQ_MAXL2_SIZE; ++q) {
463                 bzero(&marker, sizeof(marker));
464                 marker.flags = PG_BUSY | PG_FICTITIOUS | PG_MARKER;
465                 marker.queue = PQ_ACTIVE + q;
466                 marker.pc = q;
467                 marker.wire_count = 1;
468
469                 vm_page_queues_spin_lock(marker.queue);
470                 TAILQ_INSERT_HEAD(&vm_page_queues[marker.queue].pl,
471                                   &marker, pageq);
472
473                 while ((m = TAILQ_NEXT(&marker, pageq)) != NULL) {
474                         TAILQ_REMOVE(&vm_page_queues[marker.queue].pl,
475                                      &marker, pageq);
476                         TAILQ_INSERT_AFTER(&vm_page_queues[marker.queue].pl, m,
477                                            &marker, pageq);
478                         if (m->flags & (PG_MARKER | PG_FICTITIOUS))
479                                 continue;
480
481                         if (vm_page_busy_try(m, FALSE) == 0) {
482                                 vm_page_queues_spin_unlock(marker.queue);
483                                 if (m->dirty == 0) {
484                                         vm_page_test_dirty(m);
485                                         if (m->dirty == 0)
486                                                 ++pq_active_clean;
487                                 }
488                                 vm_page_wakeup(m);
489                                 vm_page_queues_spin_lock(marker.queue);
490                         }
491                 }
492                 TAILQ_REMOVE(&vm_page_queues[marker.queue].pl, &marker, pageq);
493                 vm_page_queues_spin_unlock(marker.queue);
494
495                 marker.queue = PQ_INACTIVE + q;
496                 marker.pc = q;
497                 vm_page_queues_spin_lock(marker.queue);
498                 TAILQ_INSERT_HEAD(&vm_page_queues[marker.queue].pl,
499                                   &marker, pageq);
500
501                 while ((m = TAILQ_NEXT(&marker, pageq)) != NULL) {
502                         TAILQ_REMOVE(
503                                 &vm_page_queues[marker.queue].pl,
504                                 &marker, pageq);
505                         TAILQ_INSERT_AFTER(
506                                 &vm_page_queues[marker.queue].pl,
507                                 m, &marker, pageq);
508                         if (m->flags & (PG_MARKER | PG_FICTITIOUS))
509                                 continue;
510
511                         if (vm_page_busy_try(m, FALSE) == 0) {
512                                 vm_page_queues_spin_unlock(marker.queue);
513                                 if (m->dirty == 0) {
514                                         vm_page_test_dirty(m);
515                                         if (m->dirty == 0)
516                                                 ++pq_inactive_clean;
517                                 }
518                                 vm_page_wakeup(m);
519                                 vm_page_queues_spin_lock(marker.queue);
520                         }
521                 }
522                 TAILQ_REMOVE(&vm_page_queues[marker.queue].pl,
523                              &marker, pageq);
524                 vm_page_queues_spin_unlock(marker.queue);
525         }
526
527         if (vmstats.v_free_count + vmstats.v_cache_count + pq_active_clean +
528             pq_inactive_clean + vm_swap_size < aligned_nblks + nswap_lowat) {
529                 mtx_unlock(&swap_mtx);
530                 return (ENOMEM);
531         }
532
533         /*
534          * Prevent further allocations on this device
535          */
536         sp->sw_flags |= SW_CLOSING;
537         for (dvbase = dmmax; dvbase < aligned_nblks; dvbase += dmmax) {
538                 blk = min(aligned_nblks - dvbase, dmmax);
539                 vsbase = index * dmmax + dvbase * nswdev;
540                 vm_swap_size -= blist_fill(swapblist, vsbase, blk);
541                 vm_swap_max -= blk;
542         }
543
544         /*
545          * Page in the contents of the device and close it.
546          */
547         if (swap_pager_swapoff(index)) {
548                 mtx_unlock(&swap_mtx);
549                 return (EINTR);
550         }
551
552         VOP_CLOSE(sp->sw_vp, FREAD | FWRITE);
553         vrele(sp->sw_vp);
554         bzero(swdevt + index, sizeof(struct swdevt));
555
556         /*
557          * Resize the bitmap based on the nem largest swap device,
558          * or free the bitmap if there are no more devices.
559          */
560         for (sp = swdevt, aligned_nblks = 0; sp < swdevt + nswdev; sp++) {
561                 if (sp->sw_vp)
562                         aligned_nblks = max(aligned_nblks, sp->sw_nblks);
563         }
564
565         nswap = aligned_nblks * nswdev;
566
567         if (nswap == 0) {
568                 blist_destroy(swapblist);
569                 swapblist = NULL;
570                 vrele(swapdev_vp);
571                 swapdev_vp = NULL;
572         } else {
573                 blist_resize(&swapblist, nswap, 0);
574         }
575
576         mtx_unlock(&swap_mtx);
577         return (0);
578 }
579
580 /*
581  * Account for swap space in individual swdevt's.  The caller ensures
582  * that the provided range falls into a single swdevt.
583  *
584  * +count       space freed
585  * -count       space allocated
586  */
587 void
588 swapacctspace(swblk_t base, swblk_t count)
589 {
590         int index;
591         int seg;
592
593         vm_swap_size += count;
594         seg = base / dmmax;
595         index = seg % nswdev;
596         swdevt[index].sw_nused -= count;
597 }
598
599 /*
600  * Retrieve swap info
601  */
602 static int
603 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
604 {
605         struct xswdev xs;
606         struct swdevt *sp;
607         int     error;
608         int     n;
609
610         error = 0;
611         for (n = 0; n < nswdev; ++n) {
612                 sp = &swdevt[n];
613
614                 xs.xsw_size = sizeof(xs);
615                 xs.xsw_version = XSWDEV_VERSION;
616                 xs.xsw_blksize = PAGE_SIZE;
617                 xs.xsw_dev = sp->sw_dev;
618                 xs.xsw_flags = sp->sw_flags;
619                 xs.xsw_nblks = sp->sw_nblks;
620                 xs.xsw_used = sp->sw_nused;
621
622                 error = SYSCTL_OUT(req, &xs, sizeof(xs));
623                 if (error)
624                         break;
625         }
626         return (error);
627 }
628
629 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswdev, 0,
630            "Number of swap devices");
631 SYSCTL_NODE(_vm, OID_AUTO, swap_info_array, CTLFLAG_RD, sysctl_vm_swap_info,
632             "Swap statistics by device");