2 * Copyright 1998, 2000 Marshall Kirk McKusick. All Rights Reserved.
4 * The soft updates code is derived from the appendix of a University
5 * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
6 * "Soft Updates: A Solution to the Metadata Update Problem in File
7 * Systems", CSE-TR-254-95, August 1995).
9 * Further information about soft updates can be obtained from:
11 * Marshall Kirk McKusick http://www.mckusick.com/softdep/
12 * 1614 Oxford Street mckusick@mckusick.com
13 * Berkeley, CA 94709-1608 +1-510-843-9542
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
26 * THIS SOFTWARE IS PROVIDED BY MARSHALL KIRK MCKUSICK ``AS IS'' AND ANY
27 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
28 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
29 * DISCLAIMED. IN NO EVENT SHALL MARSHALL KIRK MCKUSICK BE LIABLE FOR
30 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * from: @(#)ffs_softdep.c 9.59 (McKusick) 6/21/00
39 * $FreeBSD: src/sys/ufs/ffs/ffs_softdep.c,v 1.57.2.11 2002/02/05 18:46:53 dillon Exp $
43 * For now we want the safety net that the DIAGNOSTIC and DEBUG flags provide.
52 #include <sys/param.h>
53 #include <sys/kernel.h>
54 #include <sys/systm.h>
56 #include <sys/malloc.h>
57 #include <sys/mount.h>
59 #include <sys/syslog.h>
60 #include <sys/vnode.h>
62 #include <machine/inttypes.h>
69 #include "ffs_extern.h"
70 #include "ufs_extern.h"
73 #include <sys/thread2.h>
77 * These definitions need to be adapted to the system to which
78 * this file is being ported.
81 * malloc types defined for the softdep system.
83 MALLOC_DEFINE(M_PAGEDEP, "pagedep","File page dependencies");
84 MALLOC_DEFINE(M_INODEDEP, "inodedep","Inode dependencies");
85 MALLOC_DEFINE(M_NEWBLK, "newblk","New block allocation");
86 MALLOC_DEFINE(M_BMSAFEMAP, "bmsafemap","Block or frag allocated from cyl group map");
87 MALLOC_DEFINE(M_ALLOCDIRECT, "allocdirect","Block or frag dependency for an inode");
88 MALLOC_DEFINE(M_INDIRDEP, "indirdep","Indirect block dependencies");
89 MALLOC_DEFINE(M_ALLOCINDIR, "allocindir","Block dependency for an indirect block");
90 MALLOC_DEFINE(M_FREEFRAG, "freefrag","Previously used frag for an inode");
91 MALLOC_DEFINE(M_FREEBLKS, "freeblks","Blocks freed from an inode");
92 MALLOC_DEFINE(M_FREEFILE, "freefile","Inode deallocated");
93 MALLOC_DEFINE(M_DIRADD, "diradd","New directory entry");
94 MALLOC_DEFINE(M_MKDIR, "mkdir","New directory");
95 MALLOC_DEFINE(M_DIRREM, "dirrem","Directory entry deleted");
97 #define M_SOFTDEP_FLAGS (M_WAITOK | M_USE_RESERVE)
102 #define D_BMSAFEMAP 3
103 #define D_ALLOCDIRECT 4
105 #define D_ALLOCINDIR 6
112 #define D_LAST D_DIRREM
115 * translate from workitem type to memory type
116 * MUST match the defines above, such that memtype[D_XXX] == M_XXX
118 static struct malloc_type *memtype[] = {
134 #define DtoM(type) (memtype[type])
137 * Names of malloc types.
139 #define TYPENAME(type) \
140 ((unsigned)(type) < D_LAST ? memtype[type]->ks_shortdesc : "???")
142 * End system adaptaion definitions.
146 * Internal function prototypes.
148 static void softdep_error(char *, int);
149 static void drain_output(struct vnode *, int);
150 static int getdirtybuf(struct buf **, int);
151 static void clear_remove(struct thread *);
152 static void clear_inodedeps(struct thread *);
153 static int flush_pagedep_deps(struct vnode *, struct mount *,
155 static int flush_inodedep_deps(struct fs *, ino_t);
156 static int handle_written_filepage(struct pagedep *, struct buf *);
157 static void diradd_inode_written(struct diradd *, struct inodedep *);
158 static int handle_written_inodeblock(struct inodedep *, struct buf *);
159 static void handle_allocdirect_partdone(struct allocdirect *);
160 static void handle_allocindir_partdone(struct allocindir *);
161 static void initiate_write_filepage(struct pagedep *, struct buf *);
162 static void handle_written_mkdir(struct mkdir *, int);
163 static void initiate_write_inodeblock(struct inodedep *, struct buf *);
164 static void handle_workitem_freefile(struct freefile *);
165 static void handle_workitem_remove(struct dirrem *);
166 static struct dirrem *newdirrem(struct buf *, struct inode *,
167 struct inode *, int, struct dirrem **);
168 static void free_diradd(struct diradd *);
169 static void free_allocindir(struct allocindir *, struct inodedep *);
170 static int indir_trunc (struct inode *, off_t, int, ufs_lbn_t, long *);
171 static void deallocate_dependencies(struct buf *, struct inodedep *);
172 static void free_allocdirect(struct allocdirectlst *,
173 struct allocdirect *, int);
174 static int check_inode_unwritten(struct inodedep *);
175 static int free_inodedep(struct inodedep *);
176 static void handle_workitem_freeblocks(struct freeblks *);
177 static void merge_inode_lists(struct inodedep *);
178 static void setup_allocindir_phase2(struct buf *, struct inode *,
179 struct allocindir *);
180 static struct allocindir *newallocindir(struct inode *, int, ufs_daddr_t,
182 static void handle_workitem_freefrag(struct freefrag *);
183 static struct freefrag *newfreefrag(struct inode *, ufs_daddr_t, long);
184 static void allocdirect_merge(struct allocdirectlst *,
185 struct allocdirect *, struct allocdirect *);
186 static struct bmsafemap *bmsafemap_lookup(struct buf *);
187 static int newblk_lookup(struct fs *, ufs_daddr_t, int,
189 static int inodedep_lookup(struct fs *, ino_t, int, struct inodedep **);
190 static int pagedep_lookup(struct inode *, ufs_lbn_t, int,
192 static int request_cleanup(int);
193 static int process_worklist_item(struct mount *, int);
194 static void add_to_worklist(struct worklist *);
197 * Exported softdep operations.
199 static void softdep_disk_io_initiation(struct buf *);
200 static void softdep_disk_write_complete(struct buf *);
201 static void softdep_deallocate_dependencies(struct buf *);
202 static int softdep_fsync(struct vnode *);
203 static int softdep_process_worklist(struct mount *);
204 static void softdep_move_dependencies(struct buf *, struct buf *);
205 static int softdep_count_dependencies(struct buf *bp, int);
206 static int softdep_checkread(struct buf *bp);
207 static int softdep_checkwrite(struct buf *bp);
209 static struct bio_ops softdep_bioops = {
210 .io_start = softdep_disk_io_initiation,
211 .io_complete = softdep_disk_write_complete,
212 .io_deallocate = softdep_deallocate_dependencies,
213 .io_fsync = softdep_fsync,
214 .io_sync = softdep_process_worklist,
215 .io_movedeps = softdep_move_dependencies,
216 .io_countdeps = softdep_count_dependencies,
217 .io_checkread = softdep_checkread,
218 .io_checkwrite = softdep_checkwrite
222 * Locking primitives.
224 static void acquire_lock(struct lock *);
225 static void free_lock(struct lock *);
227 static int lock_held(struct lock *);
230 static struct lock lk;
232 #define ACQUIRE_LOCK(lkp) acquire_lock(lkp)
233 #define FREE_LOCK(lkp) free_lock(lkp)
236 acquire_lock(struct lock *lkp)
238 lockmgr(lkp, LK_EXCLUSIVE);
242 free_lock(struct lock *lkp)
244 lockmgr(lkp, LK_RELEASE);
249 lock_held(struct lock *lkp)
251 return lockcountnb(lkp);
256 * Place holder for real semaphores.
263 struct spinlock spin;
265 static void sema_init(struct sema *, char *, int);
266 static int sema_get(struct sema *, struct lock *);
267 static void sema_release(struct sema *, struct lock *);
269 #define NOHOLDER ((struct thread *) -1)
272 sema_init(struct sema *semap, char *name, int timo)
274 semap->holder = NOHOLDER;
278 spin_init(&semap->spin, "ufssema");
282 * Obtain exclusive access, semaphore is protected by the interlock.
283 * If interlock is NULL we must protect the semaphore ourselves.
286 sema_get(struct sema *semap, struct lock *interlock)
291 if (semap->value > 0) {
292 ++semap->value; /* serves as wakeup flag */
293 lksleep(semap, interlock, 0,
294 semap->name, semap->timo);
297 semap->value = 1; /* serves as owned flag */
298 semap->holder = curthread;
302 spin_lock(&semap->spin);
303 if (semap->value > 0) {
304 ++semap->value; /* serves as wakeup flag */
305 ssleep(semap, &semap->spin, 0,
306 semap->name, semap->timo);
307 spin_unlock(&semap->spin);
310 semap->value = 1; /* serves as owned flag */
311 semap->holder = curthread;
312 spin_unlock(&semap->spin);
320 sema_release(struct sema *semap, struct lock *lk)
322 if (semap->value <= 0 || semap->holder != curthread)
323 panic("sema_release: not held");
325 semap->holder = NOHOLDER;
326 if (--semap->value > 0) {
331 spin_lock(&semap->spin);
332 semap->holder = NOHOLDER;
333 if (--semap->value > 0) {
335 spin_unlock(&semap->spin);
338 spin_unlock(&semap->spin);
344 * Worklist queue management.
345 * These routines require that the lock be held.
347 static void worklist_insert(struct workhead *, struct worklist *);
348 static void worklist_remove(struct worklist *);
349 static void workitem_free(struct worklist *, int);
351 #define WORKLIST_INSERT_BP(bp, item) do { \
352 (bp)->b_ops = &softdep_bioops; \
353 worklist_insert(&(bp)->b_dep, item); \
356 #define WORKLIST_INSERT(head, item) worklist_insert(head, item)
357 #define WORKLIST_REMOVE(item) worklist_remove(item)
358 #define WORKITEM_FREE(item, type) workitem_free((struct worklist *)item, type)
361 worklist_insert(struct workhead *head, struct worklist *item)
363 KKASSERT(lock_held(&lk) > 0);
365 if (item->wk_state & ONWORKLIST) {
366 panic("worklist_insert: already on list");
368 item->wk_state |= ONWORKLIST;
369 LIST_INSERT_HEAD(head, item, wk_list);
373 worklist_remove(struct worklist *item)
376 KKASSERT(lock_held(&lk));
377 if ((item->wk_state & ONWORKLIST) == 0)
378 panic("worklist_remove: not on list");
380 item->wk_state &= ~ONWORKLIST;
381 LIST_REMOVE(item, wk_list);
385 workitem_free(struct worklist *item, int type)
388 if (item->wk_state & ONWORKLIST)
389 panic("workitem_free: still on list");
390 if (item->wk_type != type)
391 panic("workitem_free: type mismatch");
393 kfree(item, DtoM(type));
397 * Workitem queue management
399 static struct workhead softdep_workitem_pending;
400 static int num_on_worklist; /* number of worklist items to be processed */
401 static int softdep_worklist_busy; /* 1 => trying to do unmount */
402 static int softdep_worklist_req; /* serialized waiters */
403 static int max_softdeps; /* maximum number of structs before slowdown */
404 static int tickdelay = 2; /* number of ticks to pause during slowdown */
405 static int *stat_countp; /* statistic to count in proc_waiting timeout */
406 static int proc_waiting; /* tracks whether we have a timeout posted */
407 static struct thread *filesys_syncer; /* proc of filesystem syncer process */
408 static int req_clear_inodedeps; /* syncer process flush some inodedeps */
409 #define FLUSH_INODES 1
410 static int req_clear_remove; /* syncer process flush some freeblks */
411 #define FLUSH_REMOVE 2
415 static int stat_worklist_push; /* number of worklist cleanups */
416 static int stat_blk_limit_push; /* number of times block limit neared */
417 static int stat_ino_limit_push; /* number of times inode limit neared */
418 static int stat_blk_limit_hit; /* number of times block slowdown imposed */
419 static int stat_ino_limit_hit; /* number of times inode slowdown imposed */
420 static int stat_sync_limit_hit; /* number of synchronous slowdowns imposed */
421 static int stat_indir_blk_ptrs; /* bufs redirtied as indir ptrs not written */
422 static int stat_inode_bitmap; /* bufs redirtied as inode bitmap not written */
423 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
424 static int stat_dir_entry; /* bufs redirtied as dir entry cannot write */
427 #include <sys/sysctl.h>
428 SYSCTL_INT(_debug, OID_AUTO, max_softdeps, CTLFLAG_RW, &max_softdeps, 0,
429 "Maximum soft dependencies before slowdown occurs");
430 SYSCTL_INT(_debug, OID_AUTO, tickdelay, CTLFLAG_RW, &tickdelay, 0,
431 "Ticks to delay before allocating during slowdown");
432 SYSCTL_INT(_debug, OID_AUTO, worklist_push, CTLFLAG_RW, &stat_worklist_push, 0,
433 "Number of worklist cleanups");
434 SYSCTL_INT(_debug, OID_AUTO, blk_limit_push, CTLFLAG_RW, &stat_blk_limit_push, 0,
435 "Number of times block limit neared");
436 SYSCTL_INT(_debug, OID_AUTO, ino_limit_push, CTLFLAG_RW, &stat_ino_limit_push, 0,
437 "Number of times inode limit neared");
438 SYSCTL_INT(_debug, OID_AUTO, blk_limit_hit, CTLFLAG_RW, &stat_blk_limit_hit, 0,
439 "Number of times block slowdown imposed");
440 SYSCTL_INT(_debug, OID_AUTO, ino_limit_hit, CTLFLAG_RW, &stat_ino_limit_hit, 0,
441 "Number of times inode slowdown imposed ");
442 SYSCTL_INT(_debug, OID_AUTO, sync_limit_hit, CTLFLAG_RW, &stat_sync_limit_hit, 0,
443 "Number of synchronous slowdowns imposed");
444 SYSCTL_INT(_debug, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW, &stat_indir_blk_ptrs, 0,
445 "Bufs redirtied as indir ptrs not written");
446 SYSCTL_INT(_debug, OID_AUTO, inode_bitmap, CTLFLAG_RW, &stat_inode_bitmap, 0,
447 "Bufs redirtied as inode bitmap not written");
448 SYSCTL_INT(_debug, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW, &stat_direct_blk_ptrs, 0,
449 "Bufs redirtied as direct ptrs not written");
450 SYSCTL_INT(_debug, OID_AUTO, dir_entry, CTLFLAG_RW, &stat_dir_entry, 0,
451 "Bufs redirtied as dir entry cannot write");
455 * Add an item to the end of the work queue.
456 * This routine requires that the lock be held.
457 * This is the only routine that adds items to the list.
458 * The following routine is the only one that removes items
459 * and does so in order from first to last.
462 add_to_worklist(struct worklist *wk)
464 static struct worklist *worklist_tail;
466 if (wk->wk_state & ONWORKLIST) {
467 panic("add_to_worklist: already on list");
469 wk->wk_state |= ONWORKLIST;
470 if (LIST_FIRST(&softdep_workitem_pending) == NULL)
471 LIST_INSERT_HEAD(&softdep_workitem_pending, wk, wk_list);
473 LIST_INSERT_AFTER(worklist_tail, wk, wk_list);
475 num_on_worklist += 1;
479 * Process that runs once per second to handle items in the background queue.
481 * Note that we ensure that everything is done in the order in which they
482 * appear in the queue. The code below depends on this property to ensure
483 * that blocks of a file are freed before the inode itself is freed. This
484 * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
485 * until all the old ones have been purged from the dependency lists.
487 * bioops callback - hold io_token
490 softdep_process_worklist(struct mount *matchmnt)
492 thread_t td = curthread;
493 int matchcnt, loopcount;
499 * Record the process identifier of our caller so that we can give
500 * this process preferential treatment in request_cleanup below.
506 * There is no danger of having multiple processes run this
507 * code, but we have to single-thread it when softdep_flushfiles()
508 * is in operation to get an accurate count of the number of items
509 * related to its mount point that are in the list.
511 if (matchmnt == NULL) {
512 if (softdep_worklist_busy < 0) {
516 softdep_worklist_busy += 1;
520 * If requested, try removing inode or removal dependencies.
522 if (req_clear_inodedeps) {
524 req_clear_inodedeps -= 1;
525 wakeup_one(&proc_waiting);
527 if (req_clear_remove) {
529 req_clear_remove -= 1;
530 wakeup_one(&proc_waiting);
534 while (num_on_worklist > 0) {
535 matchcnt += process_worklist_item(matchmnt, 0);
538 * If a umount operation wants to run the worklist
541 if (softdep_worklist_req && matchmnt == NULL) {
547 * If requested, try removing inode or removal dependencies.
549 if (req_clear_inodedeps) {
551 req_clear_inodedeps -= 1;
552 wakeup_one(&proc_waiting);
554 if (req_clear_remove) {
556 req_clear_remove -= 1;
557 wakeup_one(&proc_waiting);
560 * We do not generally want to stop for buffer space, but if
561 * we are really being a buffer hog, we will stop and wait.
563 if (loopcount++ % 128 == 0) {
570 * Never allow processing to run for more than one
571 * second. Otherwise the other syncer tasks may get
572 * excessively backlogged.
574 * Use ticks to avoid boundary condition w/time_second or
577 if ((ticks - starttime) > hz && matchmnt == NULL) {
582 if (matchmnt == NULL) {
583 --softdep_worklist_busy;
584 if (softdep_worklist_req && softdep_worklist_busy == 0)
585 wakeup(&softdep_worklist_req);
593 * Process one item on the worklist.
596 process_worklist_item(struct mount *matchmnt, int flags)
598 struct ufsmount *ump;
600 struct dirrem *dirrem;
605 KKASSERT(lock_held(&lk) > 0);
608 if (matchmnt != NULL)
609 matchfs = VFSTOUFS(matchmnt)->um_fs;
612 * Normally we just process each item on the worklist in order.
613 * However, if we are in a situation where we cannot lock any
614 * inodes, we have to skip over any dirrem requests whose
615 * vnodes are resident and locked.
617 LIST_FOREACH(wk, &softdep_workitem_pending, wk_list) {
618 if ((flags & LK_NOWAIT) == 0 || wk->wk_type != D_DIRREM)
620 dirrem = WK_DIRREM(wk);
621 ump = VFSTOUFS(dirrem->dm_mnt);
622 lwkt_gettoken(&ump->um_mountp->mnt_token);
623 vp = ufs_ihashlookup(ump, ump->um_dev, dirrem->dm_oldinum);
624 lwkt_reltoken(&ump->um_mountp->mnt_token);
625 if (vp == NULL || !vn_islocked(vp))
632 num_on_worklist -= 1;
634 switch (wk->wk_type) {
636 /* removal of a directory entry */
637 if (WK_DIRREM(wk)->dm_mnt == matchmnt)
639 handle_workitem_remove(WK_DIRREM(wk));
643 /* releasing blocks and/or fragments from a file */
644 if (WK_FREEBLKS(wk)->fb_fs == matchfs)
646 handle_workitem_freeblocks(WK_FREEBLKS(wk));
650 /* releasing a fragment when replaced as a file grows */
651 if (WK_FREEFRAG(wk)->ff_fs == matchfs)
653 handle_workitem_freefrag(WK_FREEFRAG(wk));
657 /* releasing an inode when its link count drops to 0 */
658 if (WK_FREEFILE(wk)->fx_fs == matchfs)
660 handle_workitem_freefile(WK_FREEFILE(wk));
664 panic("%s_process_worklist: Unknown type %s",
665 "softdep", TYPENAME(wk->wk_type));
673 * Move dependencies from one buffer to another.
675 * bioops callback - hold io_token
678 softdep_move_dependencies(struct buf *oldbp, struct buf *newbp)
680 struct worklist *wk, *wktail;
682 if (LIST_FIRST(&newbp->b_dep) != NULL)
683 panic("softdep_move_dependencies: need merge code");
686 while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
687 LIST_REMOVE(wk, wk_list);
689 LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
691 LIST_INSERT_AFTER(wktail, wk, wk_list);
693 newbp->b_ops = &softdep_bioops;
699 * Purge the work list of all items associated with a particular mount point.
702 softdep_flushfiles(struct mount *oldmnt, int flags)
708 * Await our turn to clear out the queue, then serialize access.
711 while (softdep_worklist_busy != 0) {
712 softdep_worklist_req += 1;
713 lksleep(&softdep_worklist_req, &lk, 0, "softflush", 0);
714 softdep_worklist_req -= 1;
716 softdep_worklist_busy = -1;
719 if ((error = ffs_flushfiles(oldmnt, flags)) != 0) {
720 softdep_worklist_busy = 0;
721 if (softdep_worklist_req)
722 wakeup(&softdep_worklist_req);
726 * Alternately flush the block device associated with the mount
727 * point and process any dependencies that the flushing
728 * creates. In theory, this loop can happen at most twice,
729 * but we give it a few extra just to be sure.
731 devvp = VFSTOUFS(oldmnt)->um_devvp;
732 for (loopcnt = 10; loopcnt > 0; ) {
733 if (softdep_process_worklist(oldmnt) == 0) {
736 * Do another flush in case any vnodes were brought in
737 * as part of the cleanup operations.
739 if ((error = ffs_flushfiles(oldmnt, flags)) != 0)
742 * If we still found nothing to do, we are really done.
744 if (softdep_process_worklist(oldmnt) == 0)
747 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
748 error = VOP_FSYNC(devvp, MNT_WAIT, 0);
754 softdep_worklist_busy = 0;
755 if (softdep_worklist_req)
756 wakeup(&softdep_worklist_req);
760 * If we are unmounting then it is an error to fail. If we
761 * are simply trying to downgrade to read-only, then filesystem
762 * activity can keep us busy forever, so we just fail with EBUSY.
765 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
766 panic("softdep_flushfiles: looping");
775 * There are three types of structures that can be looked up:
776 * 1) pagedep structures identified by mount point, inode number,
778 * 2) inodedep structures identified by mount point and inode number.
779 * 3) newblk structures identified by mount point and
780 * physical block number.
782 * The "pagedep" and "inodedep" dependency structures are hashed
783 * separately from the file blocks and inodes to which they correspond.
784 * This separation helps when the in-memory copy of an inode or
785 * file block must be replaced. It also obviates the need to access
786 * an inode or file page when simply updating (or de-allocating)
787 * dependency structures. Lookup of newblk structures is needed to
788 * find newly allocated blocks when trying to associate them with
789 * their allocdirect or allocindir structure.
791 * The lookup routines optionally create and hash a new instance when
792 * an existing entry is not found.
794 #define DEPALLOC 0x0001 /* allocate structure if lookup fails */
795 #define NODELAY 0x0002 /* cannot do background work */
798 * Structures and routines associated with pagedep caching.
800 LIST_HEAD(pagedep_hashhead, pagedep) *pagedep_hashtbl;
801 u_long pagedep_hash; /* size of hash table - 1 */
802 #define PAGEDEP_HASH(mp, inum, lbn) \
803 (&pagedep_hashtbl[((((register_t)(mp)) >> 13) + (inum) + (lbn)) & \
805 static struct sema pagedep_in_progress;
808 * Helper routine for pagedep_lookup()
812 pagedep_find(struct pagedep_hashhead *pagedephd, ino_t ino, ufs_lbn_t lbn,
815 struct pagedep *pagedep;
817 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
818 if (ino == pagedep->pd_ino &&
819 lbn == pagedep->pd_lbn &&
820 mp == pagedep->pd_mnt) {
828 * Look up a pagedep. Return 1 if found, 0 if not found.
829 * If not found, allocate if DEPALLOC flag is passed.
830 * Found or allocated entry is returned in pagedeppp.
831 * This routine must be called with splbio interrupts blocked.
834 pagedep_lookup(struct inode *ip, ufs_lbn_t lbn, int flags,
835 struct pagedep **pagedeppp)
837 struct pagedep *pagedep;
838 struct pagedep_hashhead *pagedephd;
842 KKASSERT(lock_held(&lk) > 0);
844 mp = ITOV(ip)->v_mount;
845 pagedephd = PAGEDEP_HASH(mp, ip->i_number, lbn);
847 *pagedeppp = pagedep_find(pagedephd, ip->i_number, lbn, mp);
850 if ((flags & DEPALLOC) == 0)
852 if (sema_get(&pagedep_in_progress, &lk) == 0)
856 pagedep = kmalloc(sizeof(struct pagedep), M_PAGEDEP,
857 M_SOFTDEP_FLAGS | M_ZERO);
859 if (pagedep_find(pagedephd, ip->i_number, lbn, mp)) {
860 kprintf("pagedep_lookup: blocking race avoided\n");
861 sema_release(&pagedep_in_progress, &lk);
862 kfree(pagedep, M_PAGEDEP);
866 pagedep->pd_list.wk_type = D_PAGEDEP;
867 pagedep->pd_mnt = mp;
868 pagedep->pd_ino = ip->i_number;
869 pagedep->pd_lbn = lbn;
870 LIST_INIT(&pagedep->pd_dirremhd);
871 LIST_INIT(&pagedep->pd_pendinghd);
872 for (i = 0; i < DAHASHSZ; i++)
873 LIST_INIT(&pagedep->pd_diraddhd[i]);
874 LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
875 sema_release(&pagedep_in_progress, &lk);
876 *pagedeppp = pagedep;
881 * Structures and routines associated with inodedep caching.
883 LIST_HEAD(inodedep_hashhead, inodedep) *inodedep_hashtbl;
884 static u_long inodedep_hash; /* size of hash table - 1 */
885 static long num_inodedep; /* number of inodedep allocated */
886 #define INODEDEP_HASH(fs, inum) \
887 (&inodedep_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & inodedep_hash])
888 static struct sema inodedep_in_progress;
891 * Helper routine for inodedep_lookup()
895 inodedep_find(struct inodedep_hashhead *inodedephd, struct fs *fs, ino_t inum)
897 struct inodedep *inodedep;
899 LIST_FOREACH(inodedep, inodedephd, id_hash) {
900 if (inum == inodedep->id_ino && fs == inodedep->id_fs)
907 * Look up a inodedep. Return 1 if found, 0 if not found.
908 * If not found, allocate if DEPALLOC flag is passed.
909 * Found or allocated entry is returned in inodedeppp.
910 * This routine must be called with splbio interrupts blocked.
913 inodedep_lookup(struct fs *fs, ino_t inum, int flags,
914 struct inodedep **inodedeppp)
916 struct inodedep *inodedep;
917 struct inodedep_hashhead *inodedephd;
919 KKASSERT(lock_held(&lk) > 0);
921 inodedephd = INODEDEP_HASH(fs, inum);
923 *inodedeppp = inodedep_find(inodedephd, fs, inum);
926 if ((flags & DEPALLOC) == 0)
930 * If we are over our limit, try to improve the situation.
932 if (num_inodedep > max_softdeps / 2)
933 speedup_syncer(NULL);
934 if (num_inodedep > max_softdeps &&
935 (flags & NODELAY) == 0 &&
936 request_cleanup(FLUSH_INODES)) {
939 if (sema_get(&inodedep_in_progress, &lk) == 0)
943 inodedep = kmalloc(sizeof(struct inodedep), M_INODEDEP,
944 M_SOFTDEP_FLAGS | M_ZERO);
946 if (inodedep_find(inodedephd, fs, inum)) {
947 kprintf("inodedep_lookup: blocking race avoided\n");
948 sema_release(&inodedep_in_progress, &lk);
949 kfree(inodedep, M_INODEDEP);
952 inodedep->id_list.wk_type = D_INODEDEP;
953 inodedep->id_fs = fs;
954 inodedep->id_ino = inum;
955 inodedep->id_state = ALLCOMPLETE;
956 inodedep->id_nlinkdelta = 0;
957 inodedep->id_savedino = NULL;
958 inodedep->id_savedsize = -1;
959 inodedep->id_buf = NULL;
960 LIST_INIT(&inodedep->id_pendinghd);
961 LIST_INIT(&inodedep->id_inowait);
962 LIST_INIT(&inodedep->id_bufwait);
963 TAILQ_INIT(&inodedep->id_inoupdt);
964 TAILQ_INIT(&inodedep->id_newinoupdt);
966 LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
967 sema_release(&inodedep_in_progress, &lk);
968 *inodedeppp = inodedep;
973 * Structures and routines associated with newblk caching.
975 LIST_HEAD(newblk_hashhead, newblk) *newblk_hashtbl;
976 u_long newblk_hash; /* size of hash table - 1 */
977 #define NEWBLK_HASH(fs, inum) \
978 (&newblk_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & newblk_hash])
979 static struct sema newblk_in_progress;
982 * Helper routine for newblk_lookup()
986 newblk_find(struct newblk_hashhead *newblkhd, struct fs *fs,
987 ufs_daddr_t newblkno)
989 struct newblk *newblk;
991 LIST_FOREACH(newblk, newblkhd, nb_hash) {
992 if (newblkno == newblk->nb_newblkno && fs == newblk->nb_fs)
999 * Look up a newblk. Return 1 if found, 0 if not found.
1000 * If not found, allocate if DEPALLOC flag is passed.
1001 * Found or allocated entry is returned in newblkpp.
1004 newblk_lookup(struct fs *fs, ufs_daddr_t newblkno, int flags,
1005 struct newblk **newblkpp)
1007 struct newblk *newblk;
1008 struct newblk_hashhead *newblkhd;
1010 newblkhd = NEWBLK_HASH(fs, newblkno);
1012 *newblkpp = newblk_find(newblkhd, fs, newblkno);
1015 if ((flags & DEPALLOC) == 0)
1017 if (sema_get(&newblk_in_progress, NULL) == 0)
1020 newblk = kmalloc(sizeof(struct newblk), M_NEWBLK,
1021 M_SOFTDEP_FLAGS | M_ZERO);
1023 if (newblk_find(newblkhd, fs, newblkno)) {
1024 kprintf("newblk_lookup: blocking race avoided\n");
1025 sema_release(&pagedep_in_progress, NULL);
1026 kfree(newblk, M_NEWBLK);
1029 newblk->nb_state = 0;
1031 newblk->nb_newblkno = newblkno;
1032 LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
1033 sema_release(&newblk_in_progress, NULL);
1039 * Executed during filesystem system initialization before
1040 * mounting any filesystems.
1043 softdep_initialize(void)
1045 size_t idsize = sizeof(struct inodedep);
1046 int hsize = vfs_inodehashsize();
1048 LIST_INIT(&mkdirlisthd);
1049 LIST_INIT(&softdep_workitem_pending);
1050 max_softdeps = min(maxvnodes * 8, M_INODEDEP->ks_limit / (2 * idsize));
1052 pagedep_hashtbl = hashinit(hsize / 4, M_PAGEDEP, &pagedep_hash);
1053 lockinit(&lk, "ffs_softdep", 0, LK_CANRECURSE);
1054 sema_init(&pagedep_in_progress, "pagedep", 0);
1055 inodedep_hashtbl = hashinit(hsize, M_INODEDEP, &inodedep_hash);
1056 sema_init(&inodedep_in_progress, "inodedep", 0);
1057 newblk_hashtbl = hashinit(64, M_NEWBLK, &newblk_hash);
1058 sema_init(&newblk_in_progress, "newblk", 0);
1059 add_bio_ops(&softdep_bioops);
1063 * Called at mount time to notify the dependency code that a
1064 * filesystem wishes to use it.
1067 softdep_mount(struct vnode *devvp, struct mount *mp, struct fs *fs)
1069 struct csum cstotal;
1074 mp->mnt_flag &= ~MNT_ASYNC;
1075 mp->mnt_flag |= MNT_SOFTDEP;
1076 mp->mnt_bioops = &softdep_bioops;
1078 * When doing soft updates, the counters in the
1079 * superblock may have gotten out of sync, so we have
1080 * to scan the cylinder groups and recalculate them.
1082 if (fs->fs_clean != 0)
1084 bzero(&cstotal, sizeof cstotal);
1085 for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
1086 if ((error = bread(devvp, fsbtodoff(fs, cgtod(fs, cyl)),
1087 fs->fs_cgsize, &bp)) != 0) {
1091 cgp = (struct cg *)bp->b_data;
1092 cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
1093 cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
1094 cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
1095 cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
1096 fs->fs_cs(fs, cyl) = cgp->cg_cs;
1100 if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
1101 kprintf("ffs_mountfs: superblock updated for soft updates\n");
1103 bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
1108 * Protecting the freemaps (or bitmaps).
1110 * To eliminate the need to execute fsck before mounting a filesystem
1111 * after a power failure, one must (conservatively) guarantee that the
1112 * on-disk copy of the bitmaps never indicate that a live inode or block is
1113 * free. So, when a block or inode is allocated, the bitmap should be
1114 * updated (on disk) before any new pointers. When a block or inode is
1115 * freed, the bitmap should not be updated until all pointers have been
1116 * reset. The latter dependency is handled by the delayed de-allocation
1117 * approach described below for block and inode de-allocation. The former
1118 * dependency is handled by calling the following procedure when a block or
1119 * inode is allocated. When an inode is allocated an "inodedep" is created
1120 * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
1121 * Each "inodedep" is also inserted into the hash indexing structure so
1122 * that any additional link additions can be made dependent on the inode
1125 * The ufs filesystem maintains a number of free block counts (e.g., per
1126 * cylinder group, per cylinder and per <cylinder, rotational position> pair)
1127 * in addition to the bitmaps. These counts are used to improve efficiency
1128 * during allocation and therefore must be consistent with the bitmaps.
1129 * There is no convenient way to guarantee post-crash consistency of these
1130 * counts with simple update ordering, for two main reasons: (1) The counts
1131 * and bitmaps for a single cylinder group block are not in the same disk
1132 * sector. If a disk write is interrupted (e.g., by power failure), one may
1133 * be written and the other not. (2) Some of the counts are located in the
1134 * superblock rather than the cylinder group block. So, we focus our soft
1135 * updates implementation on protecting the bitmaps. When mounting a
1136 * filesystem, we recompute the auxiliary counts from the bitmaps.
1140 * Called just after updating the cylinder group block to allocate an inode.
1143 * bp: buffer for cylgroup block with inode map
1144 * ip: inode related to allocation
1145 * newinum: new inode number being allocated
1148 softdep_setup_inomapdep(struct buf *bp, struct inode *ip, ino_t newinum)
1150 struct inodedep *inodedep;
1151 struct bmsafemap *bmsafemap;
1154 * Create a dependency for the newly allocated inode.
1155 * Panic if it already exists as something is seriously wrong.
1156 * Otherwise add it to the dependency list for the buffer holding
1157 * the cylinder group map from which it was allocated.
1160 if ((inodedep_lookup(ip->i_fs, newinum, DEPALLOC|NODELAY, &inodedep))) {
1161 panic("softdep_setup_inomapdep: found inode");
1163 inodedep->id_buf = bp;
1164 inodedep->id_state &= ~DEPCOMPLETE;
1165 bmsafemap = bmsafemap_lookup(bp);
1166 LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
1171 * Called just after updating the cylinder group block to
1172 * allocate block or fragment.
1175 * bp: buffer for cylgroup block with block map
1176 * fs: filesystem doing allocation
1177 * newblkno: number of newly allocated block
1180 softdep_setup_blkmapdep(struct buf *bp, struct fs *fs,
1181 ufs_daddr_t newblkno)
1183 struct newblk *newblk;
1184 struct bmsafemap *bmsafemap;
1187 * Create a dependency for the newly allocated block.
1188 * Add it to the dependency list for the buffer holding
1189 * the cylinder group map from which it was allocated.
1191 if (newblk_lookup(fs, newblkno, DEPALLOC, &newblk) != 0)
1192 panic("softdep_setup_blkmapdep: found block");
1194 newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(bp);
1195 LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
1200 * Find the bmsafemap associated with a cylinder group buffer.
1201 * If none exists, create one. The buffer must be locked when
1202 * this routine is called and this routine must be called with
1203 * splbio interrupts blocked.
1205 static struct bmsafemap *
1206 bmsafemap_lookup(struct buf *bp)
1208 struct bmsafemap *bmsafemap;
1209 struct worklist *wk;
1211 KKASSERT(lock_held(&lk) > 0);
1213 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
1214 if (wk->wk_type == D_BMSAFEMAP)
1215 return (WK_BMSAFEMAP(wk));
1218 bmsafemap = kmalloc(sizeof(struct bmsafemap), M_BMSAFEMAP,
1220 bmsafemap->sm_list.wk_type = D_BMSAFEMAP;
1221 bmsafemap->sm_list.wk_state = 0;
1222 bmsafemap->sm_buf = bp;
1223 LIST_INIT(&bmsafemap->sm_allocdirecthd);
1224 LIST_INIT(&bmsafemap->sm_allocindirhd);
1225 LIST_INIT(&bmsafemap->sm_inodedephd);
1226 LIST_INIT(&bmsafemap->sm_newblkhd);
1228 WORKLIST_INSERT_BP(bp, &bmsafemap->sm_list);
1233 * Direct block allocation dependencies.
1235 * When a new block is allocated, the corresponding disk locations must be
1236 * initialized (with zeros or new data) before the on-disk inode points to
1237 * them. Also, the freemap from which the block was allocated must be
1238 * updated (on disk) before the inode's pointer. These two dependencies are
1239 * independent of each other and are needed for all file blocks and indirect
1240 * blocks that are pointed to directly by the inode. Just before the
1241 * "in-core" version of the inode is updated with a newly allocated block
1242 * number, a procedure (below) is called to setup allocation dependency
1243 * structures. These structures are removed when the corresponding
1244 * dependencies are satisfied or when the block allocation becomes obsolete
1245 * (i.e., the file is deleted, the block is de-allocated, or the block is a
1246 * fragment that gets upgraded). All of these cases are handled in
1247 * procedures described later.
1249 * When a file extension causes a fragment to be upgraded, either to a larger
1250 * fragment or to a full block, the on-disk location may change (if the
1251 * previous fragment could not simply be extended). In this case, the old
1252 * fragment must be de-allocated, but not until after the inode's pointer has
1253 * been updated. In most cases, this is handled by later procedures, which
1254 * will construct a "freefrag" structure to be added to the workitem queue
1255 * when the inode update is complete (or obsolete). The main exception to
1256 * this is when an allocation occurs while a pending allocation dependency
1257 * (for the same block pointer) remains. This case is handled in the main
1258 * allocation dependency setup procedure by immediately freeing the
1259 * unreferenced fragments.
1262 * ip: inode to which block is being added
1263 * lbn: block pointer within inode
1264 * newblkno: disk block number being added
1265 * oldblkno: previous block number, 0 unless frag
1266 * newsize: size of new block
1267 * oldsize: size of new block
1268 * bp: bp for allocated block
1271 softdep_setup_allocdirect(struct inode *ip, ufs_lbn_t lbn, ufs_daddr_t newblkno,
1272 ufs_daddr_t oldblkno, long newsize, long oldsize,
1275 struct allocdirect *adp, *oldadp;
1276 struct allocdirectlst *adphead;
1277 struct bmsafemap *bmsafemap;
1278 struct inodedep *inodedep;
1279 struct pagedep *pagedep;
1280 struct newblk *newblk;
1282 adp = kmalloc(sizeof(struct allocdirect), M_ALLOCDIRECT,
1283 M_SOFTDEP_FLAGS | M_ZERO);
1284 adp->ad_list.wk_type = D_ALLOCDIRECT;
1286 adp->ad_newblkno = newblkno;
1287 adp->ad_oldblkno = oldblkno;
1288 adp->ad_newsize = newsize;
1289 adp->ad_oldsize = oldsize;
1290 adp->ad_state = ATTACHED;
1291 if (newblkno == oldblkno)
1292 adp->ad_freefrag = NULL;
1294 adp->ad_freefrag = newfreefrag(ip, oldblkno, oldsize);
1296 if (newblk_lookup(ip->i_fs, newblkno, 0, &newblk) == 0)
1297 panic("softdep_setup_allocdirect: lost block");
1300 inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC | NODELAY, &inodedep);
1301 adp->ad_inodedep = inodedep;
1303 if (newblk->nb_state == DEPCOMPLETE) {
1304 adp->ad_state |= DEPCOMPLETE;
1307 bmsafemap = newblk->nb_bmsafemap;
1308 adp->ad_buf = bmsafemap->sm_buf;
1309 LIST_REMOVE(newblk, nb_deps);
1310 LIST_INSERT_HEAD(&bmsafemap->sm_allocdirecthd, adp, ad_deps);
1312 LIST_REMOVE(newblk, nb_hash);
1313 kfree(newblk, M_NEWBLK);
1315 WORKLIST_INSERT_BP(bp, &adp->ad_list);
1316 if (lbn >= NDADDR) {
1317 /* allocating an indirect block */
1318 if (oldblkno != 0) {
1319 panic("softdep_setup_allocdirect: non-zero indir");
1323 * Allocating a direct block.
1325 * If we are allocating a directory block, then we must
1326 * allocate an associated pagedep to track additions and
1329 if ((ip->i_mode & IFMT) == IFDIR &&
1330 pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0) {
1331 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
1335 * The list of allocdirects must be kept in sorted and ascending
1336 * order so that the rollback routines can quickly determine the
1337 * first uncommitted block (the size of the file stored on disk
1338 * ends at the end of the lowest committed fragment, or if there
1339 * are no fragments, at the end of the highest committed block).
1340 * Since files generally grow, the typical case is that the new
1341 * block is to be added at the end of the list. We speed this
1342 * special case by checking against the last allocdirect in the
1343 * list before laboriously traversing the list looking for the
1346 adphead = &inodedep->id_newinoupdt;
1347 oldadp = TAILQ_LAST(adphead, allocdirectlst);
1348 if (oldadp == NULL || oldadp->ad_lbn <= lbn) {
1349 /* insert at end of list */
1350 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
1351 if (oldadp != NULL && oldadp->ad_lbn == lbn)
1352 allocdirect_merge(adphead, adp, oldadp);
1356 TAILQ_FOREACH(oldadp, adphead, ad_next) {
1357 if (oldadp->ad_lbn >= lbn)
1360 if (oldadp == NULL) {
1361 panic("softdep_setup_allocdirect: lost entry");
1363 /* insert in middle of list */
1364 TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
1365 if (oldadp->ad_lbn == lbn)
1366 allocdirect_merge(adphead, adp, oldadp);
1371 * Replace an old allocdirect dependency with a newer one.
1372 * This routine must be called with splbio interrupts blocked.
1375 * adphead: head of list holding allocdirects
1376 * newadp: allocdirect being added
1377 * oldadp: existing allocdirect being checked
1380 allocdirect_merge(struct allocdirectlst *adphead,
1381 struct allocdirect *newadp,
1382 struct allocdirect *oldadp)
1384 struct freefrag *freefrag;
1386 KKASSERT(lock_held(&lk) > 0);
1388 if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
1389 newadp->ad_oldsize != oldadp->ad_newsize ||
1390 newadp->ad_lbn >= NDADDR) {
1391 panic("allocdirect_check: old %d != new %d || lbn %ld >= %d",
1392 newadp->ad_oldblkno, oldadp->ad_newblkno, newadp->ad_lbn,
1395 newadp->ad_oldblkno = oldadp->ad_oldblkno;
1396 newadp->ad_oldsize = oldadp->ad_oldsize;
1398 * If the old dependency had a fragment to free or had never
1399 * previously had a block allocated, then the new dependency
1400 * can immediately post its freefrag and adopt the old freefrag.
1401 * This action is done by swapping the freefrag dependencies.
1402 * The new dependency gains the old one's freefrag, and the
1403 * old one gets the new one and then immediately puts it on
1404 * the worklist when it is freed by free_allocdirect. It is
1405 * not possible to do this swap when the old dependency had a
1406 * non-zero size but no previous fragment to free. This condition
1407 * arises when the new block is an extension of the old block.
1408 * Here, the first part of the fragment allocated to the new
1409 * dependency is part of the block currently claimed on disk by
1410 * the old dependency, so cannot legitimately be freed until the
1411 * conditions for the new dependency are fulfilled.
1413 if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
1414 freefrag = newadp->ad_freefrag;
1415 newadp->ad_freefrag = oldadp->ad_freefrag;
1416 oldadp->ad_freefrag = freefrag;
1418 free_allocdirect(adphead, oldadp, 0);
1422 * Allocate a new freefrag structure if needed.
1424 static struct freefrag *
1425 newfreefrag(struct inode *ip, ufs_daddr_t blkno, long size)
1427 struct freefrag *freefrag;
1433 if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
1434 panic("newfreefrag: frag size");
1435 freefrag = kmalloc(sizeof(struct freefrag), M_FREEFRAG,
1437 freefrag->ff_list.wk_type = D_FREEFRAG;
1438 freefrag->ff_state = ip->i_uid & ~ONWORKLIST; /* XXX - used below */
1439 freefrag->ff_inum = ip->i_number;
1440 freefrag->ff_fs = fs;
1441 freefrag->ff_devvp = ip->i_devvp;
1442 freefrag->ff_blkno = blkno;
1443 freefrag->ff_fragsize = size;
1448 * This workitem de-allocates fragments that were replaced during
1449 * file block allocation.
1452 handle_workitem_freefrag(struct freefrag *freefrag)
1456 tip.i_fs = freefrag->ff_fs;
1457 tip.i_devvp = freefrag->ff_devvp;
1458 tip.i_dev = freefrag->ff_devvp->v_rdev;
1459 tip.i_number = freefrag->ff_inum;
1460 tip.i_uid = freefrag->ff_state & ~ONWORKLIST; /* XXX - set above */
1461 ffs_blkfree(&tip, freefrag->ff_blkno, freefrag->ff_fragsize);
1462 kfree(freefrag, M_FREEFRAG);
1466 * Indirect block allocation dependencies.
1468 * The same dependencies that exist for a direct block also exist when
1469 * a new block is allocated and pointed to by an entry in a block of
1470 * indirect pointers. The undo/redo states described above are also
1471 * used here. Because an indirect block contains many pointers that
1472 * may have dependencies, a second copy of the entire in-memory indirect
1473 * block is kept. The buffer cache copy is always completely up-to-date.
1474 * The second copy, which is used only as a source for disk writes,
1475 * contains only the safe pointers (i.e., those that have no remaining
1476 * update dependencies). The second copy is freed when all pointers
1477 * are safe. The cache is not allowed to replace indirect blocks with
1478 * pending update dependencies. If a buffer containing an indirect
1479 * block with dependencies is written, these routines will mark it
1480 * dirty again. It can only be successfully written once all the
1481 * dependencies are removed. The ffs_fsync routine in conjunction with
1482 * softdep_sync_metadata work together to get all the dependencies
1483 * removed so that a file can be successfully written to disk. Three
1484 * procedures are used when setting up indirect block pointer
1485 * dependencies. The division is necessary because of the organization
1486 * of the "balloc" routine and because of the distinction between file
1487 * pages and file metadata blocks.
1491 * Allocate a new allocindir structure.
1494 * ip: inode for file being extended
1495 * ptrno: offset of pointer in indirect block
1496 * newblkno: disk block number being added
1497 * oldblkno: previous block number, 0 if none
1499 static struct allocindir *
1500 newallocindir(struct inode *ip, int ptrno, ufs_daddr_t newblkno,
1501 ufs_daddr_t oldblkno)
1503 struct allocindir *aip;
1505 aip = kmalloc(sizeof(struct allocindir), M_ALLOCINDIR,
1506 M_SOFTDEP_FLAGS | M_ZERO);
1507 aip->ai_list.wk_type = D_ALLOCINDIR;
1508 aip->ai_state = ATTACHED;
1509 aip->ai_offset = ptrno;
1510 aip->ai_newblkno = newblkno;
1511 aip->ai_oldblkno = oldblkno;
1512 aip->ai_freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize);
1517 * Called just before setting an indirect block pointer
1518 * to a newly allocated file page.
1521 * ip: inode for file being extended
1522 * lbn: allocated block number within file
1523 * bp: buffer with indirect blk referencing page
1524 * ptrno: offset of pointer in indirect block
1525 * newblkno: disk block number being added
1526 * oldblkno: previous block number, 0 if none
1527 * nbp: buffer holding allocated page
1530 softdep_setup_allocindir_page(struct inode *ip, ufs_lbn_t lbn,
1531 struct buf *bp, int ptrno,
1532 ufs_daddr_t newblkno, ufs_daddr_t oldblkno,
1535 struct allocindir *aip;
1536 struct pagedep *pagedep;
1538 aip = newallocindir(ip, ptrno, newblkno, oldblkno);
1541 * If we are allocating a directory page, then we must
1542 * allocate an associated pagedep to track additions and
1545 if ((ip->i_mode & IFMT) == IFDIR &&
1546 pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0)
1547 WORKLIST_INSERT_BP(nbp, &pagedep->pd_list);
1548 WORKLIST_INSERT_BP(nbp, &aip->ai_list);
1550 setup_allocindir_phase2(bp, ip, aip);
1554 * Called just before setting an indirect block pointer to a
1555 * newly allocated indirect block.
1557 * nbp: newly allocated indirect block
1558 * ip: inode for file being extended
1559 * bp: indirect block referencing allocated block
1560 * ptrno: offset of pointer in indirect block
1561 * newblkno: disk block number being added
1564 softdep_setup_allocindir_meta(struct buf *nbp, struct inode *ip,
1565 struct buf *bp, int ptrno,
1566 ufs_daddr_t newblkno)
1568 struct allocindir *aip;
1570 aip = newallocindir(ip, ptrno, newblkno, 0);
1572 WORKLIST_INSERT_BP(nbp, &aip->ai_list);
1574 setup_allocindir_phase2(bp, ip, aip);
1578 * Called to finish the allocation of the "aip" allocated
1579 * by one of the two routines above.
1582 * bp: in-memory copy of the indirect block
1583 * ip: inode for file being extended
1584 * aip: allocindir allocated by the above routines
1587 setup_allocindir_phase2(struct buf *bp, struct inode *ip,
1588 struct allocindir *aip)
1590 struct worklist *wk;
1591 struct indirdep *indirdep, *newindirdep;
1592 struct bmsafemap *bmsafemap;
1593 struct allocindir *oldaip;
1594 struct freefrag *freefrag;
1595 struct newblk *newblk;
1597 if (bp->b_loffset >= 0)
1598 panic("setup_allocindir_phase2: not indir blk");
1599 for (indirdep = NULL, newindirdep = NULL; ; ) {
1601 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
1602 if (wk->wk_type != D_INDIRDEP)
1604 indirdep = WK_INDIRDEP(wk);
1607 if (indirdep == NULL && newindirdep) {
1608 indirdep = newindirdep;
1609 WORKLIST_INSERT_BP(bp, &indirdep->ir_list);
1614 if (newblk_lookup(ip->i_fs, aip->ai_newblkno, 0,
1616 panic("setup_allocindir: lost block");
1618 if (newblk->nb_state == DEPCOMPLETE) {
1619 aip->ai_state |= DEPCOMPLETE;
1622 bmsafemap = newblk->nb_bmsafemap;
1623 aip->ai_buf = bmsafemap->sm_buf;
1624 LIST_REMOVE(newblk, nb_deps);
1625 LIST_INSERT_HEAD(&bmsafemap->sm_allocindirhd,
1628 LIST_REMOVE(newblk, nb_hash);
1629 kfree(newblk, M_NEWBLK);
1630 aip->ai_indirdep = indirdep;
1632 * Check to see if there is an existing dependency
1633 * for this block. If there is, merge the old
1634 * dependency into the new one.
1636 if (aip->ai_oldblkno == 0)
1640 LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next)
1641 if (oldaip->ai_offset == aip->ai_offset)
1643 if (oldaip != NULL) {
1644 if (oldaip->ai_newblkno != aip->ai_oldblkno) {
1645 panic("setup_allocindir_phase2: blkno");
1647 aip->ai_oldblkno = oldaip->ai_oldblkno;
1648 freefrag = oldaip->ai_freefrag;
1649 oldaip->ai_freefrag = aip->ai_freefrag;
1650 aip->ai_freefrag = freefrag;
1651 free_allocindir(oldaip, NULL);
1653 LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
1654 ((ufs_daddr_t *)indirdep->ir_savebp->b_data)
1655 [aip->ai_offset] = aip->ai_oldblkno;
1660 * Avoid any possibility of data corruption by
1661 * ensuring that our old version is thrown away.
1663 newindirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
1664 brelse(newindirdep->ir_savebp);
1665 WORKITEM_FREE((caddr_t)newindirdep, D_INDIRDEP);
1669 newindirdep = kmalloc(sizeof(struct indirdep), M_INDIRDEP,
1671 newindirdep->ir_list.wk_type = D_INDIRDEP;
1672 newindirdep->ir_state = ATTACHED;
1673 LIST_INIT(&newindirdep->ir_deplisthd);
1674 LIST_INIT(&newindirdep->ir_donehd);
1675 if (bp->b_bio2.bio_offset == NOOFFSET) {
1676 VOP_BMAP(bp->b_vp, bp->b_bio1.bio_offset,
1677 &bp->b_bio2.bio_offset, NULL, NULL,
1680 KKASSERT(bp->b_bio2.bio_offset != NOOFFSET);
1681 newindirdep->ir_savebp = getblk(ip->i_devvp,
1682 bp->b_bio2.bio_offset,
1683 bp->b_bcount, 0, 0);
1684 BUF_KERNPROC(newindirdep->ir_savebp);
1685 bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
1690 * Block de-allocation dependencies.
1692 * When blocks are de-allocated, the on-disk pointers must be nullified before
1693 * the blocks are made available for use by other files. (The true
1694 * requirement is that old pointers must be nullified before new on-disk
1695 * pointers are set. We chose this slightly more stringent requirement to
1696 * reduce complexity.) Our implementation handles this dependency by updating
1697 * the inode (or indirect block) appropriately but delaying the actual block
1698 * de-allocation (i.e., freemap and free space count manipulation) until
1699 * after the updated versions reach stable storage. After the disk is
1700 * updated, the blocks can be safely de-allocated whenever it is convenient.
1701 * This implementation handles only the common case of reducing a file's
1702 * length to zero. Other cases are handled by the conventional synchronous
1705 * The ffs implementation with which we worked double-checks
1706 * the state of the block pointers and file size as it reduces
1707 * a file's length. Some of this code is replicated here in our
1708 * soft updates implementation. The freeblks->fb_chkcnt field is
1709 * used to transfer a part of this information to the procedure
1710 * that eventually de-allocates the blocks.
1712 * This routine should be called from the routine that shortens
1713 * a file's length, before the inode's size or block pointers
1714 * are modified. It will save the block pointer information for
1715 * later release and zero the inode so that the calling routine
1718 struct softdep_setup_freeblocks_info {
1723 static int softdep_setup_freeblocks_bp(struct buf *bp, void *data);
1727 * ip: The inode whose length is to be reduced
1728 * length: The new length for the file
1731 softdep_setup_freeblocks(struct inode *ip, off_t length)
1733 struct softdep_setup_freeblocks_info info;
1734 struct freeblks *freeblks;
1735 struct inodedep *inodedep;
1736 struct allocdirect *adp;
1740 int i, error, delay;
1745 panic("softde_setup_freeblocks: non-zero length");
1746 freeblks = kmalloc(sizeof(struct freeblks), M_FREEBLKS,
1747 M_SOFTDEP_FLAGS | M_ZERO);
1748 freeblks->fb_list.wk_type = D_FREEBLKS;
1749 freeblks->fb_state = ATTACHED;
1750 freeblks->fb_uid = ip->i_uid;
1751 freeblks->fb_previousinum = ip->i_number;
1752 freeblks->fb_devvp = ip->i_devvp;
1753 freeblks->fb_fs = fs;
1754 freeblks->fb_oldsize = ip->i_size;
1755 freeblks->fb_newsize = length;
1756 freeblks->fb_chkcnt = ip->i_blocks;
1757 for (i = 0; i < NDADDR; i++) {
1758 freeblks->fb_dblks[i] = ip->i_db[i];
1761 for (i = 0; i < NIADDR; i++) {
1762 freeblks->fb_iblks[i] = ip->i_ib[i];
1768 * Push the zero'ed inode to to its disk buffer so that we are free
1769 * to delete its dependencies below. Once the dependencies are gone
1770 * the buffer can be safely released.
1772 if ((error = bread(ip->i_devvp,
1773 fsbtodoff(fs, ino_to_fsba(fs, ip->i_number)),
1774 (int)fs->fs_bsize, &bp)) != 0)
1775 softdep_error("softdep_setup_freeblocks", error);
1776 *((struct ufs1_dinode *)bp->b_data + ino_to_fsbo(fs, ip->i_number)) =
1779 * Find and eliminate any inode dependencies.
1782 (void) inodedep_lookup(fs, ip->i_number, DEPALLOC, &inodedep);
1783 if ((inodedep->id_state & IOSTARTED) != 0) {
1784 panic("softdep_setup_freeblocks: inode busy");
1787 * Add the freeblks structure to the list of operations that
1788 * must await the zero'ed inode being written to disk. If we
1789 * still have a bitmap dependency (delay == 0), then the inode
1790 * has never been written to disk, so we can process the
1791 * freeblks below once we have deleted the dependencies.
1793 delay = (inodedep->id_state & DEPCOMPLETE);
1795 WORKLIST_INSERT(&inodedep->id_bufwait, &freeblks->fb_list);
1797 * Because the file length has been truncated to zero, any
1798 * pending block allocation dependency structures associated
1799 * with this inode are obsolete and can simply be de-allocated.
1800 * We must first merge the two dependency lists to get rid of
1801 * any duplicate freefrag structures, then purge the merged list.
1803 merge_inode_lists(inodedep);
1804 while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
1805 free_allocdirect(&inodedep->id_inoupdt, adp, 1);
1809 * We must wait for any I/O in progress to finish so that
1810 * all potential buffers on the dirty list will be visible.
1811 * Once they are all there, walk the list and get rid of
1816 drain_output(vp, 1);
1820 lwkt_gettoken(&vp->v_token);
1822 count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
1823 softdep_setup_freeblocks_bp, &info);
1824 } while (count != 0);
1825 lwkt_reltoken(&vp->v_token);
1827 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) != 0)
1828 (void)free_inodedep(inodedep);
1831 freeblks->fb_state |= DEPCOMPLETE;
1833 * If the inode with zeroed block pointers is now on disk
1834 * we can start freeing blocks. Add freeblks to the worklist
1835 * instead of calling handle_workitem_freeblocks directly as
1836 * it is more likely that additional IO is needed to complete
1837 * the request here than in the !delay case.
1839 if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
1840 add_to_worklist(&freeblks->fb_list);
1845 * If the inode has never been written to disk (delay == 0),
1846 * then we can process the freeblks now that we have deleted
1850 handle_workitem_freeblocks(freeblks);
1854 softdep_setup_freeblocks_bp(struct buf *bp, void *data)
1856 struct softdep_setup_freeblocks_info *info = data;
1857 struct inodedep *inodedep;
1859 if (getdirtybuf(&bp, MNT_WAIT) == 0) {
1860 kprintf("softdep_setup_freeblocks_bp(1): caught bp %p going away\n", bp);
1863 if (bp->b_vp != ITOV(info->ip) || (bp->b_flags & B_DELWRI) == 0) {
1864 kprintf("softdep_setup_freeblocks_bp(2): caught bp %p going away\n", bp);
1868 (void) inodedep_lookup(info->fs, info->ip->i_number, 0, &inodedep);
1869 deallocate_dependencies(bp, inodedep);
1870 bp->b_flags |= B_INVAL | B_NOCACHE;
1878 * Reclaim any dependency structures from a buffer that is about to
1879 * be reallocated to a new vnode. The buffer must be locked, thus,
1880 * no I/O completion operations can occur while we are manipulating
1881 * its associated dependencies. The mutex is held so that other I/O's
1882 * associated with related dependencies do not occur.
1885 deallocate_dependencies(struct buf *bp, struct inodedep *inodedep)
1887 struct worklist *wk;
1888 struct indirdep *indirdep;
1889 struct allocindir *aip;
1890 struct pagedep *pagedep;
1891 struct dirrem *dirrem;
1895 while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
1896 switch (wk->wk_type) {
1899 indirdep = WK_INDIRDEP(wk);
1901 * None of the indirect pointers will ever be visible,
1902 * so they can simply be tossed. GOINGAWAY ensures
1903 * that allocated pointers will be saved in the buffer
1904 * cache until they are freed. Note that they will
1905 * only be able to be found by their physical address
1906 * since the inode mapping the logical address will
1907 * be gone. The save buffer used for the safe copy
1908 * was allocated in setup_allocindir_phase2 using
1909 * the physical address so it could be used for this
1910 * purpose. Hence we swap the safe copy with the real
1911 * copy, allowing the safe copy to be freed and holding
1912 * on to the real copy for later use in indir_trunc.
1914 * NOTE: ir_savebp is relative to the block device
1915 * so b_bio1 contains the device block number.
1917 if (indirdep->ir_state & GOINGAWAY) {
1918 panic("deallocate_dependencies: already gone");
1920 indirdep->ir_state |= GOINGAWAY;
1921 while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
1922 free_allocindir(aip, inodedep);
1923 if (bp->b_bio1.bio_offset >= 0 ||
1924 bp->b_bio2.bio_offset != indirdep->ir_savebp->b_bio1.bio_offset) {
1925 panic("deallocate_dependencies: not indir");
1927 bcopy(bp->b_data, indirdep->ir_savebp->b_data,
1929 WORKLIST_REMOVE(wk);
1930 WORKLIST_INSERT_BP(indirdep->ir_savebp, wk);
1934 pagedep = WK_PAGEDEP(wk);
1936 * None of the directory additions will ever be
1937 * visible, so they can simply be tossed.
1939 for (i = 0; i < DAHASHSZ; i++)
1941 LIST_FIRST(&pagedep->pd_diraddhd[i])))
1943 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
1946 * Copy any directory remove dependencies to the list
1947 * to be processed after the zero'ed inode is written.
1948 * If the inode has already been written, then they
1949 * can be dumped directly onto the work list.
1951 LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
1952 LIST_REMOVE(dirrem, dm_next);
1953 dirrem->dm_dirinum = pagedep->pd_ino;
1954 if (inodedep == NULL ||
1955 (inodedep->id_state & ALLCOMPLETE) ==
1957 add_to_worklist(&dirrem->dm_list);
1959 WORKLIST_INSERT(&inodedep->id_bufwait,
1962 WORKLIST_REMOVE(&pagedep->pd_list);
1963 LIST_REMOVE(pagedep, pd_hash);
1964 WORKITEM_FREE(pagedep, D_PAGEDEP);
1968 free_allocindir(WK_ALLOCINDIR(wk), inodedep);
1973 panic("deallocate_dependencies: Unexpected type %s",
1974 TYPENAME(wk->wk_type));
1978 panic("deallocate_dependencies: Unknown type %s",
1979 TYPENAME(wk->wk_type));
1986 * Free an allocdirect. Generate a new freefrag work request if appropriate.
1987 * This routine must be called with splbio interrupts blocked.
1990 free_allocdirect(struct allocdirectlst *adphead,
1991 struct allocdirect *adp, int delay)
1993 KKASSERT(lock_held(&lk) > 0);
1995 if ((adp->ad_state & DEPCOMPLETE) == 0)
1996 LIST_REMOVE(adp, ad_deps);
1997 TAILQ_REMOVE(adphead, adp, ad_next);
1998 if ((adp->ad_state & COMPLETE) == 0)
1999 WORKLIST_REMOVE(&adp->ad_list);
2000 if (adp->ad_freefrag != NULL) {
2002 WORKLIST_INSERT(&adp->ad_inodedep->id_bufwait,
2003 &adp->ad_freefrag->ff_list);
2005 add_to_worklist(&adp->ad_freefrag->ff_list);
2007 WORKITEM_FREE(adp, D_ALLOCDIRECT);
2011 * Prepare an inode to be freed. The actual free operation is not
2012 * done until the zero'ed inode has been written to disk.
2015 softdep_freefile(struct vnode *pvp, ino_t ino, int mode)
2017 struct inode *ip = VTOI(pvp);
2018 struct inodedep *inodedep;
2019 struct freefile *freefile;
2022 * This sets up the inode de-allocation dependency.
2024 freefile = kmalloc(sizeof(struct freefile), M_FREEFILE,
2026 freefile->fx_list.wk_type = D_FREEFILE;
2027 freefile->fx_list.wk_state = 0;
2028 freefile->fx_mode = mode;
2029 freefile->fx_oldinum = ino;
2030 freefile->fx_devvp = ip->i_devvp;
2031 freefile->fx_fs = ip->i_fs;
2034 * If the inodedep does not exist, then the zero'ed inode has
2035 * been written to disk. If the allocated inode has never been
2036 * written to disk, then the on-disk inode is zero'ed. In either
2037 * case we can free the file immediately.
2040 if (inodedep_lookup(ip->i_fs, ino, 0, &inodedep) == 0 ||
2041 check_inode_unwritten(inodedep)) {
2043 handle_workitem_freefile(freefile);
2046 WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
2051 * Check to see if an inode has never been written to disk. If
2052 * so free the inodedep and return success, otherwise return failure.
2053 * This routine must be called with splbio interrupts blocked.
2055 * If we still have a bitmap dependency, then the inode has never
2056 * been written to disk. Drop the dependency as it is no longer
2057 * necessary since the inode is being deallocated. We set the
2058 * ALLCOMPLETE flags since the bitmap now properly shows that the
2059 * inode is not allocated. Even if the inode is actively being
2060 * written, it has been rolled back to its zero'ed state, so we
2061 * are ensured that a zero inode is what is on the disk. For short
2062 * lived files, this change will usually result in removing all the
2063 * dependencies from the inode so that it can be freed immediately.
2066 check_inode_unwritten(struct inodedep *inodedep)
2069 if ((inodedep->id_state & DEPCOMPLETE) != 0 ||
2070 LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2071 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2072 LIST_FIRST(&inodedep->id_inowait) != NULL ||
2073 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2074 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2075 inodedep->id_nlinkdelta != 0)
2079 * Another process might be in initiate_write_inodeblock
2080 * trying to allocate memory without holding "Softdep Lock".
2082 if ((inodedep->id_state & IOSTARTED) != 0 &&
2083 inodedep->id_savedino == NULL)
2086 inodedep->id_state |= ALLCOMPLETE;
2087 LIST_REMOVE(inodedep, id_deps);
2088 inodedep->id_buf = NULL;
2089 if (inodedep->id_state & ONWORKLIST)
2090 WORKLIST_REMOVE(&inodedep->id_list);
2091 if (inodedep->id_savedino != NULL) {
2092 kfree(inodedep->id_savedino, M_INODEDEP);
2093 inodedep->id_savedino = NULL;
2095 if (free_inodedep(inodedep) == 0) {
2096 panic("check_inode_unwritten: busy inode");
2102 * Try to free an inodedep structure. Return 1 if it could be freed.
2105 free_inodedep(struct inodedep *inodedep)
2108 if ((inodedep->id_state & ONWORKLIST) != 0 ||
2109 (inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
2110 LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2111 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2112 LIST_FIRST(&inodedep->id_inowait) != NULL ||
2113 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2114 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2115 inodedep->id_nlinkdelta != 0 || inodedep->id_savedino != NULL)
2117 LIST_REMOVE(inodedep, id_hash);
2118 WORKITEM_FREE(inodedep, D_INODEDEP);
2124 * This workitem routine performs the block de-allocation.
2125 * The workitem is added to the pending list after the updated
2126 * inode block has been written to disk. As mentioned above,
2127 * checks regarding the number of blocks de-allocated (compared
2128 * to the number of blocks allocated for the file) are also
2129 * performed in this function.
2132 handle_workitem_freeblocks(struct freeblks *freeblks)
2137 int i, level, bsize;
2138 long nblocks, blocksreleased = 0;
2139 int error, allerror = 0;
2140 ufs_lbn_t baselbns[NIADDR], tmpval;
2142 tip.i_number = freeblks->fb_previousinum;
2143 tip.i_devvp = freeblks->fb_devvp;
2144 tip.i_dev = freeblks->fb_devvp->v_rdev;
2145 tip.i_fs = freeblks->fb_fs;
2146 tip.i_size = freeblks->fb_oldsize;
2147 tip.i_uid = freeblks->fb_uid;
2148 fs = freeblks->fb_fs;
2150 baselbns[0] = NDADDR;
2151 for (i = 1; i < NIADDR; i++) {
2152 tmpval *= NINDIR(fs);
2153 baselbns[i] = baselbns[i - 1] + tmpval;
2155 nblocks = btodb(fs->fs_bsize);
2158 * Indirect blocks first.
2160 for (level = (NIADDR - 1); level >= 0; level--) {
2161 if ((bn = freeblks->fb_iblks[level]) == 0)
2163 if ((error = indir_trunc(&tip, fsbtodoff(fs, bn), level,
2164 baselbns[level], &blocksreleased)) == 0)
2166 ffs_blkfree(&tip, bn, fs->fs_bsize);
2167 blocksreleased += nblocks;
2170 * All direct blocks or frags.
2172 for (i = (NDADDR - 1); i >= 0; i--) {
2173 if ((bn = freeblks->fb_dblks[i]) == 0)
2175 bsize = blksize(fs, &tip, i);
2176 ffs_blkfree(&tip, bn, bsize);
2177 blocksreleased += btodb(bsize);
2181 if (freeblks->fb_chkcnt != blocksreleased)
2182 kprintf("handle_workitem_freeblocks: block count\n");
2184 softdep_error("handle_workitem_freeblks", allerror);
2185 #endif /* DIAGNOSTIC */
2186 WORKITEM_FREE(freeblks, D_FREEBLKS);
2190 * Release blocks associated with the inode ip and stored in the indirect
2191 * block at doffset. If level is greater than SINGLE, the block is an
2192 * indirect block and recursive calls to indirtrunc must be used to
2193 * cleanse other indirect blocks.
2196 indir_trunc(struct inode *ip, off_t doffset, int level, ufs_lbn_t lbn,
2203 struct worklist *wk;
2204 struct indirdep *indirdep;
2205 int i, lbnadd, nblocks;
2206 int error, allerror = 0;
2210 for (i = level; i > 0; i--)
2211 lbnadd *= NINDIR(fs);
2213 * Get buffer of block pointers to be freed. This routine is not
2214 * called until the zero'ed inode has been written, so it is safe
2215 * to free blocks as they are encountered. Because the inode has
2216 * been zero'ed, calls to bmap on these blocks will fail. So, we
2217 * have to use the on-disk address and the block device for the
2218 * filesystem to look them up. If the file was deleted before its
2219 * indirect blocks were all written to disk, the routine that set
2220 * us up (deallocate_dependencies) will have arranged to leave
2221 * a complete copy of the indirect block in memory for our use.
2222 * Otherwise we have to read the blocks in from the disk.
2225 if ((bp = findblk(ip->i_devvp, doffset, FINDBLK_TEST)) != NULL &&
2226 (wk = LIST_FIRST(&bp->b_dep)) != NULL) {
2228 * bp must be ir_savebp, which is held locked for our use.
2230 if (wk->wk_type != D_INDIRDEP ||
2231 (indirdep = WK_INDIRDEP(wk))->ir_savebp != bp ||
2232 (indirdep->ir_state & GOINGAWAY) == 0) {
2233 panic("indir_trunc: lost indirdep");
2235 WORKLIST_REMOVE(wk);
2236 WORKITEM_FREE(indirdep, D_INDIRDEP);
2237 if (LIST_FIRST(&bp->b_dep) != NULL) {
2238 panic("indir_trunc: dangling dep");
2243 error = bread(ip->i_devvp, doffset, (int)fs->fs_bsize, &bp);
2248 * Recursively free indirect blocks.
2250 bap = (ufs_daddr_t *)bp->b_data;
2251 nblocks = btodb(fs->fs_bsize);
2252 for (i = NINDIR(fs) - 1; i >= 0; i--) {
2253 if ((nb = bap[i]) == 0)
2256 if ((error = indir_trunc(ip, fsbtodoff(fs, nb),
2257 level - 1, lbn + (i * lbnadd), countp)) != 0)
2260 ffs_blkfree(ip, nb, fs->fs_bsize);
2263 bp->b_flags |= B_INVAL | B_NOCACHE;
2269 * Free an allocindir.
2270 * This routine must be called with splbio interrupts blocked.
2273 free_allocindir(struct allocindir *aip, struct inodedep *inodedep)
2275 struct freefrag *freefrag;
2277 KKASSERT(lock_held(&lk) > 0);
2279 if ((aip->ai_state & DEPCOMPLETE) == 0)
2280 LIST_REMOVE(aip, ai_deps);
2281 if (aip->ai_state & ONWORKLIST)
2282 WORKLIST_REMOVE(&aip->ai_list);
2283 LIST_REMOVE(aip, ai_next);
2284 if ((freefrag = aip->ai_freefrag) != NULL) {
2285 if (inodedep == NULL)
2286 add_to_worklist(&freefrag->ff_list);
2288 WORKLIST_INSERT(&inodedep->id_bufwait,
2289 &freefrag->ff_list);
2291 WORKITEM_FREE(aip, D_ALLOCINDIR);
2295 * Directory entry addition dependencies.
2297 * When adding a new directory entry, the inode (with its incremented link
2298 * count) must be written to disk before the directory entry's pointer to it.
2299 * Also, if the inode is newly allocated, the corresponding freemap must be
2300 * updated (on disk) before the directory entry's pointer. These requirements
2301 * are met via undo/redo on the directory entry's pointer, which consists
2302 * simply of the inode number.
2304 * As directory entries are added and deleted, the free space within a
2305 * directory block can become fragmented. The ufs filesystem will compact
2306 * a fragmented directory block to make space for a new entry. When this
2307 * occurs, the offsets of previously added entries change. Any "diradd"
2308 * dependency structures corresponding to these entries must be updated with
2313 * This routine is called after the in-memory inode's link
2314 * count has been incremented, but before the directory entry's
2315 * pointer to the inode has been set.
2318 * bp: buffer containing directory block
2319 * dp: inode for directory
2320 * diroffset: offset of new entry in directory
2321 * newinum: inode referenced by new directory entry
2322 * newdirbp: non-NULL => contents of new mkdir
2325 softdep_setup_directory_add(struct buf *bp, struct inode *dp, off_t diroffset,
2326 ino_t newinum, struct buf *newdirbp)
2328 int offset; /* offset of new entry within directory block */
2329 ufs_lbn_t lbn; /* block in directory containing new entry */
2332 struct pagedep *pagedep;
2333 struct inodedep *inodedep;
2334 struct mkdir *mkdir1, *mkdir2;
2337 * Whiteouts have no dependencies.
2339 if (newinum == WINO) {
2340 if (newdirbp != NULL)
2346 lbn = lblkno(fs, diroffset);
2347 offset = blkoff(fs, diroffset);
2348 dap = kmalloc(sizeof(struct diradd), M_DIRADD,
2349 M_SOFTDEP_FLAGS | M_ZERO);
2350 dap->da_list.wk_type = D_DIRADD;
2351 dap->da_offset = offset;
2352 dap->da_newinum = newinum;
2353 dap->da_state = ATTACHED;
2354 if (newdirbp == NULL) {
2355 dap->da_state |= DEPCOMPLETE;
2358 dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
2359 mkdir1 = kmalloc(sizeof(struct mkdir), M_MKDIR,
2361 mkdir1->md_list.wk_type = D_MKDIR;
2362 mkdir1->md_state = MKDIR_BODY;
2363 mkdir1->md_diradd = dap;
2364 mkdir2 = kmalloc(sizeof(struct mkdir), M_MKDIR,
2366 mkdir2->md_list.wk_type = D_MKDIR;
2367 mkdir2->md_state = MKDIR_PARENT;
2368 mkdir2->md_diradd = dap;
2370 * Dependency on "." and ".." being written to disk.
2372 mkdir1->md_buf = newdirbp;
2374 LIST_INSERT_HEAD(&mkdirlisthd, mkdir1, md_mkdirs);
2375 WORKLIST_INSERT_BP(newdirbp, &mkdir1->md_list);
2379 * Dependency on link count increase for parent directory
2382 if (inodedep_lookup(dp->i_fs, dp->i_number, 0, &inodedep) == 0
2383 || (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2384 dap->da_state &= ~MKDIR_PARENT;
2385 WORKITEM_FREE(mkdir2, D_MKDIR);
2387 LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
2388 WORKLIST_INSERT(&inodedep->id_bufwait,&mkdir2->md_list);
2392 * Link into parent directory pagedep to await its being written.
2394 if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2395 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
2396 dap->da_pagedep = pagedep;
2397 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
2400 * Link into its inodedep. Put it on the id_bufwait list if the inode
2401 * is not yet written. If it is written, do the post-inode write
2402 * processing to put it on the id_pendinghd list.
2404 (void) inodedep_lookup(fs, newinum, DEPALLOC, &inodedep);
2405 if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
2406 diradd_inode_written(dap, inodedep);
2408 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2413 * This procedure is called to change the offset of a directory
2414 * entry when compacting a directory block which must be owned
2415 * exclusively by the caller. Note that the actual entry movement
2416 * must be done in this procedure to ensure that no I/O completions
2417 * occur while the move is in progress.
2420 * dp: inode for directory
2421 * base: address of dp->i_offset
2422 * oldloc: address of old directory location
2423 * newloc: address of new directory location
2424 * entrysize: size of directory entry
2427 softdep_change_directoryentry_offset(struct inode *dp, caddr_t base,
2428 caddr_t oldloc, caddr_t newloc,
2431 int offset, oldoffset, newoffset;
2432 struct pagedep *pagedep;
2437 lbn = lblkno(dp->i_fs, dp->i_offset);
2438 offset = blkoff(dp->i_fs, dp->i_offset);
2439 if (pagedep_lookup(dp, lbn, 0, &pagedep) == 0)
2441 oldoffset = offset + (oldloc - base);
2442 newoffset = offset + (newloc - base);
2444 LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(oldoffset)], da_pdlist) {
2445 if (dap->da_offset != oldoffset)
2447 dap->da_offset = newoffset;
2448 if (DIRADDHASH(newoffset) == DIRADDHASH(oldoffset))
2450 LIST_REMOVE(dap, da_pdlist);
2451 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(newoffset)],
2457 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist) {
2458 if (dap->da_offset == oldoffset) {
2459 dap->da_offset = newoffset;
2465 bcopy(oldloc, newloc, entrysize);
2470 * Free a diradd dependency structure. This routine must be called
2471 * with splbio interrupts blocked.
2474 free_diradd(struct diradd *dap)
2476 struct dirrem *dirrem;
2477 struct pagedep *pagedep;
2478 struct inodedep *inodedep;
2479 struct mkdir *mkdir, *nextmd;
2481 KKASSERT(lock_held(&lk) > 0);
2483 WORKLIST_REMOVE(&dap->da_list);
2484 LIST_REMOVE(dap, da_pdlist);
2485 if ((dap->da_state & DIRCHG) == 0) {
2486 pagedep = dap->da_pagedep;
2488 dirrem = dap->da_previous;
2489 pagedep = dirrem->dm_pagedep;
2490 dirrem->dm_dirinum = pagedep->pd_ino;
2491 add_to_worklist(&dirrem->dm_list);
2493 if (inodedep_lookup(VFSTOUFS(pagedep->pd_mnt)->um_fs, dap->da_newinum,
2495 (void) free_inodedep(inodedep);
2496 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
2497 for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
2498 nextmd = LIST_NEXT(mkdir, md_mkdirs);
2499 if (mkdir->md_diradd != dap)
2501 dap->da_state &= ~mkdir->md_state;
2502 WORKLIST_REMOVE(&mkdir->md_list);
2503 LIST_REMOVE(mkdir, md_mkdirs);
2504 WORKITEM_FREE(mkdir, D_MKDIR);
2506 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
2507 panic("free_diradd: unfound ref");
2510 WORKITEM_FREE(dap, D_DIRADD);
2514 * Directory entry removal dependencies.
2516 * When removing a directory entry, the entry's inode pointer must be
2517 * zero'ed on disk before the corresponding inode's link count is decremented
2518 * (possibly freeing the inode for re-use). This dependency is handled by
2519 * updating the directory entry but delaying the inode count reduction until
2520 * after the directory block has been written to disk. After this point, the
2521 * inode count can be decremented whenever it is convenient.
2525 * This routine should be called immediately after removing
2526 * a directory entry. The inode's link count should not be
2527 * decremented by the calling procedure -- the soft updates
2528 * code will do this task when it is safe.
2531 * bp: buffer containing directory block
2532 * dp: inode for the directory being modified
2533 * ip: inode for directory entry being removed
2534 * isrmdir: indicates if doing RMDIR
2537 softdep_setup_remove(struct buf *bp, struct inode *dp, struct inode *ip,
2540 struct dirrem *dirrem, *prevdirrem;
2543 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.
2545 dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
2548 * If the COMPLETE flag is clear, then there were no active
2549 * entries and we want to roll back to a zeroed entry until
2550 * the new inode is committed to disk. If the COMPLETE flag is
2551 * set then we have deleted an entry that never made it to
2552 * disk. If the entry we deleted resulted from a name change,
2553 * then the old name still resides on disk. We cannot delete
2554 * its inode (returned to us in prevdirrem) until the zeroed
2555 * directory entry gets to disk. The new inode has never been
2556 * referenced on the disk, so can be deleted immediately.
2558 if ((dirrem->dm_state & COMPLETE) == 0) {
2559 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
2563 if (prevdirrem != NULL)
2564 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
2565 prevdirrem, dm_next);
2566 dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
2568 handle_workitem_remove(dirrem);
2573 * Allocate a new dirrem if appropriate and return it along with
2574 * its associated pagedep. Called without a lock, returns with lock.
2576 static long num_dirrem; /* number of dirrem allocated */
2580 * bp: buffer containing directory block
2581 * dp: inode for the directory being modified
2582 * ip: inode for directory entry being removed
2583 * isrmdir: indicates if doing RMDIR
2584 * prevdirremp: previously referenced inode, if any
2586 static struct dirrem *
2587 newdirrem(struct buf *bp, struct inode *dp, struct inode *ip,
2588 int isrmdir, struct dirrem **prevdirremp)
2593 struct dirrem *dirrem;
2594 struct pagedep *pagedep;
2597 * Whiteouts have no deletion dependencies.
2600 panic("newdirrem: whiteout");
2602 * If we are over our limit, try to improve the situation.
2603 * Limiting the number of dirrem structures will also limit
2604 * the number of freefile and freeblks structures.
2606 if (num_dirrem > max_softdeps / 4)
2607 speedup_syncer(NULL);
2608 if (num_dirrem > max_softdeps / 2) {
2610 request_cleanup(FLUSH_REMOVE);
2615 dirrem = kmalloc(sizeof(struct dirrem), M_DIRREM,
2616 M_SOFTDEP_FLAGS | M_ZERO);
2617 dirrem->dm_list.wk_type = D_DIRREM;
2618 dirrem->dm_state = isrmdir ? RMDIR : 0;
2619 dirrem->dm_mnt = ITOV(ip)->v_mount;
2620 dirrem->dm_oldinum = ip->i_number;
2621 *prevdirremp = NULL;
2624 lbn = lblkno(dp->i_fs, dp->i_offset);
2625 offset = blkoff(dp->i_fs, dp->i_offset);
2626 if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2627 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
2628 dirrem->dm_pagedep = pagedep;
2630 * Check for a diradd dependency for the same directory entry.
2631 * If present, then both dependencies become obsolete and can
2632 * be de-allocated. Check for an entry on both the pd_dirraddhd
2633 * list and the pd_pendinghd list.
2636 LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
2637 if (dap->da_offset == offset)
2641 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
2642 if (dap->da_offset == offset)
2648 * Must be ATTACHED at this point.
2650 if ((dap->da_state & ATTACHED) == 0) {
2651 panic("newdirrem: not ATTACHED");
2653 if (dap->da_newinum != ip->i_number) {
2654 panic("newdirrem: inum %"PRId64" should be %"PRId64,
2655 ip->i_number, dap->da_newinum);
2658 * If we are deleting a changed name that never made it to disk,
2659 * then return the dirrem describing the previous inode (which
2660 * represents the inode currently referenced from this entry on disk).
2662 if ((dap->da_state & DIRCHG) != 0) {
2663 *prevdirremp = dap->da_previous;
2664 dap->da_state &= ~DIRCHG;
2665 dap->da_pagedep = pagedep;
2668 * We are deleting an entry that never made it to disk.
2669 * Mark it COMPLETE so we can delete its inode immediately.
2671 dirrem->dm_state |= COMPLETE;
2677 * Directory entry change dependencies.
2679 * Changing an existing directory entry requires that an add operation
2680 * be completed first followed by a deletion. The semantics for the addition
2681 * are identical to the description of adding a new entry above except
2682 * that the rollback is to the old inode number rather than zero. Once
2683 * the addition dependency is completed, the removal is done as described
2684 * in the removal routine above.
2688 * This routine should be called immediately after changing
2689 * a directory entry. The inode's link count should not be
2690 * decremented by the calling procedure -- the soft updates
2691 * code will perform this task when it is safe.
2694 * bp: buffer containing directory block
2695 * dp: inode for the directory being modified
2696 * ip: inode for directory entry being removed
2697 * newinum: new inode number for changed entry
2698 * isrmdir: indicates if doing RMDIR
2701 softdep_setup_directory_change(struct buf *bp, struct inode *dp,
2702 struct inode *ip, ino_t newinum,
2706 struct diradd *dap = NULL;
2707 struct dirrem *dirrem, *prevdirrem;
2708 struct pagedep *pagedep;
2709 struct inodedep *inodedep;
2711 offset = blkoff(dp->i_fs, dp->i_offset);
2714 * Whiteouts do not need diradd dependencies.
2716 if (newinum != WINO) {
2717 dap = kmalloc(sizeof(struct diradd), M_DIRADD,
2718 M_SOFTDEP_FLAGS | M_ZERO);
2719 dap->da_list.wk_type = D_DIRADD;
2720 dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
2721 dap->da_offset = offset;
2722 dap->da_newinum = newinum;
2726 * Allocate a new dirrem and ACQUIRE_LOCK.
2728 dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
2729 pagedep = dirrem->dm_pagedep;
2731 * The possible values for isrmdir:
2732 * 0 - non-directory file rename
2733 * 1 - directory rename within same directory
2734 * inum - directory rename to new directory of given inode number
2735 * When renaming to a new directory, we are both deleting and
2736 * creating a new directory entry, so the link count on the new
2737 * directory should not change. Thus we do not need the followup
2738 * dirrem which is usually done in handle_workitem_remove. We set
2739 * the DIRCHG flag to tell handle_workitem_remove to skip the
2743 dirrem->dm_state |= DIRCHG;
2746 * Whiteouts have no additional dependencies,
2747 * so just put the dirrem on the correct list.
2749 if (newinum == WINO) {
2750 if ((dirrem->dm_state & COMPLETE) == 0) {
2751 LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
2754 dirrem->dm_dirinum = pagedep->pd_ino;
2755 add_to_worklist(&dirrem->dm_list);
2762 * If the COMPLETE flag is clear, then there were no active
2763 * entries and we want to roll back to the previous inode until
2764 * the new inode is committed to disk. If the COMPLETE flag is
2765 * set, then we have deleted an entry that never made it to disk.
2766 * If the entry we deleted resulted from a name change, then the old
2767 * inode reference still resides on disk. Any rollback that we do
2768 * needs to be to that old inode (returned to us in prevdirrem). If
2769 * the entry we deleted resulted from a create, then there is
2770 * no entry on the disk, so we want to roll back to zero rather
2771 * than the uncommitted inode. In either of the COMPLETE cases we
2772 * want to immediately free the unwritten and unreferenced inode.
2774 if ((dirrem->dm_state & COMPLETE) == 0) {
2775 dap->da_previous = dirrem;
2777 if (prevdirrem != NULL) {
2778 dap->da_previous = prevdirrem;
2780 dap->da_state &= ~DIRCHG;
2781 dap->da_pagedep = pagedep;
2783 dirrem->dm_dirinum = pagedep->pd_ino;
2784 add_to_worklist(&dirrem->dm_list);
2787 * Link into its inodedep. Put it on the id_bufwait list if the inode
2788 * is not yet written. If it is written, do the post-inode write
2789 * processing to put it on the id_pendinghd list.
2791 if (inodedep_lookup(dp->i_fs, newinum, DEPALLOC, &inodedep) == 0 ||
2792 (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2793 dap->da_state |= COMPLETE;
2794 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
2795 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
2797 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
2799 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2805 * Called whenever the link count on an inode is changed.
2806 * It creates an inode dependency so that the new reference(s)
2807 * to the inode cannot be committed to disk until the updated
2808 * inode has been written.
2811 * ip: the inode with the increased link count
2814 softdep_change_linkcnt(struct inode *ip)
2816 struct inodedep *inodedep;
2819 (void) inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC, &inodedep);
2820 if (ip->i_nlink < ip->i_effnlink) {
2821 panic("softdep_change_linkcnt: bad delta");
2823 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2828 * This workitem decrements the inode's link count.
2829 * If the link count reaches zero, the file is removed.
2832 handle_workitem_remove(struct dirrem *dirrem)
2834 struct inodedep *inodedep;
2840 error = VFS_VGET(dirrem->dm_mnt, NULL, dirrem->dm_oldinum, &vp);
2842 softdep_error("handle_workitem_remove: vget", error);
2847 if ((inodedep_lookup(ip->i_fs, dirrem->dm_oldinum, 0, &inodedep)) == 0){
2848 panic("handle_workitem_remove: lost inodedep");
2851 * Normal file deletion.
2853 if ((dirrem->dm_state & RMDIR) == 0) {
2855 ip->i_flag |= IN_CHANGE;
2856 if (ip->i_nlink < ip->i_effnlink) {
2857 panic("handle_workitem_remove: bad file delta");
2859 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2863 WORKITEM_FREE(dirrem, D_DIRREM);
2867 * Directory deletion. Decrement reference count for both the
2868 * just deleted parent directory entry and the reference for ".".
2869 * Next truncate the directory to length zero. When the
2870 * truncation completes, arrange to have the reference count on
2871 * the parent decremented to account for the loss of "..".
2874 ip->i_flag |= IN_CHANGE;
2875 if (ip->i_nlink < ip->i_effnlink) {
2876 panic("handle_workitem_remove: bad dir delta");
2878 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2880 if ((error = ffs_truncate(vp, (off_t)0, 0, proc0.p_ucred)) != 0)
2881 softdep_error("handle_workitem_remove: truncate", error);
2883 * Rename a directory to a new parent. Since, we are both deleting
2884 * and creating a new directory entry, the link count on the new
2885 * directory should not change. Thus we skip the followup dirrem.
2887 if (dirrem->dm_state & DIRCHG) {
2890 WORKITEM_FREE(dirrem, D_DIRREM);
2894 * If the inodedep does not exist, then the zero'ed inode has
2895 * been written to disk. If the allocated inode has never been
2896 * written to disk, then the on-disk inode is zero'ed. In either
2897 * case we can remove the file immediately.
2900 dirrem->dm_state = 0;
2901 oldinum = dirrem->dm_oldinum;
2902 dirrem->dm_oldinum = dirrem->dm_dirinum;
2903 if (inodedep_lookup(ip->i_fs, oldinum, 0, &inodedep) == 0 ||
2904 check_inode_unwritten(inodedep)) {
2907 handle_workitem_remove(dirrem);
2910 WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
2912 ip->i_flag |= IN_CHANGE;
2918 * Inode de-allocation dependencies.
2920 * When an inode's link count is reduced to zero, it can be de-allocated. We
2921 * found it convenient to postpone de-allocation until after the inode is
2922 * written to disk with its new link count (zero). At this point, all of the
2923 * on-disk inode's block pointers are nullified and, with careful dependency
2924 * list ordering, all dependencies related to the inode will be satisfied and
2925 * the corresponding dependency structures de-allocated. So, if/when the
2926 * inode is reused, there will be no mixing of old dependencies with new
2927 * ones. This artificial dependency is set up by the block de-allocation
2928 * procedure above (softdep_setup_freeblocks) and completed by the
2929 * following procedure.
2932 handle_workitem_freefile(struct freefile *freefile)
2936 struct inodedep *idp;
2941 error = inodedep_lookup(freefile->fx_fs, freefile->fx_oldinum, 0, &idp);
2944 panic("handle_workitem_freefile: inodedep survived");
2946 tip.i_devvp = freefile->fx_devvp;
2947 tip.i_dev = freefile->fx_devvp->v_rdev;
2948 tip.i_fs = freefile->fx_fs;
2950 if ((error = ffs_freefile(&vp, freefile->fx_oldinum, freefile->fx_mode)) != 0)
2951 softdep_error("handle_workitem_freefile", error);
2952 WORKITEM_FREE(freefile, D_FREEFILE);
2956 * Helper function which unlinks marker element from work list and returns
2957 * the next element on the list.
2959 static __inline struct worklist *
2960 markernext(struct worklist *marker)
2962 struct worklist *next;
2964 next = LIST_NEXT(marker, wk_list);
2965 LIST_REMOVE(marker, wk_list);
2970 * checkread, checkwrite
2972 * bioops callback - hold io_token
2975 softdep_checkread(struct buf *bp)
2977 /* nothing to do, mp lock not needed */
2982 * bioops callback - hold io_token
2985 softdep_checkwrite(struct buf *bp)
2987 /* nothing to do, mp lock not needed */
2994 * The dependency structures constructed above are most actively used when file
2995 * system blocks are written to disk. No constraints are placed on when a
2996 * block can be written, but unsatisfied update dependencies are made safe by
2997 * modifying (or replacing) the source memory for the duration of the disk
2998 * write. When the disk write completes, the memory block is again brought
3001 * In-core inode structure reclamation.
3003 * Because there are a finite number of "in-core" inode structures, they are
3004 * reused regularly. By transferring all inode-related dependencies to the
3005 * in-memory inode block and indexing them separately (via "inodedep"s), we
3006 * can allow "in-core" inode structures to be reused at any time and avoid
3007 * any increase in contention.
3009 * Called just before entering the device driver to initiate a new disk I/O.
3010 * The buffer must be locked, thus, no I/O completion operations can occur
3011 * while we are manipulating its associated dependencies.
3013 * bioops callback - hold io_token
3016 * bp: structure describing disk write to occur
3019 softdep_disk_io_initiation(struct buf *bp)
3021 struct worklist *wk;
3022 struct worklist marker;
3023 struct indirdep *indirdep;
3026 * We only care about write operations. There should never
3027 * be dependencies for reads.
3029 if (bp->b_cmd == BUF_CMD_READ)
3030 panic("softdep_disk_io_initiation: read");
3033 marker.wk_type = D_LAST + 1; /* Not a normal workitem */
3036 * Do any necessary pre-I/O processing.
3038 for (wk = LIST_FIRST(&bp->b_dep); wk; wk = markernext(&marker)) {
3039 LIST_INSERT_AFTER(wk, &marker, wk_list);
3041 switch (wk->wk_type) {
3043 initiate_write_filepage(WK_PAGEDEP(wk), bp);
3047 initiate_write_inodeblock(WK_INODEDEP(wk), bp);
3051 indirdep = WK_INDIRDEP(wk);
3052 if (indirdep->ir_state & GOINGAWAY)
3053 panic("disk_io_initiation: indirdep gone");
3055 * If there are no remaining dependencies, this
3056 * will be writing the real pointers, so the
3057 * dependency can be freed.
3059 if (LIST_FIRST(&indirdep->ir_deplisthd) == NULL) {
3060 indirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
3061 brelse(indirdep->ir_savebp);
3062 /* inline expand WORKLIST_REMOVE(wk); */
3063 wk->wk_state &= ~ONWORKLIST;
3064 LIST_REMOVE(wk, wk_list);
3065 WORKITEM_FREE(indirdep, D_INDIRDEP);
3069 * Replace up-to-date version with safe version.
3071 indirdep->ir_saveddata = kmalloc(bp->b_bcount,
3075 indirdep->ir_state &= ~ATTACHED;
3076 indirdep->ir_state |= UNDONE;
3077 bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
3078 bcopy(indirdep->ir_savebp->b_data, bp->b_data,
3090 panic("handle_disk_io_initiation: Unexpected type %s",
3091 TYPENAME(wk->wk_type));
3099 * Called from within the procedure above to deal with unsatisfied
3100 * allocation dependencies in a directory. The buffer must be locked,
3101 * thus, no I/O completion operations can occur while we are
3102 * manipulating its associated dependencies.
3105 initiate_write_filepage(struct pagedep *pagedep, struct buf *bp)
3111 if (pagedep->pd_state & IOSTARTED) {
3113 * This can only happen if there is a driver that does not
3114 * understand chaining. Here biodone will reissue the call
3115 * to strategy for the incomplete buffers.
3117 kprintf("initiate_write_filepage: already started\n");
3120 pagedep->pd_state |= IOSTARTED;
3122 for (i = 0; i < DAHASHSZ; i++) {
3123 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
3124 ep = (struct direct *)
3125 ((char *)bp->b_data + dap->da_offset);
3126 if (ep->d_ino != dap->da_newinum) {
3127 panic("%s: dir inum %d != new %"PRId64,
3128 "initiate_write_filepage",
3129 ep->d_ino, dap->da_newinum);
3131 if (dap->da_state & DIRCHG)
3132 ep->d_ino = dap->da_previous->dm_oldinum;
3135 dap->da_state &= ~ATTACHED;
3136 dap->da_state |= UNDONE;
3143 * Called from within the procedure above to deal with unsatisfied
3144 * allocation dependencies in an inodeblock. The buffer must be
3145 * locked, thus, no I/O completion operations can occur while we
3146 * are manipulating its associated dependencies.
3149 * bp: The inode block
3152 initiate_write_inodeblock(struct inodedep *inodedep, struct buf *bp)
3154 struct allocdirect *adp, *lastadp;
3155 struct ufs1_dinode *dp;
3156 struct ufs1_dinode *sip;
3158 ufs_lbn_t prevlbn = 0;
3161 if (inodedep->id_state & IOSTARTED)
3162 panic("initiate_write_inodeblock: already started");
3163 inodedep->id_state |= IOSTARTED;
3164 fs = inodedep->id_fs;
3165 dp = (struct ufs1_dinode *)bp->b_data +
3166 ino_to_fsbo(fs, inodedep->id_ino);
3168 * If the bitmap is not yet written, then the allocated
3169 * inode cannot be written to disk.
3171 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
3172 if (inodedep->id_savedino != NULL)
3173 panic("initiate_write_inodeblock: already doing I/O");
3174 sip = kmalloc(sizeof(struct ufs1_dinode), M_INODEDEP,
3176 inodedep->id_savedino = sip;
3177 *inodedep->id_savedino = *dp;
3178 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
3179 dp->di_gen = inodedep->id_savedino->di_gen;
3183 * If no dependencies, then there is nothing to roll back.
3185 inodedep->id_savedsize = dp->di_size;
3186 if (TAILQ_FIRST(&inodedep->id_inoupdt) == NULL)
3189 * Set the dependencies to busy.
3192 for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3193 adp = TAILQ_NEXT(adp, ad_next)) {
3195 if (deplist != 0 && prevlbn >= adp->ad_lbn) {
3196 panic("softdep_write_inodeblock: lbn order");
3198 prevlbn = adp->ad_lbn;
3199 if (adp->ad_lbn < NDADDR &&
3200 dp->di_db[adp->ad_lbn] != adp->ad_newblkno) {
3201 panic("%s: direct pointer #%ld mismatch %d != %d",
3202 "softdep_write_inodeblock", adp->ad_lbn,
3203 dp->di_db[adp->ad_lbn], adp->ad_newblkno);
3205 if (adp->ad_lbn >= NDADDR &&
3206 dp->di_ib[adp->ad_lbn - NDADDR] != adp->ad_newblkno) {
3207 panic("%s: indirect pointer #%ld mismatch %d != %d",
3208 "softdep_write_inodeblock", adp->ad_lbn - NDADDR,
3209 dp->di_ib[adp->ad_lbn - NDADDR], adp->ad_newblkno);
3211 deplist |= 1 << adp->ad_lbn;
3212 if ((adp->ad_state & ATTACHED) == 0) {
3213 panic("softdep_write_inodeblock: Unknown state 0x%x",
3216 #endif /* DIAGNOSTIC */
3217 adp->ad_state &= ~ATTACHED;
3218 adp->ad_state |= UNDONE;
3221 * The on-disk inode cannot claim to be any larger than the last
3222 * fragment that has been written. Otherwise, the on-disk inode
3223 * might have fragments that were not the last block in the file
3224 * which would corrupt the filesystem.
3226 for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3227 lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
3228 if (adp->ad_lbn >= NDADDR)
3230 dp->di_db[adp->ad_lbn] = adp->ad_oldblkno;
3231 /* keep going until hitting a rollback to a frag */
3232 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
3234 dp->di_size = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
3235 for (i = adp->ad_lbn + 1; i < NDADDR; i++) {
3237 if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0) {
3238 panic("softdep_write_inodeblock: lost dep1");
3240 #endif /* DIAGNOSTIC */
3243 for (i = 0; i < NIADDR; i++) {
3245 if (dp->di_ib[i] != 0 &&
3246 (deplist & ((1 << NDADDR) << i)) == 0) {
3247 panic("softdep_write_inodeblock: lost dep2");
3249 #endif /* DIAGNOSTIC */
3256 * If we have zero'ed out the last allocated block of the file,
3257 * roll back the size to the last currently allocated block.
3258 * We know that this last allocated block is a full-sized as
3259 * we already checked for fragments in the loop above.
3261 if (lastadp != NULL &&
3262 dp->di_size <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
3263 for (i = lastadp->ad_lbn; i >= 0; i--)
3264 if (dp->di_db[i] != 0)
3266 dp->di_size = (i + 1) * fs->fs_bsize;
3269 * The only dependencies are for indirect blocks.
3271 * The file size for indirect block additions is not guaranteed.
3272 * Such a guarantee would be non-trivial to achieve. The conventional
3273 * synchronous write implementation also does not make this guarantee.
3274 * Fsck should catch and fix discrepancies. Arguably, the file size
3275 * can be over-estimated without destroying integrity when the file
3276 * moves into the indirect blocks (i.e., is large). If we want to
3277 * postpone fsck, we are stuck with this argument.
3279 for (; adp; adp = TAILQ_NEXT(adp, ad_next))
3280 dp->di_ib[adp->ad_lbn - NDADDR] = 0;
3285 * This routine is called during the completion interrupt
3286 * service routine for a disk write (from the procedure called
3287 * by the device driver to inform the filesystem caches of
3288 * a request completion). It should be called early in this
3289 * procedure, before the block is made available to other
3290 * processes or other routines are called.
3292 * bioops callback - hold io_token
3295 * bp: describes the completed disk write
3298 softdep_disk_write_complete(struct buf *bp)
3300 struct worklist *wk;
3301 struct workhead reattach;
3302 struct newblk *newblk;
3303 struct allocindir *aip;
3304 struct allocdirect *adp;
3305 struct indirdep *indirdep;
3306 struct inodedep *inodedep;
3307 struct bmsafemap *bmsafemap;
3311 LIST_INIT(&reattach);
3312 while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
3313 WORKLIST_REMOVE(wk);
3314 switch (wk->wk_type) {
3317 if (handle_written_filepage(WK_PAGEDEP(wk), bp))
3318 WORKLIST_INSERT(&reattach, wk);
3322 if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
3323 WORKLIST_INSERT(&reattach, wk);
3327 bmsafemap = WK_BMSAFEMAP(wk);
3328 while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkhd))) {
3329 newblk->nb_state |= DEPCOMPLETE;
3330 newblk->nb_bmsafemap = NULL;
3331 LIST_REMOVE(newblk, nb_deps);
3334 LIST_FIRST(&bmsafemap->sm_allocdirecthd))) {
3335 adp->ad_state |= DEPCOMPLETE;
3337 LIST_REMOVE(adp, ad_deps);
3338 handle_allocdirect_partdone(adp);
3341 LIST_FIRST(&bmsafemap->sm_allocindirhd))) {
3342 aip->ai_state |= DEPCOMPLETE;
3344 LIST_REMOVE(aip, ai_deps);
3345 handle_allocindir_partdone(aip);
3348 LIST_FIRST(&bmsafemap->sm_inodedephd)) != NULL) {
3349 inodedep->id_state |= DEPCOMPLETE;
3350 LIST_REMOVE(inodedep, id_deps);
3351 inodedep->id_buf = NULL;
3353 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
3357 handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
3361 adp = WK_ALLOCDIRECT(wk);
3362 adp->ad_state |= COMPLETE;
3363 handle_allocdirect_partdone(adp);
3367 aip = WK_ALLOCINDIR(wk);
3368 aip->ai_state |= COMPLETE;
3369 handle_allocindir_partdone(aip);
3373 indirdep = WK_INDIRDEP(wk);
3374 if (indirdep->ir_state & GOINGAWAY) {
3375 panic("disk_write_complete: indirdep gone");
3377 bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
3378 kfree(indirdep->ir_saveddata, M_INDIRDEP);
3379 indirdep->ir_saveddata = NULL;
3380 indirdep->ir_state &= ~UNDONE;
3381 indirdep->ir_state |= ATTACHED;
3382 while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
3383 handle_allocindir_partdone(aip);
3384 if (aip == LIST_FIRST(&indirdep->ir_donehd)) {
3385 panic("disk_write_complete: not gone");
3388 WORKLIST_INSERT(&reattach, wk);
3389 if ((bp->b_flags & B_DELWRI) == 0)
3390 stat_indir_blk_ptrs++;
3395 panic("handle_disk_write_complete: Unknown type %s",
3396 TYPENAME(wk->wk_type));
3401 * Reattach any requests that must be redone.
3403 while ((wk = LIST_FIRST(&reattach)) != NULL) {
3404 WORKLIST_REMOVE(wk);
3405 WORKLIST_INSERT_BP(bp, wk);
3412 * Called from within softdep_disk_write_complete above. Note that
3413 * this routine is always called from interrupt level with further
3414 * splbio interrupts blocked.
3417 * adp: the completed allocdirect
3420 handle_allocdirect_partdone(struct allocdirect *adp)
3422 struct allocdirect *listadp;
3423 struct inodedep *inodedep;
3426 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3428 if (adp->ad_buf != NULL)
3429 panic("handle_allocdirect_partdone: dangling dep");
3432 * The on-disk inode cannot claim to be any larger than the last
3433 * fragment that has been written. Otherwise, the on-disk inode
3434 * might have fragments that were not the last block in the file
3435 * which would corrupt the filesystem. Thus, we cannot free any
3436 * allocdirects after one whose ad_oldblkno claims a fragment as
3437 * these blocks must be rolled back to zero before writing the inode.
3438 * We check the currently active set of allocdirects in id_inoupdt.
3440 inodedep = adp->ad_inodedep;
3441 bsize = inodedep->id_fs->fs_bsize;
3442 TAILQ_FOREACH(listadp, &inodedep->id_inoupdt, ad_next) {
3443 /* found our block */
3446 /* continue if ad_oldlbn is not a fragment */
3447 if (listadp->ad_oldsize == 0 ||
3448 listadp->ad_oldsize == bsize)
3450 /* hit a fragment */
3454 * If we have reached the end of the current list without
3455 * finding the just finished dependency, then it must be
3456 * on the future dependency list. Future dependencies cannot
3457 * be freed until they are moved to the current list.
3459 if (listadp == NULL) {
3461 TAILQ_FOREACH(listadp, &inodedep->id_newinoupdt, ad_next)
3462 /* found our block */
3465 if (listadp == NULL)
3466 panic("handle_allocdirect_partdone: lost dep");
3471 * If we have found the just finished dependency, then free
3472 * it along with anything that follows it that is complete.
3474 for (; adp; adp = listadp) {
3475 listadp = TAILQ_NEXT(adp, ad_next);
3476 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3478 free_allocdirect(&inodedep->id_inoupdt, adp, 1);
3483 * Called from within softdep_disk_write_complete above. Note that
3484 * this routine is always called from interrupt level with further
3485 * splbio interrupts blocked.
3488 * aip: the completed allocindir
3491 handle_allocindir_partdone(struct allocindir *aip)
3493 struct indirdep *indirdep;
3495 if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
3497 if (aip->ai_buf != NULL)
3498 panic("handle_allocindir_partdone: dangling dependency");
3500 indirdep = aip->ai_indirdep;
3501 if (indirdep->ir_state & UNDONE) {
3502 LIST_REMOVE(aip, ai_next);
3503 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
3506 ((ufs_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
3508 LIST_REMOVE(aip, ai_next);
3509 if (aip->ai_freefrag != NULL)
3510 add_to_worklist(&aip->ai_freefrag->ff_list);
3511 WORKITEM_FREE(aip, D_ALLOCINDIR);
3515 * Called from within softdep_disk_write_complete above to restore
3516 * in-memory inode block contents to their most up-to-date state. Note
3517 * that this routine is always called from interrupt level with further
3518 * splbio interrupts blocked.
3521 * bp: buffer containing the inode block
3524 handle_written_inodeblock(struct inodedep *inodedep, struct buf *bp)
3526 struct worklist *wk, *filefree;
3527 struct allocdirect *adp, *nextadp;
3528 struct ufs1_dinode *dp;
3531 if ((inodedep->id_state & IOSTARTED) == 0)
3532 panic("handle_written_inodeblock: not started");
3534 inodedep->id_state &= ~IOSTARTED;
3535 dp = (struct ufs1_dinode *)bp->b_data +
3536 ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
3538 * If we had to rollback the inode allocation because of
3539 * bitmaps being incomplete, then simply restore it.
3540 * Keep the block dirty so that it will not be reclaimed until
3541 * all associated dependencies have been cleared and the
3542 * corresponding updates written to disk.
3544 if (inodedep->id_savedino != NULL) {
3545 *dp = *inodedep->id_savedino;
3546 kfree(inodedep->id_savedino, M_INODEDEP);
3547 inodedep->id_savedino = NULL;
3548 if ((bp->b_flags & B_DELWRI) == 0)
3549 stat_inode_bitmap++;
3553 inodedep->id_state |= COMPLETE;
3555 * Roll forward anything that had to be rolled back before
3556 * the inode could be updated.
3559 for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
3560 nextadp = TAILQ_NEXT(adp, ad_next);
3561 if (adp->ad_state & ATTACHED)
3562 panic("handle_written_inodeblock: new entry");
3564 if (adp->ad_lbn < NDADDR) {
3565 if (dp->di_db[adp->ad_lbn] != adp->ad_oldblkno) {
3566 panic("%s: %s #%ld mismatch %d != %d",
3567 "handle_written_inodeblock",
3568 "direct pointer", adp->ad_lbn,
3569 dp->di_db[adp->ad_lbn], adp->ad_oldblkno);
3571 dp->di_db[adp->ad_lbn] = adp->ad_newblkno;
3573 if (dp->di_ib[adp->ad_lbn - NDADDR] != 0) {
3574 panic("%s: %s #%ld allocated as %d",
3575 "handle_written_inodeblock",
3576 "indirect pointer", adp->ad_lbn - NDADDR,
3577 dp->di_ib[adp->ad_lbn - NDADDR]);
3579 dp->di_ib[adp->ad_lbn - NDADDR] = adp->ad_newblkno;
3581 adp->ad_state &= ~UNDONE;
3582 adp->ad_state |= ATTACHED;
3585 if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
3586 stat_direct_blk_ptrs++;
3588 * Reset the file size to its most up-to-date value.
3590 if (inodedep->id_savedsize == -1) {
3591 panic("handle_written_inodeblock: bad size");
3593 if (dp->di_size != inodedep->id_savedsize) {
3594 dp->di_size = inodedep->id_savedsize;
3597 inodedep->id_savedsize = -1;
3599 * If there were any rollbacks in the inode block, then it must be
3600 * marked dirty so that its will eventually get written back in
3606 * Process any allocdirects that completed during the update.
3608 if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
3609 handle_allocdirect_partdone(adp);
3611 * Process deallocations that were held pending until the
3612 * inode had been written to disk. Freeing of the inode
3613 * is delayed until after all blocks have been freed to
3614 * avoid creation of new <vfsid, inum, lbn> triples
3615 * before the old ones have been deleted.
3618 while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
3619 WORKLIST_REMOVE(wk);
3620 switch (wk->wk_type) {
3624 * We defer adding filefree to the worklist until
3625 * all other additions have been made to ensure
3626 * that it will be done after all the old blocks
3629 if (filefree != NULL) {
3630 panic("handle_written_inodeblock: filefree");
3636 handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
3640 diradd_inode_written(WK_DIRADD(wk), inodedep);
3644 wk->wk_state |= COMPLETE;
3645 if ((wk->wk_state & ALLCOMPLETE) != ALLCOMPLETE)
3647 /* -- fall through -- */
3650 add_to_worklist(wk);
3654 panic("handle_written_inodeblock: Unknown type %s",
3655 TYPENAME(wk->wk_type));
3659 if (filefree != NULL) {
3660 if (free_inodedep(inodedep) == 0) {
3661 panic("handle_written_inodeblock: live inodedep");
3663 add_to_worklist(filefree);
3668 * If no outstanding dependencies, free it.
3670 if (free_inodedep(inodedep) || TAILQ_FIRST(&inodedep->id_inoupdt) == NULL)
3672 return (hadchanges);
3676 * Process a diradd entry after its dependent inode has been written.
3677 * This routine must be called with splbio interrupts blocked.
3680 diradd_inode_written(struct diradd *dap, struct inodedep *inodedep)
3682 struct pagedep *pagedep;
3684 dap->da_state |= COMPLETE;
3685 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3686 if (dap->da_state & DIRCHG)
3687 pagedep = dap->da_previous->dm_pagedep;
3689 pagedep = dap->da_pagedep;
3690 LIST_REMOVE(dap, da_pdlist);
3691 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3693 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
3697 * Handle the completion of a mkdir dependency.
3700 handle_written_mkdir(struct mkdir *mkdir, int type)
3703 struct pagedep *pagedep;
3705 if (mkdir->md_state != type) {
3706 panic("handle_written_mkdir: bad type");
3708 dap = mkdir->md_diradd;
3709 dap->da_state &= ~type;
3710 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
3711 dap->da_state |= DEPCOMPLETE;
3712 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3713 if (dap->da_state & DIRCHG)
3714 pagedep = dap->da_previous->dm_pagedep;
3716 pagedep = dap->da_pagedep;
3717 LIST_REMOVE(dap, da_pdlist);
3718 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3720 LIST_REMOVE(mkdir, md_mkdirs);
3721 WORKITEM_FREE(mkdir, D_MKDIR);
3725 * Called from within softdep_disk_write_complete above.
3726 * A write operation was just completed. Removed inodes can
3727 * now be freed and associated block pointers may be committed.
3728 * Note that this routine is always called from interrupt level
3729 * with further splbio interrupts blocked.
3732 * bp: buffer containing the written page
3735 handle_written_filepage(struct pagedep *pagedep, struct buf *bp)
3737 struct dirrem *dirrem;
3738 struct diradd *dap, *nextdap;
3742 if ((pagedep->pd_state & IOSTARTED) == 0) {
3743 panic("handle_written_filepage: not started");
3745 pagedep->pd_state &= ~IOSTARTED;
3747 * Process any directory removals that have been committed.
3749 while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
3750 LIST_REMOVE(dirrem, dm_next);
3751 dirrem->dm_dirinum = pagedep->pd_ino;
3752 add_to_worklist(&dirrem->dm_list);
3755 * Free any directory additions that have been committed.
3757 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
3760 * Uncommitted directory entries must be restored.
3762 for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
3763 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
3765 nextdap = LIST_NEXT(dap, da_pdlist);
3766 if (dap->da_state & ATTACHED) {
3767 panic("handle_written_filepage: attached");
3769 ep = (struct direct *)
3770 ((char *)bp->b_data + dap->da_offset);
3771 ep->d_ino = dap->da_newinum;
3772 dap->da_state &= ~UNDONE;
3773 dap->da_state |= ATTACHED;
3776 * If the inode referenced by the directory has
3777 * been written out, then the dependency can be
3778 * moved to the pending list.
3780 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3781 LIST_REMOVE(dap, da_pdlist);
3782 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
3788 * If there were any rollbacks in the directory, then it must be
3789 * marked dirty so that its will eventually get written back in
3793 if ((bp->b_flags & B_DELWRI) == 0)
3798 * If no dependencies remain, the pagedep will be freed.
3799 * Otherwise it will remain to update the page before it
3800 * is written back to disk.
3802 if (LIST_FIRST(&pagedep->pd_pendinghd) == NULL) {
3803 for (i = 0; i < DAHASHSZ; i++)
3804 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) != NULL)
3806 if (i == DAHASHSZ) {
3807 LIST_REMOVE(pagedep, pd_hash);
3808 WORKITEM_FREE(pagedep, D_PAGEDEP);
3816 * Writing back in-core inode structures.
3818 * The filesystem only accesses an inode's contents when it occupies an
3819 * "in-core" inode structure. These "in-core" structures are separate from
3820 * the page frames used to cache inode blocks. Only the latter are
3821 * transferred to/from the disk. So, when the updated contents of the
3822 * "in-core" inode structure are copied to the corresponding in-memory inode
3823 * block, the dependencies are also transferred. The following procedure is
3824 * called when copying a dirty "in-core" inode to a cached inode block.
3828 * Called when an inode is loaded from disk. If the effective link count
3829 * differed from the actual link count when it was last flushed, then we
3830 * need to ensure that the correct effective link count is put back.
3833 * ip: the "in_core" copy of the inode
3836 softdep_load_inodeblock(struct inode *ip)
3838 struct inodedep *inodedep;
3841 * Check for alternate nlink count.
3843 ip->i_effnlink = ip->i_nlink;
3845 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3849 ip->i_effnlink -= inodedep->id_nlinkdelta;
3854 * This routine is called just before the "in-core" inode
3855 * information is to be copied to the in-memory inode block.
3856 * Recall that an inode block contains several inodes. If
3857 * the force flag is set, then the dependencies will be
3858 * cleared so that the update can always be made. Note that
3859 * the buffer is locked when this routine is called, so we
3860 * will never be in the middle of writing the inode block
3864 * ip: the "in_core" copy of the inode
3865 * bp: the buffer containing the inode block
3866 * waitfor: nonzero => update must be allowed
3869 softdep_update_inodeblock(struct inode *ip, struct buf *bp,
3872 struct inodedep *inodedep;
3873 struct worklist *wk;
3878 * If the effective link count is not equal to the actual link
3879 * count, then we must track the difference in an inodedep while
3880 * the inode is (potentially) tossed out of the cache. Otherwise,
3881 * if there is no existing inodedep, then there are no dependencies
3885 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3887 if (ip->i_effnlink != ip->i_nlink)
3888 panic("softdep_update_inodeblock: bad link count");
3891 if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink) {
3892 panic("softdep_update_inodeblock: bad delta");
3895 * Changes have been initiated. Anything depending on these
3896 * changes cannot occur until this inode has been written.
3898 inodedep->id_state &= ~COMPLETE;
3899 if ((inodedep->id_state & ONWORKLIST) == 0)
3900 WORKLIST_INSERT_BP(bp, &inodedep->id_list);
3902 * Any new dependencies associated with the incore inode must
3903 * now be moved to the list associated with the buffer holding
3904 * the in-memory copy of the inode. Once merged process any
3905 * allocdirects that are completed by the merger.
3907 merge_inode_lists(inodedep);
3908 if (TAILQ_FIRST(&inodedep->id_inoupdt) != NULL)
3909 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt));
3911 * Now that the inode has been pushed into the buffer, the
3912 * operations dependent on the inode being written to disk
3913 * can be moved to the id_bufwait so that they will be
3914 * processed when the buffer I/O completes.
3916 while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
3917 WORKLIST_REMOVE(wk);
3918 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
3921 * Newly allocated inodes cannot be written until the bitmap
3922 * that allocates them have been written (indicated by
3923 * DEPCOMPLETE being set in id_state). If we are doing a
3924 * forced sync (e.g., an fsync on a file), we force the bitmap
3925 * to be written so that the update can be done.
3932 if ((inodedep->id_state & DEPCOMPLETE) != 0) {
3936 gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
3938 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) != 0)
3943 ibp = inodedep->id_buf;
3945 if ((error = bwrite(ibp)) != 0)
3946 softdep_error("softdep_update_inodeblock: bwrite", error);
3950 * Merge the new inode dependency list (id_newinoupdt) into the old
3951 * inode dependency list (id_inoupdt). This routine must be called
3952 * with splbio interrupts blocked.
3955 merge_inode_lists(struct inodedep *inodedep)
3957 struct allocdirect *listadp, *newadp;
3959 newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3960 for (listadp = TAILQ_FIRST(&inodedep->id_inoupdt); listadp && newadp;) {
3961 if (listadp->ad_lbn < newadp->ad_lbn) {
3962 listadp = TAILQ_NEXT(listadp, ad_next);
3965 TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3966 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
3967 if (listadp->ad_lbn == newadp->ad_lbn) {
3968 allocdirect_merge(&inodedep->id_inoupdt, newadp,
3972 newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3974 while ((newadp = TAILQ_FIRST(&inodedep->id_newinoupdt)) != NULL) {
3975 TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3976 TAILQ_INSERT_TAIL(&inodedep->id_inoupdt, newadp, ad_next);
3981 * If we are doing an fsync, then we must ensure that any directory
3982 * entries for the inode have been written after the inode gets to disk.
3984 * bioops callback - hold io_token
3987 * vp: the "in_core" copy of the inode
3990 softdep_fsync(struct vnode *vp)
3992 struct inodedep *inodedep;
3993 struct pagedep *pagedep;
3994 struct worklist *wk;
4001 int error, flushparent;
4006 * Move check from original kernel code, possibly not needed any
4007 * more with the per-mount bioops.
4009 if ((vp->v_mount->mnt_flag & MNT_SOFTDEP) == 0)
4015 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0) {
4019 if (LIST_FIRST(&inodedep->id_inowait) != NULL ||
4020 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
4021 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
4022 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL) {
4023 panic("softdep_fsync: pending ops");
4025 for (error = 0, flushparent = 0; ; ) {
4026 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
4028 if (wk->wk_type != D_DIRADD) {
4029 panic("softdep_fsync: Unexpected type %s",
4030 TYPENAME(wk->wk_type));
4032 dap = WK_DIRADD(wk);
4034 * Flush our parent if this directory entry
4035 * has a MKDIR_PARENT dependency.
4037 if (dap->da_state & DIRCHG)
4038 pagedep = dap->da_previous->dm_pagedep;
4040 pagedep = dap->da_pagedep;
4041 mnt = pagedep->pd_mnt;
4042 parentino = pagedep->pd_ino;
4043 lbn = pagedep->pd_lbn;
4044 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE) {
4045 panic("softdep_fsync: dirty");
4047 flushparent = dap->da_state & MKDIR_PARENT;
4049 * If we are being fsync'ed as part of vgone'ing this vnode,
4050 * then we will not be able to release and recover the
4051 * vnode below, so we just have to give up on writing its
4052 * directory entry out. It will eventually be written, just
4053 * not now, but then the user was not asking to have it
4054 * written, so we are not breaking any promises.
4056 if (vp->v_flag & VRECLAIMED)
4059 * We prevent deadlock by always fetching inodes from the
4060 * root, moving down the directory tree. Thus, when fetching
4061 * our parent directory, we must unlock ourselves before
4062 * requesting the lock on our parent. See the comment in
4063 * ufs_lookup for details on possible races.
4067 error = VFS_VGET(mnt, NULL, parentino, &pvp);
4068 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4073 if ((error = ffs_update(pvp, 1)) != 0) {
4079 * Flush directory page containing the inode's name.
4081 error = bread(pvp, lblktodoff(fs, lbn), blksize(fs, VTOI(pvp), lbn), &bp);
4089 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0)
4097 * Flush all the dirty bitmaps associated with the block device
4098 * before flushing the rest of the dirty blocks so as to reduce
4099 * the number of dependencies that will have to be rolled back.
4101 static int softdep_fsync_mountdev_bp(struct buf *bp, void *data);
4104 softdep_fsync_mountdev(struct vnode *vp)
4106 if (!vn_isdisk(vp, NULL))
4107 panic("softdep_fsync_mountdev: vnode not a disk");
4109 lwkt_gettoken(&vp->v_token);
4110 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
4111 softdep_fsync_mountdev_bp, vp);
4112 lwkt_reltoken(&vp->v_token);
4113 drain_output(vp, 1);
4118 softdep_fsync_mountdev_bp(struct buf *bp, void *data)
4120 struct worklist *wk;
4121 struct vnode *vp = data;
4124 * If it is already scheduled, skip to the next buffer.
4126 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT))
4128 if (bp->b_vp != vp || (bp->b_flags & B_DELWRI) == 0) {
4130 kprintf("softdep_fsync_mountdev_bp: warning, buffer %p ripped out from under vnode %p\n", bp, vp);
4134 * We are only interested in bitmaps with outstanding
4137 if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
4138 wk->wk_type != D_BMSAFEMAP) {
4150 * This routine is called when we are trying to synchronously flush a
4151 * file. This routine must eliminate any filesystem metadata dependencies
4152 * so that the syncing routine can succeed by pushing the dirty blocks
4153 * associated with the file. If any I/O errors occur, they are returned.
4155 struct softdep_sync_metadata_info {
4160 static int softdep_sync_metadata_bp(struct buf *bp, void *data);
4163 softdep_sync_metadata(struct vnode *vp, struct thread *td)
4165 struct softdep_sync_metadata_info info;
4169 * Check whether this vnode is involved in a filesystem
4170 * that is doing soft dependency processing.
4172 if (!vn_isdisk(vp, NULL)) {
4173 if (!DOINGSOFTDEP(vp))
4176 if (vp->v_rdev->si_mountpoint == NULL ||
4177 (vp->v_rdev->si_mountpoint->mnt_flag & MNT_SOFTDEP) == 0)
4180 * Ensure that any direct block dependencies have been cleared.
4183 if ((error = flush_inodedep_deps(VTOI(vp)->i_fs, VTOI(vp)->i_number))) {
4188 * For most files, the only metadata dependencies are the
4189 * cylinder group maps that allocate their inode or blocks.
4190 * The block allocation dependencies can be found by traversing
4191 * the dependency lists for any buffers that remain on their
4192 * dirty buffer list. The inode allocation dependency will
4193 * be resolved when the inode is updated with MNT_WAIT.
4194 * This work is done in two passes. The first pass grabs most
4195 * of the buffers and begins asynchronously writing them. The
4196 * only way to wait for these asynchronous writes is to sleep
4197 * on the filesystem vnode which may stay busy for a long time
4198 * if the filesystem is active. So, instead, we make a second
4199 * pass over the dependencies blocking on each write. In the
4200 * usual case we will be blocking against a write that we
4201 * initiated, so when it is done the dependency will have been
4202 * resolved. Thus the second pass is expected to end quickly.
4204 waitfor = MNT_NOWAIT;
4207 * We must wait for any I/O in progress to finish so that
4208 * all potential buffers on the dirty list will be visible.
4210 drain_output(vp, 1);
4213 info.waitfor = waitfor;
4214 lwkt_gettoken(&vp->v_token);
4215 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
4216 softdep_sync_metadata_bp, &info);
4217 lwkt_reltoken(&vp->v_token);
4220 return(-error); /* error code */
4224 * The brief unlock is to allow any pent up dependency
4225 * processing to be done. Then proceed with the second pass.
4227 if (waitfor & MNT_NOWAIT) {
4235 * If we have managed to get rid of all the dirty buffers,
4236 * then we are done. For certain directories and block
4237 * devices, we may need to do further work.
4239 * We must wait for any I/O in progress to finish so that
4240 * all potential buffers on the dirty list will be visible.
4242 drain_output(vp, 1);
4243 if (RB_EMPTY(&vp->v_rbdirty_tree)) {
4250 * If we are trying to sync a block device, some of its buffers may
4251 * contain metadata that cannot be written until the contents of some
4252 * partially written files have been written to disk. The only easy
4253 * way to accomplish this is to sync the entire filesystem (luckily
4254 * this happens rarely).
4256 if (vn_isdisk(vp, NULL) &&
4258 vp->v_rdev->si_mountpoint && !vn_islocked(vp) &&
4259 (error = VFS_SYNC(vp->v_rdev->si_mountpoint, MNT_WAIT)) != 0)
4265 softdep_sync_metadata_bp(struct buf *bp, void *data)
4267 struct softdep_sync_metadata_info *info = data;
4268 struct pagedep *pagedep;
4269 struct allocdirect *adp;
4270 struct allocindir *aip;
4271 struct worklist *wk;
4276 if (getdirtybuf(&bp, MNT_WAIT) == 0) {
4277 kprintf("softdep_sync_metadata_bp(1): caught buf %p going away\n", bp);
4280 if (bp->b_vp != info->vp || (bp->b_flags & B_DELWRI) == 0) {
4281 kprintf("softdep_sync_metadata_bp(2): caught buf %p going away vp %p\n", bp, info->vp);
4287 * As we hold the buffer locked, none of its dependencies
4290 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4291 switch (wk->wk_type) {
4294 adp = WK_ALLOCDIRECT(wk);
4295 if (adp->ad_state & DEPCOMPLETE)
4298 if (getdirtybuf(&nbp, info->waitfor) == 0)
4301 if (info->waitfor & MNT_NOWAIT) {
4303 } else if ((error = bwrite(nbp)) != 0) {
4312 aip = WK_ALLOCINDIR(wk);
4313 if (aip->ai_state & DEPCOMPLETE)
4316 if (getdirtybuf(&nbp, info->waitfor) == 0)
4319 if (info->waitfor & MNT_NOWAIT) {
4321 } else if ((error = bwrite(nbp)) != 0) {
4332 LIST_FOREACH(aip, &WK_INDIRDEP(wk)->ir_deplisthd, ai_next) {
4333 if (aip->ai_state & DEPCOMPLETE)
4336 if (getdirtybuf(&nbp, MNT_WAIT) == 0)
4339 if ((error = bwrite(nbp)) != 0) {
4350 if ((error = flush_inodedep_deps(WK_INODEDEP(wk)->id_fs,
4351 WK_INODEDEP(wk)->id_ino)) != 0) {
4361 * We are trying to sync a directory that may
4362 * have dependencies on both its own metadata
4363 * and/or dependencies on the inodes of any
4364 * recently allocated files. We walk its diradd
4365 * lists pushing out the associated inode.
4367 pagedep = WK_PAGEDEP(wk);
4368 for (i = 0; i < DAHASHSZ; i++) {
4369 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL)
4372 flush_pagedep_deps(info->vp,
4374 &pagedep->pd_diraddhd[i]))) {
4385 * This case should never happen if the vnode has
4386 * been properly sync'ed. However, if this function
4387 * is used at a place where the vnode has not yet
4388 * been sync'ed, this dependency can show up. So,
4389 * rather than panic, just flush it.
4391 nbp = WK_MKDIR(wk)->md_buf;
4392 if (getdirtybuf(&nbp, info->waitfor) == 0)
4395 if (info->waitfor & MNT_NOWAIT) {
4397 } else if ((error = bwrite(nbp)) != 0) {
4407 * This case should never happen if the vnode has
4408 * been properly sync'ed. However, if this function
4409 * is used at a place where the vnode has not yet
4410 * been sync'ed, this dependency can show up. So,
4411 * rather than panic, just flush it.
4413 * nbp can wind up == bp if a device node for the
4414 * same filesystem is being fsynced at the same time,
4415 * leading to a panic if we don't catch the case.
4417 nbp = WK_BMSAFEMAP(wk)->sm_buf;
4420 if (getdirtybuf(&nbp, info->waitfor) == 0)
4423 if (info->waitfor & MNT_NOWAIT) {
4425 } else if ((error = bwrite(nbp)) != 0) {
4434 panic("softdep_sync_metadata: Unknown type %s",
4435 TYPENAME(wk->wk_type));
4446 * Flush the dependencies associated with an inodedep.
4447 * Called with splbio blocked.
4450 flush_inodedep_deps(struct fs *fs, ino_t ino)
4452 struct inodedep *inodedep;
4453 struct allocdirect *adp;
4458 * This work is done in two passes. The first pass grabs most
4459 * of the buffers and begins asynchronously writing them. The
4460 * only way to wait for these asynchronous writes is to sleep
4461 * on the filesystem vnode which may stay busy for a long time
4462 * if the filesystem is active. So, instead, we make a second
4463 * pass over the dependencies blocking on each write. In the
4464 * usual case we will be blocking against a write that we
4465 * initiated, so when it is done the dependency will have been
4466 * resolved. Thus the second pass is expected to end quickly.
4467 * We give a brief window at the top of the loop to allow
4468 * any pending I/O to complete.
4470 for (waitfor = MNT_NOWAIT; ; ) {
4473 if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4475 TAILQ_FOREACH(adp, &inodedep->id_inoupdt, ad_next) {
4476 if (adp->ad_state & DEPCOMPLETE)
4479 if (getdirtybuf(&bp, waitfor) == 0) {
4480 if (waitfor & MNT_NOWAIT)
4485 if (waitfor & MNT_NOWAIT) {
4487 } else if ((error = bwrite(bp)) != 0) {
4496 TAILQ_FOREACH(adp, &inodedep->id_newinoupdt, ad_next) {
4497 if (adp->ad_state & DEPCOMPLETE)
4500 if (getdirtybuf(&bp, waitfor) == 0) {
4501 if (waitfor & MNT_NOWAIT)
4506 if (waitfor & MNT_NOWAIT) {
4508 } else if ((error = bwrite(bp)) != 0) {
4518 * If pass2, we are done, otherwise do pass 2.
4520 if (waitfor == MNT_WAIT)
4525 * Try freeing inodedep in case all dependencies have been removed.
4527 if (inodedep_lookup(fs, ino, 0, &inodedep) != 0)
4528 (void) free_inodedep(inodedep);
4533 * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
4534 * Called with splbio blocked.
4537 flush_pagedep_deps(struct vnode *pvp, struct mount *mp,
4538 struct diraddhd *diraddhdp)
4540 struct inodedep *inodedep;
4541 struct ufsmount *ump;
4543 struct worklist *wk;
4545 int gotit, error = 0;
4550 while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
4552 * Flush ourselves if this directory entry
4553 * has a MKDIR_PARENT dependency.
4555 if (dap->da_state & MKDIR_PARENT) {
4557 if ((error = ffs_update(pvp, 1)) != 0)
4561 * If that cleared dependencies, go on to next.
4563 if (dap != LIST_FIRST(diraddhdp))
4565 if (dap->da_state & MKDIR_PARENT) {
4566 panic("flush_pagedep_deps: MKDIR_PARENT");
4570 * A newly allocated directory must have its "." and
4571 * ".." entries written out before its name can be
4572 * committed in its parent. We do not want or need
4573 * the full semantics of a synchronous VOP_FSYNC as
4574 * that may end up here again, once for each directory
4575 * level in the filesystem. Instead, we push the blocks
4576 * and wait for them to clear. We have to fsync twice
4577 * because the first call may choose to defer blocks
4578 * that still have dependencies, but deferral will
4579 * happen at most once.
4581 inum = dap->da_newinum;
4582 if (dap->da_state & MKDIR_BODY) {
4584 if ((error = VFS_VGET(mp, NULL, inum, &vp)) != 0)
4586 if ((error=VOP_FSYNC(vp, MNT_NOWAIT, 0)) ||
4587 (error=VOP_FSYNC(vp, MNT_NOWAIT, 0))) {
4591 drain_output(vp, 0);
4593 * If first block is still dirty with a D_MKDIR
4594 * dependency then it needs to be written now.
4598 bp = findblk(vp, 0, FINDBLK_TEST);
4601 goto mkdir_body_continue;
4603 LIST_FOREACH(wk, &bp->b_dep, wk_list)
4604 if (wk->wk_type == D_MKDIR) {
4605 gotit = getdirtybuf(&bp, MNT_WAIT);
4607 if (gotit && (error = bwrite(bp)) != 0)
4608 goto mkdir_body_continue;
4613 mkdir_body_continue:
4615 /* Flushing of first block failed. */
4620 * If that cleared dependencies, go on to next.
4622 if (dap != LIST_FIRST(diraddhdp))
4624 if (dap->da_state & MKDIR_BODY) {
4625 panic("flush_pagedep_deps: %p MKDIR_BODY", dap);
4629 * Flush the inode on which the directory entry depends.
4630 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
4631 * the only remaining dependency is that the updated inode
4632 * count must get pushed to disk. The inode has already
4633 * been pushed into its inode buffer (via VOP_UPDATE) at
4634 * the time of the reference count change. So we need only
4635 * locate that buffer, ensure that there will be no rollback
4636 * caused by a bitmap dependency, then write the inode buffer.
4639 if (inodedep_lookup(ump->um_fs, inum, 0, &inodedep) == 0) {
4640 panic("flush_pagedep_deps: lost inode");
4643 * If the inode still has bitmap dependencies,
4644 * push them to disk.
4646 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4647 gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
4651 if (gotit && (error = bwrite(inodedep->id_buf)) != 0)
4654 if (dap != LIST_FIRST(diraddhdp))
4658 * If the inode is still sitting in a buffer waiting
4659 * to be written, push it to disk.
4662 if ((error = bread(ump->um_devvp,
4663 fsbtodoff(ump->um_fs, ino_to_fsba(ump->um_fs, inum)),
4664 (int)ump->um_fs->fs_bsize, &bp)) != 0)
4666 if ((error = bwrite(bp)) != 0)
4670 * If we have failed to get rid of all the dependencies
4671 * then something is seriously wrong.
4673 if (dap == LIST_FIRST(diraddhdp)) {
4674 panic("flush_pagedep_deps: flush failed");
4683 * A large burst of file addition or deletion activity can drive the
4684 * memory load excessively high. First attempt to slow things down
4685 * using the techniques below. If that fails, this routine requests
4686 * the offending operations to fall back to running synchronously
4687 * until the memory load returns to a reasonable level.
4690 softdep_slowdown(struct vnode *vp)
4692 int max_softdeps_hard;
4694 max_softdeps_hard = max_softdeps * 11 / 10;
4695 if (num_dirrem < max_softdeps_hard / 2 &&
4696 num_inodedep < max_softdeps_hard)
4698 stat_sync_limit_hit += 1;
4703 * If memory utilization has gotten too high, deliberately slow things
4704 * down and speed up the I/O processing.
4707 request_cleanup(int resource)
4709 struct thread *td = curthread; /* XXX */
4711 KKASSERT(lock_held(&lk) > 0);
4714 * We never hold up the filesystem syncer process.
4716 if (td == filesys_syncer)
4719 * First check to see if the work list has gotten backlogged.
4720 * If it has, co-opt this process to help clean up two entries.
4721 * Because this process may hold inodes locked, we cannot
4722 * handle any remove requests that might block on a locked
4723 * inode as that could lead to deadlock.
4725 if (num_on_worklist > max_softdeps / 10) {
4726 process_worklist_item(NULL, LK_NOWAIT);
4727 process_worklist_item(NULL, LK_NOWAIT);
4728 stat_worklist_push += 2;
4733 * If we are resource constrained on inode dependencies, try
4734 * flushing some dirty inodes. Otherwise, we are constrained
4735 * by file deletions, so try accelerating flushes of directories
4736 * with removal dependencies. We would like to do the cleanup
4737 * here, but we probably hold an inode locked at this point and
4738 * that might deadlock against one that we try to clean. So,
4739 * the best that we can do is request the syncer daemon to do
4740 * the cleanup for us.
4745 stat_ino_limit_push += 1;
4746 req_clear_inodedeps += 1;
4747 stat_countp = &stat_ino_limit_hit;
4751 stat_blk_limit_push += 1;
4752 req_clear_remove += 1;
4753 stat_countp = &stat_blk_limit_hit;
4757 panic("request_cleanup: unknown type");
4760 * Hopefully the syncer daemon will catch up and awaken us.
4761 * We wait at most tickdelay before proceeding in any case.
4763 lksleep(&proc_waiting, &lk, 0, "softupdate",
4764 tickdelay > 2 ? tickdelay : 2);
4769 * Flush out a directory with at least one removal dependency in an effort to
4770 * reduce the number of dirrem, freefile, and freeblks dependency structures.
4773 clear_remove(struct thread *td)
4775 struct pagedep_hashhead *pagedephd;
4776 struct pagedep *pagedep;
4777 static int next = 0;
4784 for (cnt = 0; cnt < pagedep_hash; cnt++) {
4785 pagedephd = &pagedep_hashtbl[next++];
4786 if (next >= pagedep_hash)
4788 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
4789 if (LIST_FIRST(&pagedep->pd_dirremhd) == NULL)
4791 mp = pagedep->pd_mnt;
4792 ino = pagedep->pd_ino;
4794 if ((error = VFS_VGET(mp, NULL, ino, &vp)) != 0) {
4795 softdep_error("clear_remove: vget", error);
4798 if ((error = VOP_FSYNC(vp, MNT_NOWAIT, 0)))
4799 softdep_error("clear_remove: fsync", error);
4800 drain_output(vp, 0);
4809 * Clear out a block of dirty inodes in an effort to reduce
4810 * the number of inodedep dependency structures.
4812 struct clear_inodedeps_info {
4818 clear_inodedeps_mountlist_callback(struct mount *mp, void *data)
4820 struct clear_inodedeps_info *info = data;
4822 if ((mp->mnt_flag & MNT_SOFTDEP) && info->fs == VFSTOUFS(mp)->um_fs) {
4830 clear_inodedeps(struct thread *td)
4832 struct clear_inodedeps_info info;
4833 struct inodedep_hashhead *inodedephd;
4834 struct inodedep *inodedep;
4835 static int next = 0;
4839 ino_t firstino, lastino, ino;
4843 * Pick a random inode dependency to be cleared.
4844 * We will then gather up all the inodes in its block
4845 * that have dependencies and flush them out.
4847 inodedep = NULL; /* avoid gcc warnings */
4848 for (cnt = 0; cnt < inodedep_hash; cnt++) {
4849 inodedephd = &inodedep_hashtbl[next++];
4850 if (next >= inodedep_hash)
4852 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
4855 if (inodedep == NULL) {
4860 * Ugly code to find mount point given pointer to superblock.
4862 fs = inodedep->id_fs;
4865 mountlist_scan(clear_inodedeps_mountlist_callback,
4866 &info, MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
4868 * Find the last inode in the block with dependencies.
4870 firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
4871 for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
4872 if (inodedep_lookup(fs, lastino, 0, &inodedep) != 0)
4875 * Asynchronously push all but the last inode with dependencies.
4876 * Synchronously push the last inode with dependencies to ensure
4877 * that the inode block gets written to free up the inodedeps.
4879 for (ino = firstino; ino <= lastino; ino++) {
4880 if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4883 if ((error = VFS_VGET(info.mp, NULL, ino, &vp)) != 0) {
4884 softdep_error("clear_inodedeps: vget", error);
4887 if (ino == lastino) {
4888 if ((error = VOP_FSYNC(vp, MNT_WAIT, 0)))
4889 softdep_error("clear_inodedeps: fsync1", error);
4891 if ((error = VOP_FSYNC(vp, MNT_NOWAIT, 0)))
4892 softdep_error("clear_inodedeps: fsync2", error);
4893 drain_output(vp, 0);
4902 * Function to determine if the buffer has outstanding dependencies
4903 * that will cause a roll-back if the buffer is written. If wantcount
4904 * is set, return number of dependencies, otherwise just yes or no.
4906 * bioops callback - hold io_token
4909 softdep_count_dependencies(struct buf *bp, int wantcount)
4911 struct worklist *wk;
4912 struct inodedep *inodedep;
4913 struct indirdep *indirdep;
4914 struct allocindir *aip;
4915 struct pagedep *pagedep;
4922 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4923 switch (wk->wk_type) {
4926 inodedep = WK_INODEDEP(wk);
4927 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4928 /* bitmap allocation dependency */
4933 if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
4934 /* direct block pointer dependency */
4942 indirdep = WK_INDIRDEP(wk);
4944 LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
4945 /* indirect block pointer dependency */
4953 pagedep = WK_PAGEDEP(wk);
4954 for (i = 0; i < DAHASHSZ; i++) {
4956 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
4957 /* directory entry dependency */
4969 /* never a dependency on these blocks */
4973 panic("softdep_check_for_rollback: Unexpected type %s",
4974 TYPENAME(wk->wk_type));
4985 * Acquire exclusive access to a buffer. Requires softdep lock
4986 * to be held on entry. If waitfor is MNT_WAIT, may release/reacquire
4989 * Returns 1 if the buffer was locked, 0 if it was not locked or
4990 * if we had to block.
4992 * NOTE! In order to return 1 we must acquire the buffer lock prior
4993 * to any release of &lk. Once we release &lk it's all over.
4994 * We may still have to block on the (type-stable) bp in that
4995 * case, but we must then unlock it and return 0.
4998 getdirtybuf(struct buf **bpp, int waitfor)
5004 * If the contents of *bpp is NULL the caller presumably lost a race.
5011 * Try to obtain the buffer lock without deadlocking on &lk.
5013 KKASSERT(lock_held(&lk) > 0);
5014 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT);
5017 * If the buffer is no longer dirty the OS already wrote it
5018 * out, return failure.
5020 if ((bp->b_flags & B_DELWRI) == 0) {
5026 * Finish nominal buffer locking sequence return success.
5028 * Since we are not using a normal getblk(), and UFS
5029 * isn't KVABIO aware, we must make sure that the bp
5030 * is synchronized before returning it.
5040 * If we are not being asked to wait, return 0 immediately.
5042 if (waitfor != MNT_WAIT)
5046 * Once we release the softdep lock we can never return success,
5047 * but we still have to block on the type-stable buf for the caller
5048 * to be able to retry without livelocking the system.
5050 * The caller will normally retry in this case.
5053 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL);
5061 * Wait for pending output on a vnode to complete.
5062 * Must be called with vnode locked.
5065 drain_output(struct vnode *vp, int islocked)
5070 while (bio_track_active(&vp->v_track_write)) {
5072 bio_track_wait(&vp->v_track_write, 0, 0);
5080 * Called whenever a buffer that is being invalidated or reallocated
5081 * contains dependencies. This should only happen if an I/O error has
5082 * occurred. The routine is called with the buffer locked.
5084 * bioops callback - hold io_token
5087 softdep_deallocate_dependencies(struct buf *bp)
5089 /* nothing to do, mp lock not needed */
5090 if ((bp->b_flags & B_ERROR) == 0)
5091 panic("softdep_deallocate_dependencies: dangling deps");
5092 softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntfromname, bp->b_error);
5093 panic("softdep_deallocate_dependencies: unrecovered I/O error");
5097 * Function to handle asynchronous write errors in the filesystem.
5100 softdep_error(char *func, int error)
5102 /* XXX should do something better! */
5103 kprintf("%s: got error %d while accessing filesystem\n", func, error);