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);
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);
533 starttime = time_second;
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 if (starttime != time_second && matchmnt == NULL) {
579 if (matchmnt == NULL) {
580 --softdep_worklist_busy;
581 if (softdep_worklist_req && softdep_worklist_busy == 0)
582 wakeup(&softdep_worklist_req);
590 * Process one item on the worklist.
593 process_worklist_item(struct mount *matchmnt, int flags)
595 struct ufsmount *ump;
597 struct dirrem *dirrem;
602 KKASSERT(lock_held(&lk) > 0);
605 if (matchmnt != NULL)
606 matchfs = VFSTOUFS(matchmnt)->um_fs;
609 * Normally we just process each item on the worklist in order.
610 * However, if we are in a situation where we cannot lock any
611 * inodes, we have to skip over any dirrem requests whose
612 * vnodes are resident and locked.
614 LIST_FOREACH(wk, &softdep_workitem_pending, wk_list) {
615 if ((flags & LK_NOWAIT) == 0 || wk->wk_type != D_DIRREM)
617 dirrem = WK_DIRREM(wk);
618 ump = VFSTOUFS(dirrem->dm_mnt);
619 lwkt_gettoken(&ump->um_mountp->mnt_token);
620 vp = ufs_ihashlookup(ump, ump->um_dev, dirrem->dm_oldinum);
621 lwkt_reltoken(&ump->um_mountp->mnt_token);
622 if (vp == NULL || !vn_islocked(vp))
629 num_on_worklist -= 1;
631 switch (wk->wk_type) {
633 /* removal of a directory entry */
634 if (WK_DIRREM(wk)->dm_mnt == matchmnt)
636 handle_workitem_remove(WK_DIRREM(wk));
640 /* releasing blocks and/or fragments from a file */
641 if (WK_FREEBLKS(wk)->fb_fs == matchfs)
643 handle_workitem_freeblocks(WK_FREEBLKS(wk));
647 /* releasing a fragment when replaced as a file grows */
648 if (WK_FREEFRAG(wk)->ff_fs == matchfs)
650 handle_workitem_freefrag(WK_FREEFRAG(wk));
654 /* releasing an inode when its link count drops to 0 */
655 if (WK_FREEFILE(wk)->fx_fs == matchfs)
657 handle_workitem_freefile(WK_FREEFILE(wk));
661 panic("%s_process_worklist: Unknown type %s",
662 "softdep", TYPENAME(wk->wk_type));
670 * Move dependencies from one buffer to another.
672 * bioops callback - hold io_token
675 softdep_move_dependencies(struct buf *oldbp, struct buf *newbp)
677 struct worklist *wk, *wktail;
679 if (LIST_FIRST(&newbp->b_dep) != NULL)
680 panic("softdep_move_dependencies: need merge code");
683 while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
684 LIST_REMOVE(wk, wk_list);
686 LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
688 LIST_INSERT_AFTER(wktail, wk, wk_list);
690 newbp->b_ops = &softdep_bioops;
696 * Purge the work list of all items associated with a particular mount point.
699 softdep_flushfiles(struct mount *oldmnt, int flags)
705 * Await our turn to clear out the queue, then serialize access.
708 while (softdep_worklist_busy != 0) {
709 softdep_worklist_req += 1;
710 lksleep(&softdep_worklist_req, &lk, 0, "softflush", 0);
711 softdep_worklist_req -= 1;
713 softdep_worklist_busy = -1;
716 if ((error = ffs_flushfiles(oldmnt, flags)) != 0) {
717 softdep_worklist_busy = 0;
718 if (softdep_worklist_req)
719 wakeup(&softdep_worklist_req);
723 * Alternately flush the block device associated with the mount
724 * point and process any dependencies that the flushing
725 * creates. In theory, this loop can happen at most twice,
726 * but we give it a few extra just to be sure.
728 devvp = VFSTOUFS(oldmnt)->um_devvp;
729 for (loopcnt = 10; loopcnt > 0; ) {
730 if (softdep_process_worklist(oldmnt) == 0) {
733 * Do another flush in case any vnodes were brought in
734 * as part of the cleanup operations.
736 if ((error = ffs_flushfiles(oldmnt, flags)) != 0)
739 * If we still found nothing to do, we are really done.
741 if (softdep_process_worklist(oldmnt) == 0)
744 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
745 error = VOP_FSYNC(devvp, MNT_WAIT, 0);
751 softdep_worklist_busy = 0;
752 if (softdep_worklist_req)
753 wakeup(&softdep_worklist_req);
757 * If we are unmounting then it is an error to fail. If we
758 * are simply trying to downgrade to read-only, then filesystem
759 * activity can keep us busy forever, so we just fail with EBUSY.
762 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
763 panic("softdep_flushfiles: looping");
772 * There are three types of structures that can be looked up:
773 * 1) pagedep structures identified by mount point, inode number,
775 * 2) inodedep structures identified by mount point and inode number.
776 * 3) newblk structures identified by mount point and
777 * physical block number.
779 * The "pagedep" and "inodedep" dependency structures are hashed
780 * separately from the file blocks and inodes to which they correspond.
781 * This separation helps when the in-memory copy of an inode or
782 * file block must be replaced. It also obviates the need to access
783 * an inode or file page when simply updating (or de-allocating)
784 * dependency structures. Lookup of newblk structures is needed to
785 * find newly allocated blocks when trying to associate them with
786 * their allocdirect or allocindir structure.
788 * The lookup routines optionally create and hash a new instance when
789 * an existing entry is not found.
791 #define DEPALLOC 0x0001 /* allocate structure if lookup fails */
792 #define NODELAY 0x0002 /* cannot do background work */
795 * Structures and routines associated with pagedep caching.
797 LIST_HEAD(pagedep_hashhead, pagedep) *pagedep_hashtbl;
798 u_long pagedep_hash; /* size of hash table - 1 */
799 #define PAGEDEP_HASH(mp, inum, lbn) \
800 (&pagedep_hashtbl[((((register_t)(mp)) >> 13) + (inum) + (lbn)) & \
802 static struct sema pagedep_in_progress;
805 * Helper routine for pagedep_lookup()
809 pagedep_find(struct pagedep_hashhead *pagedephd, ino_t ino, ufs_lbn_t lbn,
812 struct pagedep *pagedep;
814 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
815 if (ino == pagedep->pd_ino &&
816 lbn == pagedep->pd_lbn &&
817 mp == pagedep->pd_mnt) {
825 * Look up a pagedep. Return 1 if found, 0 if not found.
826 * If not found, allocate if DEPALLOC flag is passed.
827 * Found or allocated entry is returned in pagedeppp.
828 * This routine must be called with splbio interrupts blocked.
831 pagedep_lookup(struct inode *ip, ufs_lbn_t lbn, int flags,
832 struct pagedep **pagedeppp)
834 struct pagedep *pagedep;
835 struct pagedep_hashhead *pagedephd;
839 KKASSERT(lock_held(&lk) > 0);
841 mp = ITOV(ip)->v_mount;
842 pagedephd = PAGEDEP_HASH(mp, ip->i_number, lbn);
844 *pagedeppp = pagedep_find(pagedephd, ip->i_number, lbn, mp);
847 if ((flags & DEPALLOC) == 0)
849 if (sema_get(&pagedep_in_progress, &lk) == 0)
853 pagedep = kmalloc(sizeof(struct pagedep), M_PAGEDEP,
854 M_SOFTDEP_FLAGS | M_ZERO);
856 if (pagedep_find(pagedephd, ip->i_number, lbn, mp)) {
857 kprintf("pagedep_lookup: blocking race avoided\n");
858 sema_release(&pagedep_in_progress, &lk);
859 kfree(pagedep, M_PAGEDEP);
863 pagedep->pd_list.wk_type = D_PAGEDEP;
864 pagedep->pd_mnt = mp;
865 pagedep->pd_ino = ip->i_number;
866 pagedep->pd_lbn = lbn;
867 LIST_INIT(&pagedep->pd_dirremhd);
868 LIST_INIT(&pagedep->pd_pendinghd);
869 for (i = 0; i < DAHASHSZ; i++)
870 LIST_INIT(&pagedep->pd_diraddhd[i]);
871 LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
872 sema_release(&pagedep_in_progress, &lk);
873 *pagedeppp = pagedep;
878 * Structures and routines associated with inodedep caching.
880 LIST_HEAD(inodedep_hashhead, inodedep) *inodedep_hashtbl;
881 static u_long inodedep_hash; /* size of hash table - 1 */
882 static long num_inodedep; /* number of inodedep allocated */
883 #define INODEDEP_HASH(fs, inum) \
884 (&inodedep_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & inodedep_hash])
885 static struct sema inodedep_in_progress;
888 * Helper routine for inodedep_lookup()
892 inodedep_find(struct inodedep_hashhead *inodedephd, struct fs *fs, ino_t inum)
894 struct inodedep *inodedep;
896 LIST_FOREACH(inodedep, inodedephd, id_hash) {
897 if (inum == inodedep->id_ino && fs == inodedep->id_fs)
904 * Look up a inodedep. Return 1 if found, 0 if not found.
905 * If not found, allocate if DEPALLOC flag is passed.
906 * Found or allocated entry is returned in inodedeppp.
907 * This routine must be called with splbio interrupts blocked.
910 inodedep_lookup(struct fs *fs, ino_t inum, int flags,
911 struct inodedep **inodedeppp)
913 struct inodedep *inodedep;
914 struct inodedep_hashhead *inodedephd;
917 KKASSERT(lock_held(&lk) > 0);
920 inodedephd = INODEDEP_HASH(fs, inum);
922 *inodedeppp = inodedep_find(inodedephd, fs, inum);
925 if ((flags & DEPALLOC) == 0)
928 * If we are over our limit, try to improve the situation.
930 if (num_inodedep > max_softdeps && firsttry &&
931 speedup_syncer() == 0 && (flags & NODELAY) == 0 &&
932 request_cleanup(FLUSH_INODES)) {
936 if (sema_get(&inodedep_in_progress, &lk) == 0)
940 inodedep = kmalloc(sizeof(struct inodedep), M_INODEDEP,
941 M_SOFTDEP_FLAGS | M_ZERO);
943 if (inodedep_find(inodedephd, fs, inum)) {
944 kprintf("inodedep_lookup: blocking race avoided\n");
945 sema_release(&inodedep_in_progress, &lk);
946 kfree(inodedep, M_INODEDEP);
949 inodedep->id_list.wk_type = D_INODEDEP;
950 inodedep->id_fs = fs;
951 inodedep->id_ino = inum;
952 inodedep->id_state = ALLCOMPLETE;
953 inodedep->id_nlinkdelta = 0;
954 inodedep->id_savedino = NULL;
955 inodedep->id_savedsize = -1;
956 inodedep->id_buf = NULL;
957 LIST_INIT(&inodedep->id_pendinghd);
958 LIST_INIT(&inodedep->id_inowait);
959 LIST_INIT(&inodedep->id_bufwait);
960 TAILQ_INIT(&inodedep->id_inoupdt);
961 TAILQ_INIT(&inodedep->id_newinoupdt);
963 LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
964 sema_release(&inodedep_in_progress, &lk);
965 *inodedeppp = inodedep;
970 * Structures and routines associated with newblk caching.
972 LIST_HEAD(newblk_hashhead, newblk) *newblk_hashtbl;
973 u_long newblk_hash; /* size of hash table - 1 */
974 #define NEWBLK_HASH(fs, inum) \
975 (&newblk_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & newblk_hash])
976 static struct sema newblk_in_progress;
979 * Helper routine for newblk_lookup()
983 newblk_find(struct newblk_hashhead *newblkhd, struct fs *fs,
984 ufs_daddr_t newblkno)
986 struct newblk *newblk;
988 LIST_FOREACH(newblk, newblkhd, nb_hash) {
989 if (newblkno == newblk->nb_newblkno && fs == newblk->nb_fs)
996 * Look up a newblk. Return 1 if found, 0 if not found.
997 * If not found, allocate if DEPALLOC flag is passed.
998 * Found or allocated entry is returned in newblkpp.
1001 newblk_lookup(struct fs *fs, ufs_daddr_t newblkno, int flags,
1002 struct newblk **newblkpp)
1004 struct newblk *newblk;
1005 struct newblk_hashhead *newblkhd;
1007 newblkhd = NEWBLK_HASH(fs, newblkno);
1009 *newblkpp = newblk_find(newblkhd, fs, newblkno);
1012 if ((flags & DEPALLOC) == 0)
1014 if (sema_get(&newblk_in_progress, NULL) == 0)
1017 newblk = kmalloc(sizeof(struct newblk), M_NEWBLK,
1018 M_SOFTDEP_FLAGS | M_ZERO);
1020 if (newblk_find(newblkhd, fs, newblkno)) {
1021 kprintf("newblk_lookup: blocking race avoided\n");
1022 sema_release(&pagedep_in_progress, NULL);
1023 kfree(newblk, M_NEWBLK);
1026 newblk->nb_state = 0;
1028 newblk->nb_newblkno = newblkno;
1029 LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
1030 sema_release(&newblk_in_progress, NULL);
1036 * Executed during filesystem system initialization before
1037 * mounting any filesystems.
1040 softdep_initialize(void)
1042 LIST_INIT(&mkdirlisthd);
1043 LIST_INIT(&softdep_workitem_pending);
1044 max_softdeps = min(desiredvnodes * 8,
1045 M_INODEDEP->ks_limit / (2 * sizeof(struct inodedep)));
1046 pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
1048 lockinit(&lk, "ffs_softdep", 0, LK_CANRECURSE);
1049 sema_init(&pagedep_in_progress, "pagedep", 0);
1050 inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP, &inodedep_hash);
1051 sema_init(&inodedep_in_progress, "inodedep", 0);
1052 newblk_hashtbl = hashinit(64, M_NEWBLK, &newblk_hash);
1053 sema_init(&newblk_in_progress, "newblk", 0);
1054 add_bio_ops(&softdep_bioops);
1058 * Called at mount time to notify the dependency code that a
1059 * filesystem wishes to use it.
1062 softdep_mount(struct vnode *devvp, struct mount *mp, struct fs *fs)
1064 struct csum cstotal;
1069 mp->mnt_flag &= ~MNT_ASYNC;
1070 mp->mnt_flag |= MNT_SOFTDEP;
1071 mp->mnt_bioops = &softdep_bioops;
1073 * When doing soft updates, the counters in the
1074 * superblock may have gotten out of sync, so we have
1075 * to scan the cylinder groups and recalculate them.
1077 if (fs->fs_clean != 0)
1079 bzero(&cstotal, sizeof cstotal);
1080 for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
1081 if ((error = bread(devvp, fsbtodoff(fs, cgtod(fs, cyl)),
1082 fs->fs_cgsize, &bp)) != 0) {
1086 cgp = (struct cg *)bp->b_data;
1087 cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
1088 cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
1089 cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
1090 cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
1091 fs->fs_cs(fs, cyl) = cgp->cg_cs;
1095 if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
1096 kprintf("ffs_mountfs: superblock updated for soft updates\n");
1098 bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
1103 * Protecting the freemaps (or bitmaps).
1105 * To eliminate the need to execute fsck before mounting a filesystem
1106 * after a power failure, one must (conservatively) guarantee that the
1107 * on-disk copy of the bitmaps never indicate that a live inode or block is
1108 * free. So, when a block or inode is allocated, the bitmap should be
1109 * updated (on disk) before any new pointers. When a block or inode is
1110 * freed, the bitmap should not be updated until all pointers have been
1111 * reset. The latter dependency is handled by the delayed de-allocation
1112 * approach described below for block and inode de-allocation. The former
1113 * dependency is handled by calling the following procedure when a block or
1114 * inode is allocated. When an inode is allocated an "inodedep" is created
1115 * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
1116 * Each "inodedep" is also inserted into the hash indexing structure so
1117 * that any additional link additions can be made dependent on the inode
1120 * The ufs filesystem maintains a number of free block counts (e.g., per
1121 * cylinder group, per cylinder and per <cylinder, rotational position> pair)
1122 * in addition to the bitmaps. These counts are used to improve efficiency
1123 * during allocation and therefore must be consistent with the bitmaps.
1124 * There is no convenient way to guarantee post-crash consistency of these
1125 * counts with simple update ordering, for two main reasons: (1) The counts
1126 * and bitmaps for a single cylinder group block are not in the same disk
1127 * sector. If a disk write is interrupted (e.g., by power failure), one may
1128 * be written and the other not. (2) Some of the counts are located in the
1129 * superblock rather than the cylinder group block. So, we focus our soft
1130 * updates implementation on protecting the bitmaps. When mounting a
1131 * filesystem, we recompute the auxiliary counts from the bitmaps.
1135 * Called just after updating the cylinder group block to allocate an inode.
1138 * bp: buffer for cylgroup block with inode map
1139 * ip: inode related to allocation
1140 * newinum: new inode number being allocated
1143 softdep_setup_inomapdep(struct buf *bp, struct inode *ip, ino_t newinum)
1145 struct inodedep *inodedep;
1146 struct bmsafemap *bmsafemap;
1149 * Create a dependency for the newly allocated inode.
1150 * Panic if it already exists as something is seriously wrong.
1151 * Otherwise add it to the dependency list for the buffer holding
1152 * the cylinder group map from which it was allocated.
1155 if ((inodedep_lookup(ip->i_fs, newinum, DEPALLOC|NODELAY, &inodedep))) {
1156 panic("softdep_setup_inomapdep: found inode");
1158 inodedep->id_buf = bp;
1159 inodedep->id_state &= ~DEPCOMPLETE;
1160 bmsafemap = bmsafemap_lookup(bp);
1161 LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
1166 * Called just after updating the cylinder group block to
1167 * allocate block or fragment.
1170 * bp: buffer for cylgroup block with block map
1171 * fs: filesystem doing allocation
1172 * newblkno: number of newly allocated block
1175 softdep_setup_blkmapdep(struct buf *bp, struct fs *fs,
1176 ufs_daddr_t newblkno)
1178 struct newblk *newblk;
1179 struct bmsafemap *bmsafemap;
1182 * Create a dependency for the newly allocated block.
1183 * Add it to the dependency list for the buffer holding
1184 * the cylinder group map from which it was allocated.
1186 if (newblk_lookup(fs, newblkno, DEPALLOC, &newblk) != 0)
1187 panic("softdep_setup_blkmapdep: found block");
1189 newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(bp);
1190 LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
1195 * Find the bmsafemap associated with a cylinder group buffer.
1196 * If none exists, create one. The buffer must be locked when
1197 * this routine is called and this routine must be called with
1198 * splbio interrupts blocked.
1200 static struct bmsafemap *
1201 bmsafemap_lookup(struct buf *bp)
1203 struct bmsafemap *bmsafemap;
1204 struct worklist *wk;
1206 KKASSERT(lock_held(&lk) > 0);
1208 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
1209 if (wk->wk_type == D_BMSAFEMAP)
1210 return (WK_BMSAFEMAP(wk));
1213 bmsafemap = kmalloc(sizeof(struct bmsafemap), M_BMSAFEMAP,
1215 bmsafemap->sm_list.wk_type = D_BMSAFEMAP;
1216 bmsafemap->sm_list.wk_state = 0;
1217 bmsafemap->sm_buf = bp;
1218 LIST_INIT(&bmsafemap->sm_allocdirecthd);
1219 LIST_INIT(&bmsafemap->sm_allocindirhd);
1220 LIST_INIT(&bmsafemap->sm_inodedephd);
1221 LIST_INIT(&bmsafemap->sm_newblkhd);
1223 WORKLIST_INSERT_BP(bp, &bmsafemap->sm_list);
1228 * Direct block allocation dependencies.
1230 * When a new block is allocated, the corresponding disk locations must be
1231 * initialized (with zeros or new data) before the on-disk inode points to
1232 * them. Also, the freemap from which the block was allocated must be
1233 * updated (on disk) before the inode's pointer. These two dependencies are
1234 * independent of each other and are needed for all file blocks and indirect
1235 * blocks that are pointed to directly by the inode. Just before the
1236 * "in-core" version of the inode is updated with a newly allocated block
1237 * number, a procedure (below) is called to setup allocation dependency
1238 * structures. These structures are removed when the corresponding
1239 * dependencies are satisfied or when the block allocation becomes obsolete
1240 * (i.e., the file is deleted, the block is de-allocated, or the block is a
1241 * fragment that gets upgraded). All of these cases are handled in
1242 * procedures described later.
1244 * When a file extension causes a fragment to be upgraded, either to a larger
1245 * fragment or to a full block, the on-disk location may change (if the
1246 * previous fragment could not simply be extended). In this case, the old
1247 * fragment must be de-allocated, but not until after the inode's pointer has
1248 * been updated. In most cases, this is handled by later procedures, which
1249 * will construct a "freefrag" structure to be added to the workitem queue
1250 * when the inode update is complete (or obsolete). The main exception to
1251 * this is when an allocation occurs while a pending allocation dependency
1252 * (for the same block pointer) remains. This case is handled in the main
1253 * allocation dependency setup procedure by immediately freeing the
1254 * unreferenced fragments.
1257 * ip: inode to which block is being added
1258 * lbn: block pointer within inode
1259 * newblkno: disk block number being added
1260 * oldblkno: previous block number, 0 unless frag
1261 * newsize: size of new block
1262 * oldsize: size of new block
1263 * bp: bp for allocated block
1266 softdep_setup_allocdirect(struct inode *ip, ufs_lbn_t lbn, ufs_daddr_t newblkno,
1267 ufs_daddr_t oldblkno, long newsize, long oldsize,
1270 struct allocdirect *adp, *oldadp;
1271 struct allocdirectlst *adphead;
1272 struct bmsafemap *bmsafemap;
1273 struct inodedep *inodedep;
1274 struct pagedep *pagedep;
1275 struct newblk *newblk;
1277 adp = kmalloc(sizeof(struct allocdirect), M_ALLOCDIRECT,
1278 M_SOFTDEP_FLAGS | M_ZERO);
1279 adp->ad_list.wk_type = D_ALLOCDIRECT;
1281 adp->ad_newblkno = newblkno;
1282 adp->ad_oldblkno = oldblkno;
1283 adp->ad_newsize = newsize;
1284 adp->ad_oldsize = oldsize;
1285 adp->ad_state = ATTACHED;
1286 if (newblkno == oldblkno)
1287 adp->ad_freefrag = NULL;
1289 adp->ad_freefrag = newfreefrag(ip, oldblkno, oldsize);
1291 if (newblk_lookup(ip->i_fs, newblkno, 0, &newblk) == 0)
1292 panic("softdep_setup_allocdirect: lost block");
1295 inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC | NODELAY, &inodedep);
1296 adp->ad_inodedep = inodedep;
1298 if (newblk->nb_state == DEPCOMPLETE) {
1299 adp->ad_state |= DEPCOMPLETE;
1302 bmsafemap = newblk->nb_bmsafemap;
1303 adp->ad_buf = bmsafemap->sm_buf;
1304 LIST_REMOVE(newblk, nb_deps);
1305 LIST_INSERT_HEAD(&bmsafemap->sm_allocdirecthd, adp, ad_deps);
1307 LIST_REMOVE(newblk, nb_hash);
1308 kfree(newblk, M_NEWBLK);
1310 WORKLIST_INSERT_BP(bp, &adp->ad_list);
1311 if (lbn >= NDADDR) {
1312 /* allocating an indirect block */
1313 if (oldblkno != 0) {
1314 panic("softdep_setup_allocdirect: non-zero indir");
1318 * Allocating a direct block.
1320 * If we are allocating a directory block, then we must
1321 * allocate an associated pagedep to track additions and
1324 if ((ip->i_mode & IFMT) == IFDIR &&
1325 pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0) {
1326 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
1330 * The list of allocdirects must be kept in sorted and ascending
1331 * order so that the rollback routines can quickly determine the
1332 * first uncommitted block (the size of the file stored on disk
1333 * ends at the end of the lowest committed fragment, or if there
1334 * are no fragments, at the end of the highest committed block).
1335 * Since files generally grow, the typical case is that the new
1336 * block is to be added at the end of the list. We speed this
1337 * special case by checking against the last allocdirect in the
1338 * list before laboriously traversing the list looking for the
1341 adphead = &inodedep->id_newinoupdt;
1342 oldadp = TAILQ_LAST(adphead, allocdirectlst);
1343 if (oldadp == NULL || oldadp->ad_lbn <= lbn) {
1344 /* insert at end of list */
1345 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
1346 if (oldadp != NULL && oldadp->ad_lbn == lbn)
1347 allocdirect_merge(adphead, adp, oldadp);
1351 TAILQ_FOREACH(oldadp, adphead, ad_next) {
1352 if (oldadp->ad_lbn >= lbn)
1355 if (oldadp == NULL) {
1356 panic("softdep_setup_allocdirect: lost entry");
1358 /* insert in middle of list */
1359 TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
1360 if (oldadp->ad_lbn == lbn)
1361 allocdirect_merge(adphead, adp, oldadp);
1366 * Replace an old allocdirect dependency with a newer one.
1367 * This routine must be called with splbio interrupts blocked.
1370 * adphead: head of list holding allocdirects
1371 * newadp: allocdirect being added
1372 * oldadp: existing allocdirect being checked
1375 allocdirect_merge(struct allocdirectlst *adphead,
1376 struct allocdirect *newadp,
1377 struct allocdirect *oldadp)
1379 struct freefrag *freefrag;
1381 KKASSERT(lock_held(&lk) > 0);
1383 if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
1384 newadp->ad_oldsize != oldadp->ad_newsize ||
1385 newadp->ad_lbn >= NDADDR) {
1386 panic("allocdirect_check: old %d != new %d || lbn %ld >= %d",
1387 newadp->ad_oldblkno, oldadp->ad_newblkno, newadp->ad_lbn,
1390 newadp->ad_oldblkno = oldadp->ad_oldblkno;
1391 newadp->ad_oldsize = oldadp->ad_oldsize;
1393 * If the old dependency had a fragment to free or had never
1394 * previously had a block allocated, then the new dependency
1395 * can immediately post its freefrag and adopt the old freefrag.
1396 * This action is done by swapping the freefrag dependencies.
1397 * The new dependency gains the old one's freefrag, and the
1398 * old one gets the new one and then immediately puts it on
1399 * the worklist when it is freed by free_allocdirect. It is
1400 * not possible to do this swap when the old dependency had a
1401 * non-zero size but no previous fragment to free. This condition
1402 * arises when the new block is an extension of the old block.
1403 * Here, the first part of the fragment allocated to the new
1404 * dependency is part of the block currently claimed on disk by
1405 * the old dependency, so cannot legitimately be freed until the
1406 * conditions for the new dependency are fulfilled.
1408 if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
1409 freefrag = newadp->ad_freefrag;
1410 newadp->ad_freefrag = oldadp->ad_freefrag;
1411 oldadp->ad_freefrag = freefrag;
1413 free_allocdirect(adphead, oldadp, 0);
1417 * Allocate a new freefrag structure if needed.
1419 static struct freefrag *
1420 newfreefrag(struct inode *ip, ufs_daddr_t blkno, long size)
1422 struct freefrag *freefrag;
1428 if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
1429 panic("newfreefrag: frag size");
1430 freefrag = kmalloc(sizeof(struct freefrag), M_FREEFRAG,
1432 freefrag->ff_list.wk_type = D_FREEFRAG;
1433 freefrag->ff_state = ip->i_uid & ~ONWORKLIST; /* XXX - used below */
1434 freefrag->ff_inum = ip->i_number;
1435 freefrag->ff_fs = fs;
1436 freefrag->ff_devvp = ip->i_devvp;
1437 freefrag->ff_blkno = blkno;
1438 freefrag->ff_fragsize = size;
1443 * This workitem de-allocates fragments that were replaced during
1444 * file block allocation.
1447 handle_workitem_freefrag(struct freefrag *freefrag)
1451 tip.i_fs = freefrag->ff_fs;
1452 tip.i_devvp = freefrag->ff_devvp;
1453 tip.i_dev = freefrag->ff_devvp->v_rdev;
1454 tip.i_number = freefrag->ff_inum;
1455 tip.i_uid = freefrag->ff_state & ~ONWORKLIST; /* XXX - set above */
1456 ffs_blkfree(&tip, freefrag->ff_blkno, freefrag->ff_fragsize);
1457 kfree(freefrag, M_FREEFRAG);
1461 * Indirect block allocation dependencies.
1463 * The same dependencies that exist for a direct block also exist when
1464 * a new block is allocated and pointed to by an entry in a block of
1465 * indirect pointers. The undo/redo states described above are also
1466 * used here. Because an indirect block contains many pointers that
1467 * may have dependencies, a second copy of the entire in-memory indirect
1468 * block is kept. The buffer cache copy is always completely up-to-date.
1469 * The second copy, which is used only as a source for disk writes,
1470 * contains only the safe pointers (i.e., those that have no remaining
1471 * update dependencies). The second copy is freed when all pointers
1472 * are safe. The cache is not allowed to replace indirect blocks with
1473 * pending update dependencies. If a buffer containing an indirect
1474 * block with dependencies is written, these routines will mark it
1475 * dirty again. It can only be successfully written once all the
1476 * dependencies are removed. The ffs_fsync routine in conjunction with
1477 * softdep_sync_metadata work together to get all the dependencies
1478 * removed so that a file can be successfully written to disk. Three
1479 * procedures are used when setting up indirect block pointer
1480 * dependencies. The division is necessary because of the organization
1481 * of the "balloc" routine and because of the distinction between file
1482 * pages and file metadata blocks.
1486 * Allocate a new allocindir structure.
1489 * ip: inode for file being extended
1490 * ptrno: offset of pointer in indirect block
1491 * newblkno: disk block number being added
1492 * oldblkno: previous block number, 0 if none
1494 static struct allocindir *
1495 newallocindir(struct inode *ip, int ptrno, ufs_daddr_t newblkno,
1496 ufs_daddr_t oldblkno)
1498 struct allocindir *aip;
1500 aip = kmalloc(sizeof(struct allocindir), M_ALLOCINDIR,
1501 M_SOFTDEP_FLAGS | M_ZERO);
1502 aip->ai_list.wk_type = D_ALLOCINDIR;
1503 aip->ai_state = ATTACHED;
1504 aip->ai_offset = ptrno;
1505 aip->ai_newblkno = newblkno;
1506 aip->ai_oldblkno = oldblkno;
1507 aip->ai_freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize);
1512 * Called just before setting an indirect block pointer
1513 * to a newly allocated file page.
1516 * ip: inode for file being extended
1517 * lbn: allocated block number within file
1518 * bp: buffer with indirect blk referencing page
1519 * ptrno: offset of pointer in indirect block
1520 * newblkno: disk block number being added
1521 * oldblkno: previous block number, 0 if none
1522 * nbp: buffer holding allocated page
1525 softdep_setup_allocindir_page(struct inode *ip, ufs_lbn_t lbn,
1526 struct buf *bp, int ptrno,
1527 ufs_daddr_t newblkno, ufs_daddr_t oldblkno,
1530 struct allocindir *aip;
1531 struct pagedep *pagedep;
1533 aip = newallocindir(ip, ptrno, newblkno, oldblkno);
1536 * If we are allocating a directory page, then we must
1537 * allocate an associated pagedep to track additions and
1540 if ((ip->i_mode & IFMT) == IFDIR &&
1541 pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0)
1542 WORKLIST_INSERT_BP(nbp, &pagedep->pd_list);
1543 WORKLIST_INSERT_BP(nbp, &aip->ai_list);
1545 setup_allocindir_phase2(bp, ip, aip);
1549 * Called just before setting an indirect block pointer to a
1550 * newly allocated indirect block.
1552 * nbp: newly allocated indirect block
1553 * ip: inode for file being extended
1554 * bp: indirect block referencing allocated block
1555 * ptrno: offset of pointer in indirect block
1556 * newblkno: disk block number being added
1559 softdep_setup_allocindir_meta(struct buf *nbp, struct inode *ip,
1560 struct buf *bp, int ptrno,
1561 ufs_daddr_t newblkno)
1563 struct allocindir *aip;
1565 aip = newallocindir(ip, ptrno, newblkno, 0);
1567 WORKLIST_INSERT_BP(nbp, &aip->ai_list);
1569 setup_allocindir_phase2(bp, ip, aip);
1573 * Called to finish the allocation of the "aip" allocated
1574 * by one of the two routines above.
1577 * bp: in-memory copy of the indirect block
1578 * ip: inode for file being extended
1579 * aip: allocindir allocated by the above routines
1582 setup_allocindir_phase2(struct buf *bp, struct inode *ip,
1583 struct allocindir *aip)
1585 struct worklist *wk;
1586 struct indirdep *indirdep, *newindirdep;
1587 struct bmsafemap *bmsafemap;
1588 struct allocindir *oldaip;
1589 struct freefrag *freefrag;
1590 struct newblk *newblk;
1592 if (bp->b_loffset >= 0)
1593 panic("setup_allocindir_phase2: not indir blk");
1594 for (indirdep = NULL, newindirdep = NULL; ; ) {
1596 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
1597 if (wk->wk_type != D_INDIRDEP)
1599 indirdep = WK_INDIRDEP(wk);
1602 if (indirdep == NULL && newindirdep) {
1603 indirdep = newindirdep;
1604 WORKLIST_INSERT_BP(bp, &indirdep->ir_list);
1609 if (newblk_lookup(ip->i_fs, aip->ai_newblkno, 0,
1611 panic("setup_allocindir: lost block");
1613 if (newblk->nb_state == DEPCOMPLETE) {
1614 aip->ai_state |= DEPCOMPLETE;
1617 bmsafemap = newblk->nb_bmsafemap;
1618 aip->ai_buf = bmsafemap->sm_buf;
1619 LIST_REMOVE(newblk, nb_deps);
1620 LIST_INSERT_HEAD(&bmsafemap->sm_allocindirhd,
1623 LIST_REMOVE(newblk, nb_hash);
1624 kfree(newblk, M_NEWBLK);
1625 aip->ai_indirdep = indirdep;
1627 * Check to see if there is an existing dependency
1628 * for this block. If there is, merge the old
1629 * dependency into the new one.
1631 if (aip->ai_oldblkno == 0)
1635 LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next)
1636 if (oldaip->ai_offset == aip->ai_offset)
1638 if (oldaip != NULL) {
1639 if (oldaip->ai_newblkno != aip->ai_oldblkno) {
1640 panic("setup_allocindir_phase2: blkno");
1642 aip->ai_oldblkno = oldaip->ai_oldblkno;
1643 freefrag = oldaip->ai_freefrag;
1644 oldaip->ai_freefrag = aip->ai_freefrag;
1645 aip->ai_freefrag = freefrag;
1646 free_allocindir(oldaip, NULL);
1648 LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
1649 ((ufs_daddr_t *)indirdep->ir_savebp->b_data)
1650 [aip->ai_offset] = aip->ai_oldblkno;
1655 * Avoid any possibility of data corruption by
1656 * ensuring that our old version is thrown away.
1658 newindirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
1659 brelse(newindirdep->ir_savebp);
1660 WORKITEM_FREE((caddr_t)newindirdep, D_INDIRDEP);
1664 newindirdep = kmalloc(sizeof(struct indirdep), M_INDIRDEP,
1666 newindirdep->ir_list.wk_type = D_INDIRDEP;
1667 newindirdep->ir_state = ATTACHED;
1668 LIST_INIT(&newindirdep->ir_deplisthd);
1669 LIST_INIT(&newindirdep->ir_donehd);
1670 if (bp->b_bio2.bio_offset == NOOFFSET) {
1671 VOP_BMAP(bp->b_vp, bp->b_bio1.bio_offset,
1672 &bp->b_bio2.bio_offset, NULL, NULL,
1675 KKASSERT(bp->b_bio2.bio_offset != NOOFFSET);
1676 newindirdep->ir_savebp = getblk(ip->i_devvp,
1677 bp->b_bio2.bio_offset,
1678 bp->b_bcount, 0, 0);
1679 BUF_KERNPROC(newindirdep->ir_savebp);
1680 bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
1685 * Block de-allocation dependencies.
1687 * When blocks are de-allocated, the on-disk pointers must be nullified before
1688 * the blocks are made available for use by other files. (The true
1689 * requirement is that old pointers must be nullified before new on-disk
1690 * pointers are set. We chose this slightly more stringent requirement to
1691 * reduce complexity.) Our implementation handles this dependency by updating
1692 * the inode (or indirect block) appropriately but delaying the actual block
1693 * de-allocation (i.e., freemap and free space count manipulation) until
1694 * after the updated versions reach stable storage. After the disk is
1695 * updated, the blocks can be safely de-allocated whenever it is convenient.
1696 * This implementation handles only the common case of reducing a file's
1697 * length to zero. Other cases are handled by the conventional synchronous
1700 * The ffs implementation with which we worked double-checks
1701 * the state of the block pointers and file size as it reduces
1702 * a file's length. Some of this code is replicated here in our
1703 * soft updates implementation. The freeblks->fb_chkcnt field is
1704 * used to transfer a part of this information to the procedure
1705 * that eventually de-allocates the blocks.
1707 * This routine should be called from the routine that shortens
1708 * a file's length, before the inode's size or block pointers
1709 * are modified. It will save the block pointer information for
1710 * later release and zero the inode so that the calling routine
1713 struct softdep_setup_freeblocks_info {
1718 static int softdep_setup_freeblocks_bp(struct buf *bp, void *data);
1722 * ip: The inode whose length is to be reduced
1723 * length: The new length for the file
1726 softdep_setup_freeblocks(struct inode *ip, off_t length)
1728 struct softdep_setup_freeblocks_info info;
1729 struct freeblks *freeblks;
1730 struct inodedep *inodedep;
1731 struct allocdirect *adp;
1735 int i, error, delay;
1740 panic("softde_setup_freeblocks: non-zero length");
1741 freeblks = kmalloc(sizeof(struct freeblks), M_FREEBLKS,
1742 M_SOFTDEP_FLAGS | M_ZERO);
1743 freeblks->fb_list.wk_type = D_FREEBLKS;
1744 freeblks->fb_state = ATTACHED;
1745 freeblks->fb_uid = ip->i_uid;
1746 freeblks->fb_previousinum = ip->i_number;
1747 freeblks->fb_devvp = ip->i_devvp;
1748 freeblks->fb_fs = fs;
1749 freeblks->fb_oldsize = ip->i_size;
1750 freeblks->fb_newsize = length;
1751 freeblks->fb_chkcnt = ip->i_blocks;
1752 for (i = 0; i < NDADDR; i++) {
1753 freeblks->fb_dblks[i] = ip->i_db[i];
1756 for (i = 0; i < NIADDR; i++) {
1757 freeblks->fb_iblks[i] = ip->i_ib[i];
1763 * Push the zero'ed inode to to its disk buffer so that we are free
1764 * to delete its dependencies below. Once the dependencies are gone
1765 * the buffer can be safely released.
1767 if ((error = bread(ip->i_devvp,
1768 fsbtodoff(fs, ino_to_fsba(fs, ip->i_number)),
1769 (int)fs->fs_bsize, &bp)) != 0)
1770 softdep_error("softdep_setup_freeblocks", error);
1771 *((struct ufs1_dinode *)bp->b_data + ino_to_fsbo(fs, ip->i_number)) =
1774 * Find and eliminate any inode dependencies.
1777 (void) inodedep_lookup(fs, ip->i_number, DEPALLOC, &inodedep);
1778 if ((inodedep->id_state & IOSTARTED) != 0) {
1779 panic("softdep_setup_freeblocks: inode busy");
1782 * Add the freeblks structure to the list of operations that
1783 * must await the zero'ed inode being written to disk. If we
1784 * still have a bitmap dependency (delay == 0), then the inode
1785 * has never been written to disk, so we can process the
1786 * freeblks below once we have deleted the dependencies.
1788 delay = (inodedep->id_state & DEPCOMPLETE);
1790 WORKLIST_INSERT(&inodedep->id_bufwait, &freeblks->fb_list);
1792 * Because the file length has been truncated to zero, any
1793 * pending block allocation dependency structures associated
1794 * with this inode are obsolete and can simply be de-allocated.
1795 * We must first merge the two dependency lists to get rid of
1796 * any duplicate freefrag structures, then purge the merged list.
1798 merge_inode_lists(inodedep);
1799 while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
1800 free_allocdirect(&inodedep->id_inoupdt, adp, 1);
1804 * We must wait for any I/O in progress to finish so that
1805 * all potential buffers on the dirty list will be visible.
1806 * Once they are all there, walk the list and get rid of
1811 drain_output(vp, 1);
1815 lwkt_gettoken(&vp->v_token);
1817 count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
1818 softdep_setup_freeblocks_bp, &info);
1819 } while (count != 0);
1820 lwkt_reltoken(&vp->v_token);
1822 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) != 0)
1823 (void)free_inodedep(inodedep);
1826 freeblks->fb_state |= DEPCOMPLETE;
1828 * If the inode with zeroed block pointers is now on disk
1829 * we can start freeing blocks. Add freeblks to the worklist
1830 * instead of calling handle_workitem_freeblocks directly as
1831 * it is more likely that additional IO is needed to complete
1832 * the request here than in the !delay case.
1834 if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
1835 add_to_worklist(&freeblks->fb_list);
1840 * If the inode has never been written to disk (delay == 0),
1841 * then we can process the freeblks now that we have deleted
1845 handle_workitem_freeblocks(freeblks);
1849 softdep_setup_freeblocks_bp(struct buf *bp, void *data)
1851 struct softdep_setup_freeblocks_info *info = data;
1852 struct inodedep *inodedep;
1854 if (getdirtybuf(&bp, MNT_WAIT) == 0) {
1855 kprintf("softdep_setup_freeblocks_bp(1): caught bp %p going away\n", bp);
1858 if (bp->b_vp != ITOV(info->ip) || (bp->b_flags & B_DELWRI) == 0) {
1859 kprintf("softdep_setup_freeblocks_bp(2): caught bp %p going away\n", bp);
1863 (void) inodedep_lookup(info->fs, info->ip->i_number, 0, &inodedep);
1864 deallocate_dependencies(bp, inodedep);
1865 bp->b_flags |= B_INVAL | B_NOCACHE;
1873 * Reclaim any dependency structures from a buffer that is about to
1874 * be reallocated to a new vnode. The buffer must be locked, thus,
1875 * no I/O completion operations can occur while we are manipulating
1876 * its associated dependencies. The mutex is held so that other I/O's
1877 * associated with related dependencies do not occur.
1880 deallocate_dependencies(struct buf *bp, struct inodedep *inodedep)
1882 struct worklist *wk;
1883 struct indirdep *indirdep;
1884 struct allocindir *aip;
1885 struct pagedep *pagedep;
1886 struct dirrem *dirrem;
1890 while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
1891 switch (wk->wk_type) {
1894 indirdep = WK_INDIRDEP(wk);
1896 * None of the indirect pointers will ever be visible,
1897 * so they can simply be tossed. GOINGAWAY ensures
1898 * that allocated pointers will be saved in the buffer
1899 * cache until they are freed. Note that they will
1900 * only be able to be found by their physical address
1901 * since the inode mapping the logical address will
1902 * be gone. The save buffer used for the safe copy
1903 * was allocated in setup_allocindir_phase2 using
1904 * the physical address so it could be used for this
1905 * purpose. Hence we swap the safe copy with the real
1906 * copy, allowing the safe copy to be freed and holding
1907 * on to the real copy for later use in indir_trunc.
1909 * NOTE: ir_savebp is relative to the block device
1910 * so b_bio1 contains the device block number.
1912 if (indirdep->ir_state & GOINGAWAY) {
1913 panic("deallocate_dependencies: already gone");
1915 indirdep->ir_state |= GOINGAWAY;
1916 while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
1917 free_allocindir(aip, inodedep);
1918 if (bp->b_bio1.bio_offset >= 0 ||
1919 bp->b_bio2.bio_offset != indirdep->ir_savebp->b_bio1.bio_offset) {
1920 panic("deallocate_dependencies: not indir");
1922 bcopy(bp->b_data, indirdep->ir_savebp->b_data,
1924 WORKLIST_REMOVE(wk);
1925 WORKLIST_INSERT_BP(indirdep->ir_savebp, wk);
1929 pagedep = WK_PAGEDEP(wk);
1931 * None of the directory additions will ever be
1932 * visible, so they can simply be tossed.
1934 for (i = 0; i < DAHASHSZ; i++)
1936 LIST_FIRST(&pagedep->pd_diraddhd[i])))
1938 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
1941 * Copy any directory remove dependencies to the list
1942 * to be processed after the zero'ed inode is written.
1943 * If the inode has already been written, then they
1944 * can be dumped directly onto the work list.
1946 LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
1947 LIST_REMOVE(dirrem, dm_next);
1948 dirrem->dm_dirinum = pagedep->pd_ino;
1949 if (inodedep == NULL ||
1950 (inodedep->id_state & ALLCOMPLETE) ==
1952 add_to_worklist(&dirrem->dm_list);
1954 WORKLIST_INSERT(&inodedep->id_bufwait,
1957 WORKLIST_REMOVE(&pagedep->pd_list);
1958 LIST_REMOVE(pagedep, pd_hash);
1959 WORKITEM_FREE(pagedep, D_PAGEDEP);
1963 free_allocindir(WK_ALLOCINDIR(wk), inodedep);
1968 panic("deallocate_dependencies: Unexpected type %s",
1969 TYPENAME(wk->wk_type));
1973 panic("deallocate_dependencies: Unknown type %s",
1974 TYPENAME(wk->wk_type));
1981 * Free an allocdirect. Generate a new freefrag work request if appropriate.
1982 * This routine must be called with splbio interrupts blocked.
1985 free_allocdirect(struct allocdirectlst *adphead,
1986 struct allocdirect *adp, int delay)
1988 KKASSERT(lock_held(&lk) > 0);
1990 if ((adp->ad_state & DEPCOMPLETE) == 0)
1991 LIST_REMOVE(adp, ad_deps);
1992 TAILQ_REMOVE(adphead, adp, ad_next);
1993 if ((adp->ad_state & COMPLETE) == 0)
1994 WORKLIST_REMOVE(&adp->ad_list);
1995 if (adp->ad_freefrag != NULL) {
1997 WORKLIST_INSERT(&adp->ad_inodedep->id_bufwait,
1998 &adp->ad_freefrag->ff_list);
2000 add_to_worklist(&adp->ad_freefrag->ff_list);
2002 WORKITEM_FREE(adp, D_ALLOCDIRECT);
2006 * Prepare an inode to be freed. The actual free operation is not
2007 * done until the zero'ed inode has been written to disk.
2010 softdep_freefile(struct vnode *pvp, ino_t ino, int mode)
2012 struct inode *ip = VTOI(pvp);
2013 struct inodedep *inodedep;
2014 struct freefile *freefile;
2017 * This sets up the inode de-allocation dependency.
2019 freefile = kmalloc(sizeof(struct freefile), M_FREEFILE,
2021 freefile->fx_list.wk_type = D_FREEFILE;
2022 freefile->fx_list.wk_state = 0;
2023 freefile->fx_mode = mode;
2024 freefile->fx_oldinum = ino;
2025 freefile->fx_devvp = ip->i_devvp;
2026 freefile->fx_fs = ip->i_fs;
2029 * If the inodedep does not exist, then the zero'ed inode has
2030 * been written to disk. If the allocated inode has never been
2031 * written to disk, then the on-disk inode is zero'ed. In either
2032 * case we can free the file immediately.
2035 if (inodedep_lookup(ip->i_fs, ino, 0, &inodedep) == 0 ||
2036 check_inode_unwritten(inodedep)) {
2038 handle_workitem_freefile(freefile);
2041 WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
2046 * Check to see if an inode has never been written to disk. If
2047 * so free the inodedep and return success, otherwise return failure.
2048 * This routine must be called with splbio interrupts blocked.
2050 * If we still have a bitmap dependency, then the inode has never
2051 * been written to disk. Drop the dependency as it is no longer
2052 * necessary since the inode is being deallocated. We set the
2053 * ALLCOMPLETE flags since the bitmap now properly shows that the
2054 * inode is not allocated. Even if the inode is actively being
2055 * written, it has been rolled back to its zero'ed state, so we
2056 * are ensured that a zero inode is what is on the disk. For short
2057 * lived files, this change will usually result in removing all the
2058 * dependencies from the inode so that it can be freed immediately.
2061 check_inode_unwritten(struct inodedep *inodedep)
2064 if ((inodedep->id_state & DEPCOMPLETE) != 0 ||
2065 LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2066 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2067 LIST_FIRST(&inodedep->id_inowait) != NULL ||
2068 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2069 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2070 inodedep->id_nlinkdelta != 0)
2074 * Another process might be in initiate_write_inodeblock
2075 * trying to allocate memory without holding "Softdep Lock".
2077 if ((inodedep->id_state & IOSTARTED) != 0 &&
2078 inodedep->id_savedino == NULL)
2081 inodedep->id_state |= ALLCOMPLETE;
2082 LIST_REMOVE(inodedep, id_deps);
2083 inodedep->id_buf = NULL;
2084 if (inodedep->id_state & ONWORKLIST)
2085 WORKLIST_REMOVE(&inodedep->id_list);
2086 if (inodedep->id_savedino != NULL) {
2087 kfree(inodedep->id_savedino, M_INODEDEP);
2088 inodedep->id_savedino = NULL;
2090 if (free_inodedep(inodedep) == 0) {
2091 panic("check_inode_unwritten: busy inode");
2097 * Try to free an inodedep structure. Return 1 if it could be freed.
2100 free_inodedep(struct inodedep *inodedep)
2103 if ((inodedep->id_state & ONWORKLIST) != 0 ||
2104 (inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
2105 LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2106 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2107 LIST_FIRST(&inodedep->id_inowait) != NULL ||
2108 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2109 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2110 inodedep->id_nlinkdelta != 0 || inodedep->id_savedino != NULL)
2112 LIST_REMOVE(inodedep, id_hash);
2113 WORKITEM_FREE(inodedep, D_INODEDEP);
2119 * This workitem routine performs the block de-allocation.
2120 * The workitem is added to the pending list after the updated
2121 * inode block has been written to disk. As mentioned above,
2122 * checks regarding the number of blocks de-allocated (compared
2123 * to the number of blocks allocated for the file) are also
2124 * performed in this function.
2127 handle_workitem_freeblocks(struct freeblks *freeblks)
2132 int i, level, bsize;
2133 long nblocks, blocksreleased = 0;
2134 int error, allerror = 0;
2135 ufs_lbn_t baselbns[NIADDR], tmpval;
2137 tip.i_number = freeblks->fb_previousinum;
2138 tip.i_devvp = freeblks->fb_devvp;
2139 tip.i_dev = freeblks->fb_devvp->v_rdev;
2140 tip.i_fs = freeblks->fb_fs;
2141 tip.i_size = freeblks->fb_oldsize;
2142 tip.i_uid = freeblks->fb_uid;
2143 fs = freeblks->fb_fs;
2145 baselbns[0] = NDADDR;
2146 for (i = 1; i < NIADDR; i++) {
2147 tmpval *= NINDIR(fs);
2148 baselbns[i] = baselbns[i - 1] + tmpval;
2150 nblocks = btodb(fs->fs_bsize);
2153 * Indirect blocks first.
2155 for (level = (NIADDR - 1); level >= 0; level--) {
2156 if ((bn = freeblks->fb_iblks[level]) == 0)
2158 if ((error = indir_trunc(&tip, fsbtodoff(fs, bn), level,
2159 baselbns[level], &blocksreleased)) == 0)
2161 ffs_blkfree(&tip, bn, fs->fs_bsize);
2162 blocksreleased += nblocks;
2165 * All direct blocks or frags.
2167 for (i = (NDADDR - 1); i >= 0; i--) {
2168 if ((bn = freeblks->fb_dblks[i]) == 0)
2170 bsize = blksize(fs, &tip, i);
2171 ffs_blkfree(&tip, bn, bsize);
2172 blocksreleased += btodb(bsize);
2176 if (freeblks->fb_chkcnt != blocksreleased)
2177 kprintf("handle_workitem_freeblocks: block count\n");
2179 softdep_error("handle_workitem_freeblks", allerror);
2180 #endif /* DIAGNOSTIC */
2181 WORKITEM_FREE(freeblks, D_FREEBLKS);
2185 * Release blocks associated with the inode ip and stored in the indirect
2186 * block at doffset. If level is greater than SINGLE, the block is an
2187 * indirect block and recursive calls to indirtrunc must be used to
2188 * cleanse other indirect blocks.
2191 indir_trunc(struct inode *ip, off_t doffset, int level, ufs_lbn_t lbn,
2198 struct worklist *wk;
2199 struct indirdep *indirdep;
2200 int i, lbnadd, nblocks;
2201 int error, allerror = 0;
2205 for (i = level; i > 0; i--)
2206 lbnadd *= NINDIR(fs);
2208 * Get buffer of block pointers to be freed. This routine is not
2209 * called until the zero'ed inode has been written, so it is safe
2210 * to free blocks as they are encountered. Because the inode has
2211 * been zero'ed, calls to bmap on these blocks will fail. So, we
2212 * have to use the on-disk address and the block device for the
2213 * filesystem to look them up. If the file was deleted before its
2214 * indirect blocks were all written to disk, the routine that set
2215 * us up (deallocate_dependencies) will have arranged to leave
2216 * a complete copy of the indirect block in memory for our use.
2217 * Otherwise we have to read the blocks in from the disk.
2220 if ((bp = findblk(ip->i_devvp, doffset, FINDBLK_TEST)) != NULL &&
2221 (wk = LIST_FIRST(&bp->b_dep)) != NULL) {
2223 * bp must be ir_savebp, which is held locked for our use.
2225 if (wk->wk_type != D_INDIRDEP ||
2226 (indirdep = WK_INDIRDEP(wk))->ir_savebp != bp ||
2227 (indirdep->ir_state & GOINGAWAY) == 0) {
2228 panic("indir_trunc: lost indirdep");
2230 WORKLIST_REMOVE(wk);
2231 WORKITEM_FREE(indirdep, D_INDIRDEP);
2232 if (LIST_FIRST(&bp->b_dep) != NULL) {
2233 panic("indir_trunc: dangling dep");
2238 error = bread(ip->i_devvp, doffset, (int)fs->fs_bsize, &bp);
2243 * Recursively free indirect blocks.
2245 bap = (ufs_daddr_t *)bp->b_data;
2246 nblocks = btodb(fs->fs_bsize);
2247 for (i = NINDIR(fs) - 1; i >= 0; i--) {
2248 if ((nb = bap[i]) == 0)
2251 if ((error = indir_trunc(ip, fsbtodoff(fs, nb),
2252 level - 1, lbn + (i * lbnadd), countp)) != 0)
2255 ffs_blkfree(ip, nb, fs->fs_bsize);
2258 bp->b_flags |= B_INVAL | B_NOCACHE;
2264 * Free an allocindir.
2265 * This routine must be called with splbio interrupts blocked.
2268 free_allocindir(struct allocindir *aip, struct inodedep *inodedep)
2270 struct freefrag *freefrag;
2272 KKASSERT(lock_held(&lk) > 0);
2274 if ((aip->ai_state & DEPCOMPLETE) == 0)
2275 LIST_REMOVE(aip, ai_deps);
2276 if (aip->ai_state & ONWORKLIST)
2277 WORKLIST_REMOVE(&aip->ai_list);
2278 LIST_REMOVE(aip, ai_next);
2279 if ((freefrag = aip->ai_freefrag) != NULL) {
2280 if (inodedep == NULL)
2281 add_to_worklist(&freefrag->ff_list);
2283 WORKLIST_INSERT(&inodedep->id_bufwait,
2284 &freefrag->ff_list);
2286 WORKITEM_FREE(aip, D_ALLOCINDIR);
2290 * Directory entry addition dependencies.
2292 * When adding a new directory entry, the inode (with its incremented link
2293 * count) must be written to disk before the directory entry's pointer to it.
2294 * Also, if the inode is newly allocated, the corresponding freemap must be
2295 * updated (on disk) before the directory entry's pointer. These requirements
2296 * are met via undo/redo on the directory entry's pointer, which consists
2297 * simply of the inode number.
2299 * As directory entries are added and deleted, the free space within a
2300 * directory block can become fragmented. The ufs filesystem will compact
2301 * a fragmented directory block to make space for a new entry. When this
2302 * occurs, the offsets of previously added entries change. Any "diradd"
2303 * dependency structures corresponding to these entries must be updated with
2308 * This routine is called after the in-memory inode's link
2309 * count has been incremented, but before the directory entry's
2310 * pointer to the inode has been set.
2313 * bp: buffer containing directory block
2314 * dp: inode for directory
2315 * diroffset: offset of new entry in directory
2316 * newinum: inode referenced by new directory entry
2317 * newdirbp: non-NULL => contents of new mkdir
2320 softdep_setup_directory_add(struct buf *bp, struct inode *dp, off_t diroffset,
2321 ino_t newinum, struct buf *newdirbp)
2323 int offset; /* offset of new entry within directory block */
2324 ufs_lbn_t lbn; /* block in directory containing new entry */
2327 struct pagedep *pagedep;
2328 struct inodedep *inodedep;
2329 struct mkdir *mkdir1, *mkdir2;
2332 * Whiteouts have no dependencies.
2334 if (newinum == WINO) {
2335 if (newdirbp != NULL)
2341 lbn = lblkno(fs, diroffset);
2342 offset = blkoff(fs, diroffset);
2343 dap = kmalloc(sizeof(struct diradd), M_DIRADD,
2344 M_SOFTDEP_FLAGS | M_ZERO);
2345 dap->da_list.wk_type = D_DIRADD;
2346 dap->da_offset = offset;
2347 dap->da_newinum = newinum;
2348 dap->da_state = ATTACHED;
2349 if (newdirbp == NULL) {
2350 dap->da_state |= DEPCOMPLETE;
2353 dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
2354 mkdir1 = kmalloc(sizeof(struct mkdir), M_MKDIR,
2356 mkdir1->md_list.wk_type = D_MKDIR;
2357 mkdir1->md_state = MKDIR_BODY;
2358 mkdir1->md_diradd = dap;
2359 mkdir2 = kmalloc(sizeof(struct mkdir), M_MKDIR,
2361 mkdir2->md_list.wk_type = D_MKDIR;
2362 mkdir2->md_state = MKDIR_PARENT;
2363 mkdir2->md_diradd = dap;
2365 * Dependency on "." and ".." being written to disk.
2367 mkdir1->md_buf = newdirbp;
2369 LIST_INSERT_HEAD(&mkdirlisthd, mkdir1, md_mkdirs);
2370 WORKLIST_INSERT_BP(newdirbp, &mkdir1->md_list);
2374 * Dependency on link count increase for parent directory
2377 if (inodedep_lookup(dp->i_fs, dp->i_number, 0, &inodedep) == 0
2378 || (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2379 dap->da_state &= ~MKDIR_PARENT;
2380 WORKITEM_FREE(mkdir2, D_MKDIR);
2382 LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
2383 WORKLIST_INSERT(&inodedep->id_bufwait,&mkdir2->md_list);
2387 * Link into parent directory pagedep to await its being written.
2389 if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2390 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
2391 dap->da_pagedep = pagedep;
2392 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
2395 * Link into its inodedep. Put it on the id_bufwait list if the inode
2396 * is not yet written. If it is written, do the post-inode write
2397 * processing to put it on the id_pendinghd list.
2399 (void) inodedep_lookup(fs, newinum, DEPALLOC, &inodedep);
2400 if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
2401 diradd_inode_written(dap, inodedep);
2403 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2408 * This procedure is called to change the offset of a directory
2409 * entry when compacting a directory block which must be owned
2410 * exclusively by the caller. Note that the actual entry movement
2411 * must be done in this procedure to ensure that no I/O completions
2412 * occur while the move is in progress.
2415 * dp: inode for directory
2416 * base: address of dp->i_offset
2417 * oldloc: address of old directory location
2418 * newloc: address of new directory location
2419 * entrysize: size of directory entry
2422 softdep_change_directoryentry_offset(struct inode *dp, caddr_t base,
2423 caddr_t oldloc, caddr_t newloc,
2426 int offset, oldoffset, newoffset;
2427 struct pagedep *pagedep;
2432 lbn = lblkno(dp->i_fs, dp->i_offset);
2433 offset = blkoff(dp->i_fs, dp->i_offset);
2434 if (pagedep_lookup(dp, lbn, 0, &pagedep) == 0)
2436 oldoffset = offset + (oldloc - base);
2437 newoffset = offset + (newloc - base);
2439 LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(oldoffset)], da_pdlist) {
2440 if (dap->da_offset != oldoffset)
2442 dap->da_offset = newoffset;
2443 if (DIRADDHASH(newoffset) == DIRADDHASH(oldoffset))
2445 LIST_REMOVE(dap, da_pdlist);
2446 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(newoffset)],
2452 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist) {
2453 if (dap->da_offset == oldoffset) {
2454 dap->da_offset = newoffset;
2460 bcopy(oldloc, newloc, entrysize);
2465 * Free a diradd dependency structure. This routine must be called
2466 * with splbio interrupts blocked.
2469 free_diradd(struct diradd *dap)
2471 struct dirrem *dirrem;
2472 struct pagedep *pagedep;
2473 struct inodedep *inodedep;
2474 struct mkdir *mkdir, *nextmd;
2476 KKASSERT(lock_held(&lk) > 0);
2478 WORKLIST_REMOVE(&dap->da_list);
2479 LIST_REMOVE(dap, da_pdlist);
2480 if ((dap->da_state & DIRCHG) == 0) {
2481 pagedep = dap->da_pagedep;
2483 dirrem = dap->da_previous;
2484 pagedep = dirrem->dm_pagedep;
2485 dirrem->dm_dirinum = pagedep->pd_ino;
2486 add_to_worklist(&dirrem->dm_list);
2488 if (inodedep_lookup(VFSTOUFS(pagedep->pd_mnt)->um_fs, dap->da_newinum,
2490 (void) free_inodedep(inodedep);
2491 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
2492 for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
2493 nextmd = LIST_NEXT(mkdir, md_mkdirs);
2494 if (mkdir->md_diradd != dap)
2496 dap->da_state &= ~mkdir->md_state;
2497 WORKLIST_REMOVE(&mkdir->md_list);
2498 LIST_REMOVE(mkdir, md_mkdirs);
2499 WORKITEM_FREE(mkdir, D_MKDIR);
2501 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
2502 panic("free_diradd: unfound ref");
2505 WORKITEM_FREE(dap, D_DIRADD);
2509 * Directory entry removal dependencies.
2511 * When removing a directory entry, the entry's inode pointer must be
2512 * zero'ed on disk before the corresponding inode's link count is decremented
2513 * (possibly freeing the inode for re-use). This dependency is handled by
2514 * updating the directory entry but delaying the inode count reduction until
2515 * after the directory block has been written to disk. After this point, the
2516 * inode count can be decremented whenever it is convenient.
2520 * This routine should be called immediately after removing
2521 * a directory entry. The inode's link count should not be
2522 * decremented by the calling procedure -- the soft updates
2523 * code will do this task when it is safe.
2526 * bp: buffer containing directory block
2527 * dp: inode for the directory being modified
2528 * ip: inode for directory entry being removed
2529 * isrmdir: indicates if doing RMDIR
2532 softdep_setup_remove(struct buf *bp, struct inode *dp, struct inode *ip,
2535 struct dirrem *dirrem, *prevdirrem;
2538 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.
2540 dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
2543 * If the COMPLETE flag is clear, then there were no active
2544 * entries and we want to roll back to a zeroed entry until
2545 * the new inode is committed to disk. If the COMPLETE flag is
2546 * set then we have deleted an entry that never made it to
2547 * disk. If the entry we deleted resulted from a name change,
2548 * then the old name still resides on disk. We cannot delete
2549 * its inode (returned to us in prevdirrem) until the zeroed
2550 * directory entry gets to disk. The new inode has never been
2551 * referenced on the disk, so can be deleted immediately.
2553 if ((dirrem->dm_state & COMPLETE) == 0) {
2554 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
2558 if (prevdirrem != NULL)
2559 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
2560 prevdirrem, dm_next);
2561 dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
2563 handle_workitem_remove(dirrem);
2568 * Allocate a new dirrem if appropriate and return it along with
2569 * its associated pagedep. Called without a lock, returns with lock.
2571 static long num_dirrem; /* number of dirrem allocated */
2575 * bp: buffer containing directory block
2576 * dp: inode for the directory being modified
2577 * ip: inode for directory entry being removed
2578 * isrmdir: indicates if doing RMDIR
2579 * prevdirremp: previously referenced inode, if any
2581 static struct dirrem *
2582 newdirrem(struct buf *bp, struct inode *dp, struct inode *ip,
2583 int isrmdir, struct dirrem **prevdirremp)
2588 struct dirrem *dirrem;
2589 struct pagedep *pagedep;
2592 * Whiteouts have no deletion dependencies.
2595 panic("newdirrem: whiteout");
2597 * If we are over our limit, try to improve the situation.
2598 * Limiting the number of dirrem structures will also limit
2599 * the number of freefile and freeblks structures.
2601 if (num_dirrem > max_softdeps / 2 && speedup_syncer() == 0) {
2603 request_cleanup(FLUSH_REMOVE);
2608 dirrem = kmalloc(sizeof(struct dirrem), M_DIRREM,
2609 M_SOFTDEP_FLAGS | M_ZERO);
2610 dirrem->dm_list.wk_type = D_DIRREM;
2611 dirrem->dm_state = isrmdir ? RMDIR : 0;
2612 dirrem->dm_mnt = ITOV(ip)->v_mount;
2613 dirrem->dm_oldinum = ip->i_number;
2614 *prevdirremp = NULL;
2617 lbn = lblkno(dp->i_fs, dp->i_offset);
2618 offset = blkoff(dp->i_fs, dp->i_offset);
2619 if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2620 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
2621 dirrem->dm_pagedep = pagedep;
2623 * Check for a diradd dependency for the same directory entry.
2624 * If present, then both dependencies become obsolete and can
2625 * be de-allocated. Check for an entry on both the pd_dirraddhd
2626 * list and the pd_pendinghd list.
2629 LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
2630 if (dap->da_offset == offset)
2634 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
2635 if (dap->da_offset == offset)
2641 * Must be ATTACHED at this point.
2643 if ((dap->da_state & ATTACHED) == 0) {
2644 panic("newdirrem: not ATTACHED");
2646 if (dap->da_newinum != ip->i_number) {
2647 panic("newdirrem: inum %"PRId64" should be %"PRId64,
2648 ip->i_number, dap->da_newinum);
2651 * If we are deleting a changed name that never made it to disk,
2652 * then return the dirrem describing the previous inode (which
2653 * represents the inode currently referenced from this entry on disk).
2655 if ((dap->da_state & DIRCHG) != 0) {
2656 *prevdirremp = dap->da_previous;
2657 dap->da_state &= ~DIRCHG;
2658 dap->da_pagedep = pagedep;
2661 * We are deleting an entry that never made it to disk.
2662 * Mark it COMPLETE so we can delete its inode immediately.
2664 dirrem->dm_state |= COMPLETE;
2670 * Directory entry change dependencies.
2672 * Changing an existing directory entry requires that an add operation
2673 * be completed first followed by a deletion. The semantics for the addition
2674 * are identical to the description of adding a new entry above except
2675 * that the rollback is to the old inode number rather than zero. Once
2676 * the addition dependency is completed, the removal is done as described
2677 * in the removal routine above.
2681 * This routine should be called immediately after changing
2682 * a directory entry. The inode's link count should not be
2683 * decremented by the calling procedure -- the soft updates
2684 * code will perform this task when it is safe.
2687 * bp: buffer containing directory block
2688 * dp: inode for the directory being modified
2689 * ip: inode for directory entry being removed
2690 * newinum: new inode number for changed entry
2691 * isrmdir: indicates if doing RMDIR
2694 softdep_setup_directory_change(struct buf *bp, struct inode *dp,
2695 struct inode *ip, ino_t newinum,
2699 struct diradd *dap = NULL;
2700 struct dirrem *dirrem, *prevdirrem;
2701 struct pagedep *pagedep;
2702 struct inodedep *inodedep;
2704 offset = blkoff(dp->i_fs, dp->i_offset);
2707 * Whiteouts do not need diradd dependencies.
2709 if (newinum != WINO) {
2710 dap = kmalloc(sizeof(struct diradd), M_DIRADD,
2711 M_SOFTDEP_FLAGS | M_ZERO);
2712 dap->da_list.wk_type = D_DIRADD;
2713 dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
2714 dap->da_offset = offset;
2715 dap->da_newinum = newinum;
2719 * Allocate a new dirrem and ACQUIRE_LOCK.
2721 dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
2722 pagedep = dirrem->dm_pagedep;
2724 * The possible values for isrmdir:
2725 * 0 - non-directory file rename
2726 * 1 - directory rename within same directory
2727 * inum - directory rename to new directory of given inode number
2728 * When renaming to a new directory, we are both deleting and
2729 * creating a new directory entry, so the link count on the new
2730 * directory should not change. Thus we do not need the followup
2731 * dirrem which is usually done in handle_workitem_remove. We set
2732 * the DIRCHG flag to tell handle_workitem_remove to skip the
2736 dirrem->dm_state |= DIRCHG;
2739 * Whiteouts have no additional dependencies,
2740 * so just put the dirrem on the correct list.
2742 if (newinum == WINO) {
2743 if ((dirrem->dm_state & COMPLETE) == 0) {
2744 LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
2747 dirrem->dm_dirinum = pagedep->pd_ino;
2748 add_to_worklist(&dirrem->dm_list);
2755 * If the COMPLETE flag is clear, then there were no active
2756 * entries and we want to roll back to the previous inode until
2757 * the new inode is committed to disk. If the COMPLETE flag is
2758 * set, then we have deleted an entry that never made it to disk.
2759 * If the entry we deleted resulted from a name change, then the old
2760 * inode reference still resides on disk. Any rollback that we do
2761 * needs to be to that old inode (returned to us in prevdirrem). If
2762 * the entry we deleted resulted from a create, then there is
2763 * no entry on the disk, so we want to roll back to zero rather
2764 * than the uncommitted inode. In either of the COMPLETE cases we
2765 * want to immediately free the unwritten and unreferenced inode.
2767 if ((dirrem->dm_state & COMPLETE) == 0) {
2768 dap->da_previous = dirrem;
2770 if (prevdirrem != NULL) {
2771 dap->da_previous = prevdirrem;
2773 dap->da_state &= ~DIRCHG;
2774 dap->da_pagedep = pagedep;
2776 dirrem->dm_dirinum = pagedep->pd_ino;
2777 add_to_worklist(&dirrem->dm_list);
2780 * Link into its inodedep. Put it on the id_bufwait list if the inode
2781 * is not yet written. If it is written, do the post-inode write
2782 * processing to put it on the id_pendinghd list.
2784 if (inodedep_lookup(dp->i_fs, newinum, DEPALLOC, &inodedep) == 0 ||
2785 (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2786 dap->da_state |= COMPLETE;
2787 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
2788 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
2790 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
2792 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2798 * Called whenever the link count on an inode is changed.
2799 * It creates an inode dependency so that the new reference(s)
2800 * to the inode cannot be committed to disk until the updated
2801 * inode has been written.
2804 * ip: the inode with the increased link count
2807 softdep_change_linkcnt(struct inode *ip)
2809 struct inodedep *inodedep;
2812 (void) inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC, &inodedep);
2813 if (ip->i_nlink < ip->i_effnlink) {
2814 panic("softdep_change_linkcnt: bad delta");
2816 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2821 * This workitem decrements the inode's link count.
2822 * If the link count reaches zero, the file is removed.
2825 handle_workitem_remove(struct dirrem *dirrem)
2827 struct inodedep *inodedep;
2833 error = VFS_VGET(dirrem->dm_mnt, NULL, dirrem->dm_oldinum, &vp);
2835 softdep_error("handle_workitem_remove: vget", error);
2840 if ((inodedep_lookup(ip->i_fs, dirrem->dm_oldinum, 0, &inodedep)) == 0){
2841 panic("handle_workitem_remove: lost inodedep");
2844 * Normal file deletion.
2846 if ((dirrem->dm_state & RMDIR) == 0) {
2848 ip->i_flag |= IN_CHANGE;
2849 if (ip->i_nlink < ip->i_effnlink) {
2850 panic("handle_workitem_remove: bad file delta");
2852 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2856 WORKITEM_FREE(dirrem, D_DIRREM);
2860 * Directory deletion. Decrement reference count for both the
2861 * just deleted parent directory entry and the reference for ".".
2862 * Next truncate the directory to length zero. When the
2863 * truncation completes, arrange to have the reference count on
2864 * the parent decremented to account for the loss of "..".
2867 ip->i_flag |= IN_CHANGE;
2868 if (ip->i_nlink < ip->i_effnlink) {
2869 panic("handle_workitem_remove: bad dir delta");
2871 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2873 if ((error = ffs_truncate(vp, (off_t)0, 0, proc0.p_ucred)) != 0)
2874 softdep_error("handle_workitem_remove: truncate", error);
2876 * Rename a directory to a new parent. Since, we are both deleting
2877 * and creating a new directory entry, the link count on the new
2878 * directory should not change. Thus we skip the followup dirrem.
2880 if (dirrem->dm_state & DIRCHG) {
2883 WORKITEM_FREE(dirrem, D_DIRREM);
2887 * If the inodedep does not exist, then the zero'ed inode has
2888 * been written to disk. If the allocated inode has never been
2889 * written to disk, then the on-disk inode is zero'ed. In either
2890 * case we can remove the file immediately.
2893 dirrem->dm_state = 0;
2894 oldinum = dirrem->dm_oldinum;
2895 dirrem->dm_oldinum = dirrem->dm_dirinum;
2896 if (inodedep_lookup(ip->i_fs, oldinum, 0, &inodedep) == 0 ||
2897 check_inode_unwritten(inodedep)) {
2900 handle_workitem_remove(dirrem);
2903 WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
2905 ip->i_flag |= IN_CHANGE;
2911 * Inode de-allocation dependencies.
2913 * When an inode's link count is reduced to zero, it can be de-allocated. We
2914 * found it convenient to postpone de-allocation until after the inode is
2915 * written to disk with its new link count (zero). At this point, all of the
2916 * on-disk inode's block pointers are nullified and, with careful dependency
2917 * list ordering, all dependencies related to the inode will be satisfied and
2918 * the corresponding dependency structures de-allocated. So, if/when the
2919 * inode is reused, there will be no mixing of old dependencies with new
2920 * ones. This artificial dependency is set up by the block de-allocation
2921 * procedure above (softdep_setup_freeblocks) and completed by the
2922 * following procedure.
2925 handle_workitem_freefile(struct freefile *freefile)
2929 struct inodedep *idp;
2934 error = inodedep_lookup(freefile->fx_fs, freefile->fx_oldinum, 0, &idp);
2937 panic("handle_workitem_freefile: inodedep survived");
2939 tip.i_devvp = freefile->fx_devvp;
2940 tip.i_dev = freefile->fx_devvp->v_rdev;
2941 tip.i_fs = freefile->fx_fs;
2943 if ((error = ffs_freefile(&vp, freefile->fx_oldinum, freefile->fx_mode)) != 0)
2944 softdep_error("handle_workitem_freefile", error);
2945 WORKITEM_FREE(freefile, D_FREEFILE);
2949 * Helper function which unlinks marker element from work list and returns
2950 * the next element on the list.
2952 static __inline struct worklist *
2953 markernext(struct worklist *marker)
2955 struct worklist *next;
2957 next = LIST_NEXT(marker, wk_list);
2958 LIST_REMOVE(marker, wk_list);
2963 * checkread, checkwrite
2965 * bioops callback - hold io_token
2968 softdep_checkread(struct buf *bp)
2970 /* nothing to do, mp lock not needed */
2975 * bioops callback - hold io_token
2978 softdep_checkwrite(struct buf *bp)
2980 /* nothing to do, mp lock not needed */
2987 * The dependency structures constructed above are most actively used when file
2988 * system blocks are written to disk. No constraints are placed on when a
2989 * block can be written, but unsatisfied update dependencies are made safe by
2990 * modifying (or replacing) the source memory for the duration of the disk
2991 * write. When the disk write completes, the memory block is again brought
2994 * In-core inode structure reclamation.
2996 * Because there are a finite number of "in-core" inode structures, they are
2997 * reused regularly. By transferring all inode-related dependencies to the
2998 * in-memory inode block and indexing them separately (via "inodedep"s), we
2999 * can allow "in-core" inode structures to be reused at any time and avoid
3000 * any increase in contention.
3002 * Called just before entering the device driver to initiate a new disk I/O.
3003 * The buffer must be locked, thus, no I/O completion operations can occur
3004 * while we are manipulating its associated dependencies.
3006 * bioops callback - hold io_token
3009 * bp: structure describing disk write to occur
3012 softdep_disk_io_initiation(struct buf *bp)
3014 struct worklist *wk;
3015 struct worklist marker;
3016 struct indirdep *indirdep;
3019 * We only care about write operations. There should never
3020 * be dependencies for reads.
3022 if (bp->b_cmd == BUF_CMD_READ)
3023 panic("softdep_disk_io_initiation: read");
3026 marker.wk_type = D_LAST + 1; /* Not a normal workitem */
3029 * Do any necessary pre-I/O processing.
3031 for (wk = LIST_FIRST(&bp->b_dep); wk; wk = markernext(&marker)) {
3032 LIST_INSERT_AFTER(wk, &marker, wk_list);
3034 switch (wk->wk_type) {
3036 initiate_write_filepage(WK_PAGEDEP(wk), bp);
3040 initiate_write_inodeblock(WK_INODEDEP(wk), bp);
3044 indirdep = WK_INDIRDEP(wk);
3045 if (indirdep->ir_state & GOINGAWAY)
3046 panic("disk_io_initiation: indirdep gone");
3048 * If there are no remaining dependencies, this
3049 * will be writing the real pointers, so the
3050 * dependency can be freed.
3052 if (LIST_FIRST(&indirdep->ir_deplisthd) == NULL) {
3053 indirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
3054 brelse(indirdep->ir_savebp);
3055 /* inline expand WORKLIST_REMOVE(wk); */
3056 wk->wk_state &= ~ONWORKLIST;
3057 LIST_REMOVE(wk, wk_list);
3058 WORKITEM_FREE(indirdep, D_INDIRDEP);
3062 * Replace up-to-date version with safe version.
3064 indirdep->ir_saveddata = kmalloc(bp->b_bcount,
3068 indirdep->ir_state &= ~ATTACHED;
3069 indirdep->ir_state |= UNDONE;
3070 bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
3071 bcopy(indirdep->ir_savebp->b_data, bp->b_data,
3083 panic("handle_disk_io_initiation: Unexpected type %s",
3084 TYPENAME(wk->wk_type));
3092 * Called from within the procedure above to deal with unsatisfied
3093 * allocation dependencies in a directory. The buffer must be locked,
3094 * thus, no I/O completion operations can occur while we are
3095 * manipulating its associated dependencies.
3098 initiate_write_filepage(struct pagedep *pagedep, struct buf *bp)
3104 if (pagedep->pd_state & IOSTARTED) {
3106 * This can only happen if there is a driver that does not
3107 * understand chaining. Here biodone will reissue the call
3108 * to strategy for the incomplete buffers.
3110 kprintf("initiate_write_filepage: already started\n");
3113 pagedep->pd_state |= IOSTARTED;
3115 for (i = 0; i < DAHASHSZ; i++) {
3116 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
3117 ep = (struct direct *)
3118 ((char *)bp->b_data + dap->da_offset);
3119 if (ep->d_ino != dap->da_newinum) {
3120 panic("%s: dir inum %d != new %"PRId64,
3121 "initiate_write_filepage",
3122 ep->d_ino, dap->da_newinum);
3124 if (dap->da_state & DIRCHG)
3125 ep->d_ino = dap->da_previous->dm_oldinum;
3128 dap->da_state &= ~ATTACHED;
3129 dap->da_state |= UNDONE;
3136 * Called from within the procedure above to deal with unsatisfied
3137 * allocation dependencies in an inodeblock. The buffer must be
3138 * locked, thus, no I/O completion operations can occur while we
3139 * are manipulating its associated dependencies.
3142 * bp: The inode block
3145 initiate_write_inodeblock(struct inodedep *inodedep, struct buf *bp)
3147 struct allocdirect *adp, *lastadp;
3148 struct ufs1_dinode *dp;
3149 struct ufs1_dinode *sip;
3151 ufs_lbn_t prevlbn = 0;
3154 if (inodedep->id_state & IOSTARTED)
3155 panic("initiate_write_inodeblock: already started");
3156 inodedep->id_state |= IOSTARTED;
3157 fs = inodedep->id_fs;
3158 dp = (struct ufs1_dinode *)bp->b_data +
3159 ino_to_fsbo(fs, inodedep->id_ino);
3161 * If the bitmap is not yet written, then the allocated
3162 * inode cannot be written to disk.
3164 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
3165 if (inodedep->id_savedino != NULL)
3166 panic("initiate_write_inodeblock: already doing I/O");
3167 sip = kmalloc(sizeof(struct ufs1_dinode), M_INODEDEP,
3169 inodedep->id_savedino = sip;
3170 *inodedep->id_savedino = *dp;
3171 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
3172 dp->di_gen = inodedep->id_savedino->di_gen;
3176 * If no dependencies, then there is nothing to roll back.
3178 inodedep->id_savedsize = dp->di_size;
3179 if (TAILQ_FIRST(&inodedep->id_inoupdt) == NULL)
3182 * Set the dependencies to busy.
3185 for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3186 adp = TAILQ_NEXT(adp, ad_next)) {
3188 if (deplist != 0 && prevlbn >= adp->ad_lbn) {
3189 panic("softdep_write_inodeblock: lbn order");
3191 prevlbn = adp->ad_lbn;
3192 if (adp->ad_lbn < NDADDR &&
3193 dp->di_db[adp->ad_lbn] != adp->ad_newblkno) {
3194 panic("%s: direct pointer #%ld mismatch %d != %d",
3195 "softdep_write_inodeblock", adp->ad_lbn,
3196 dp->di_db[adp->ad_lbn], adp->ad_newblkno);
3198 if (adp->ad_lbn >= NDADDR &&
3199 dp->di_ib[adp->ad_lbn - NDADDR] != adp->ad_newblkno) {
3200 panic("%s: indirect pointer #%ld mismatch %d != %d",
3201 "softdep_write_inodeblock", adp->ad_lbn - NDADDR,
3202 dp->di_ib[adp->ad_lbn - NDADDR], adp->ad_newblkno);
3204 deplist |= 1 << adp->ad_lbn;
3205 if ((adp->ad_state & ATTACHED) == 0) {
3206 panic("softdep_write_inodeblock: Unknown state 0x%x",
3209 #endif /* DIAGNOSTIC */
3210 adp->ad_state &= ~ATTACHED;
3211 adp->ad_state |= UNDONE;
3214 * The on-disk inode cannot claim to be any larger than the last
3215 * fragment that has been written. Otherwise, the on-disk inode
3216 * might have fragments that were not the last block in the file
3217 * which would corrupt the filesystem.
3219 for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3220 lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
3221 if (adp->ad_lbn >= NDADDR)
3223 dp->di_db[adp->ad_lbn] = adp->ad_oldblkno;
3224 /* keep going until hitting a rollback to a frag */
3225 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
3227 dp->di_size = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
3228 for (i = adp->ad_lbn + 1; i < NDADDR; i++) {
3230 if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0) {
3231 panic("softdep_write_inodeblock: lost dep1");
3233 #endif /* DIAGNOSTIC */
3236 for (i = 0; i < NIADDR; i++) {
3238 if (dp->di_ib[i] != 0 &&
3239 (deplist & ((1 << NDADDR) << i)) == 0) {
3240 panic("softdep_write_inodeblock: lost dep2");
3242 #endif /* DIAGNOSTIC */
3249 * If we have zero'ed out the last allocated block of the file,
3250 * roll back the size to the last currently allocated block.
3251 * We know that this last allocated block is a full-sized as
3252 * we already checked for fragments in the loop above.
3254 if (lastadp != NULL &&
3255 dp->di_size <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
3256 for (i = lastadp->ad_lbn; i >= 0; i--)
3257 if (dp->di_db[i] != 0)
3259 dp->di_size = (i + 1) * fs->fs_bsize;
3262 * The only dependencies are for indirect blocks.
3264 * The file size for indirect block additions is not guaranteed.
3265 * Such a guarantee would be non-trivial to achieve. The conventional
3266 * synchronous write implementation also does not make this guarantee.
3267 * Fsck should catch and fix discrepancies. Arguably, the file size
3268 * can be over-estimated without destroying integrity when the file
3269 * moves into the indirect blocks (i.e., is large). If we want to
3270 * postpone fsck, we are stuck with this argument.
3272 for (; adp; adp = TAILQ_NEXT(adp, ad_next))
3273 dp->di_ib[adp->ad_lbn - NDADDR] = 0;
3278 * This routine is called during the completion interrupt
3279 * service routine for a disk write (from the procedure called
3280 * by the device driver to inform the filesystem caches of
3281 * a request completion). It should be called early in this
3282 * procedure, before the block is made available to other
3283 * processes or other routines are called.
3285 * bioops callback - hold io_token
3288 * bp: describes the completed disk write
3291 softdep_disk_write_complete(struct buf *bp)
3293 struct worklist *wk;
3294 struct workhead reattach;
3295 struct newblk *newblk;
3296 struct allocindir *aip;
3297 struct allocdirect *adp;
3298 struct indirdep *indirdep;
3299 struct inodedep *inodedep;
3300 struct bmsafemap *bmsafemap;
3304 LIST_INIT(&reattach);
3305 while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
3306 WORKLIST_REMOVE(wk);
3307 switch (wk->wk_type) {
3310 if (handle_written_filepage(WK_PAGEDEP(wk), bp))
3311 WORKLIST_INSERT(&reattach, wk);
3315 if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
3316 WORKLIST_INSERT(&reattach, wk);
3320 bmsafemap = WK_BMSAFEMAP(wk);
3321 while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkhd))) {
3322 newblk->nb_state |= DEPCOMPLETE;
3323 newblk->nb_bmsafemap = NULL;
3324 LIST_REMOVE(newblk, nb_deps);
3327 LIST_FIRST(&bmsafemap->sm_allocdirecthd))) {
3328 adp->ad_state |= DEPCOMPLETE;
3330 LIST_REMOVE(adp, ad_deps);
3331 handle_allocdirect_partdone(adp);
3334 LIST_FIRST(&bmsafemap->sm_allocindirhd))) {
3335 aip->ai_state |= DEPCOMPLETE;
3337 LIST_REMOVE(aip, ai_deps);
3338 handle_allocindir_partdone(aip);
3341 LIST_FIRST(&bmsafemap->sm_inodedephd)) != NULL) {
3342 inodedep->id_state |= DEPCOMPLETE;
3343 LIST_REMOVE(inodedep, id_deps);
3344 inodedep->id_buf = NULL;
3346 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
3350 handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
3354 adp = WK_ALLOCDIRECT(wk);
3355 adp->ad_state |= COMPLETE;
3356 handle_allocdirect_partdone(adp);
3360 aip = WK_ALLOCINDIR(wk);
3361 aip->ai_state |= COMPLETE;
3362 handle_allocindir_partdone(aip);
3366 indirdep = WK_INDIRDEP(wk);
3367 if (indirdep->ir_state & GOINGAWAY) {
3368 panic("disk_write_complete: indirdep gone");
3370 bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
3371 kfree(indirdep->ir_saveddata, M_INDIRDEP);
3372 indirdep->ir_saveddata = NULL;
3373 indirdep->ir_state &= ~UNDONE;
3374 indirdep->ir_state |= ATTACHED;
3375 while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
3376 handle_allocindir_partdone(aip);
3377 if (aip == LIST_FIRST(&indirdep->ir_donehd)) {
3378 panic("disk_write_complete: not gone");
3381 WORKLIST_INSERT(&reattach, wk);
3382 if ((bp->b_flags & B_DELWRI) == 0)
3383 stat_indir_blk_ptrs++;
3388 panic("handle_disk_write_complete: Unknown type %s",
3389 TYPENAME(wk->wk_type));
3394 * Reattach any requests that must be redone.
3396 while ((wk = LIST_FIRST(&reattach)) != NULL) {
3397 WORKLIST_REMOVE(wk);
3398 WORKLIST_INSERT_BP(bp, wk);
3405 * Called from within softdep_disk_write_complete above. Note that
3406 * this routine is always called from interrupt level with further
3407 * splbio interrupts blocked.
3410 * adp: the completed allocdirect
3413 handle_allocdirect_partdone(struct allocdirect *adp)
3415 struct allocdirect *listadp;
3416 struct inodedep *inodedep;
3419 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3421 if (adp->ad_buf != NULL)
3422 panic("handle_allocdirect_partdone: dangling dep");
3425 * The on-disk inode cannot claim to be any larger than the last
3426 * fragment that has been written. Otherwise, the on-disk inode
3427 * might have fragments that were not the last block in the file
3428 * which would corrupt the filesystem. Thus, we cannot free any
3429 * allocdirects after one whose ad_oldblkno claims a fragment as
3430 * these blocks must be rolled back to zero before writing the inode.
3431 * We check the currently active set of allocdirects in id_inoupdt.
3433 inodedep = adp->ad_inodedep;
3434 bsize = inodedep->id_fs->fs_bsize;
3435 TAILQ_FOREACH(listadp, &inodedep->id_inoupdt, ad_next) {
3436 /* found our block */
3439 /* continue if ad_oldlbn is not a fragment */
3440 if (listadp->ad_oldsize == 0 ||
3441 listadp->ad_oldsize == bsize)
3443 /* hit a fragment */
3447 * If we have reached the end of the current list without
3448 * finding the just finished dependency, then it must be
3449 * on the future dependency list. Future dependencies cannot
3450 * be freed until they are moved to the current list.
3452 if (listadp == NULL) {
3454 TAILQ_FOREACH(listadp, &inodedep->id_newinoupdt, ad_next)
3455 /* found our block */
3458 if (listadp == NULL)
3459 panic("handle_allocdirect_partdone: lost dep");
3464 * If we have found the just finished dependency, then free
3465 * it along with anything that follows it that is complete.
3467 for (; adp; adp = listadp) {
3468 listadp = TAILQ_NEXT(adp, ad_next);
3469 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3471 free_allocdirect(&inodedep->id_inoupdt, adp, 1);
3476 * Called from within softdep_disk_write_complete above. Note that
3477 * this routine is always called from interrupt level with further
3478 * splbio interrupts blocked.
3481 * aip: the completed allocindir
3484 handle_allocindir_partdone(struct allocindir *aip)
3486 struct indirdep *indirdep;
3488 if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
3490 if (aip->ai_buf != NULL)
3491 panic("handle_allocindir_partdone: dangling dependency");
3493 indirdep = aip->ai_indirdep;
3494 if (indirdep->ir_state & UNDONE) {
3495 LIST_REMOVE(aip, ai_next);
3496 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
3499 ((ufs_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
3501 LIST_REMOVE(aip, ai_next);
3502 if (aip->ai_freefrag != NULL)
3503 add_to_worklist(&aip->ai_freefrag->ff_list);
3504 WORKITEM_FREE(aip, D_ALLOCINDIR);
3508 * Called from within softdep_disk_write_complete above to restore
3509 * in-memory inode block contents to their most up-to-date state. Note
3510 * that this routine is always called from interrupt level with further
3511 * splbio interrupts blocked.
3514 * bp: buffer containing the inode block
3517 handle_written_inodeblock(struct inodedep *inodedep, struct buf *bp)
3519 struct worklist *wk, *filefree;
3520 struct allocdirect *adp, *nextadp;
3521 struct ufs1_dinode *dp;
3524 if ((inodedep->id_state & IOSTARTED) == 0)
3525 panic("handle_written_inodeblock: not started");
3527 inodedep->id_state &= ~IOSTARTED;
3528 dp = (struct ufs1_dinode *)bp->b_data +
3529 ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
3531 * If we had to rollback the inode allocation because of
3532 * bitmaps being incomplete, then simply restore it.
3533 * Keep the block dirty so that it will not be reclaimed until
3534 * all associated dependencies have been cleared and the
3535 * corresponding updates written to disk.
3537 if (inodedep->id_savedino != NULL) {
3538 *dp = *inodedep->id_savedino;
3539 kfree(inodedep->id_savedino, M_INODEDEP);
3540 inodedep->id_savedino = NULL;
3541 if ((bp->b_flags & B_DELWRI) == 0)
3542 stat_inode_bitmap++;
3546 inodedep->id_state |= COMPLETE;
3548 * Roll forward anything that had to be rolled back before
3549 * the inode could be updated.
3552 for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
3553 nextadp = TAILQ_NEXT(adp, ad_next);
3554 if (adp->ad_state & ATTACHED)
3555 panic("handle_written_inodeblock: new entry");
3557 if (adp->ad_lbn < NDADDR) {
3558 if (dp->di_db[adp->ad_lbn] != adp->ad_oldblkno) {
3559 panic("%s: %s #%ld mismatch %d != %d",
3560 "handle_written_inodeblock",
3561 "direct pointer", adp->ad_lbn,
3562 dp->di_db[adp->ad_lbn], adp->ad_oldblkno);
3564 dp->di_db[adp->ad_lbn] = adp->ad_newblkno;
3566 if (dp->di_ib[adp->ad_lbn - NDADDR] != 0) {
3567 panic("%s: %s #%ld allocated as %d",
3568 "handle_written_inodeblock",
3569 "indirect pointer", adp->ad_lbn - NDADDR,
3570 dp->di_ib[adp->ad_lbn - NDADDR]);
3572 dp->di_ib[adp->ad_lbn - NDADDR] = adp->ad_newblkno;
3574 adp->ad_state &= ~UNDONE;
3575 adp->ad_state |= ATTACHED;
3578 if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
3579 stat_direct_blk_ptrs++;
3581 * Reset the file size to its most up-to-date value.
3583 if (inodedep->id_savedsize == -1) {
3584 panic("handle_written_inodeblock: bad size");
3586 if (dp->di_size != inodedep->id_savedsize) {
3587 dp->di_size = inodedep->id_savedsize;
3590 inodedep->id_savedsize = -1;
3592 * If there were any rollbacks in the inode block, then it must be
3593 * marked dirty so that its will eventually get written back in
3599 * Process any allocdirects that completed during the update.
3601 if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
3602 handle_allocdirect_partdone(adp);
3604 * Process deallocations that were held pending until the
3605 * inode had been written to disk. Freeing of the inode
3606 * is delayed until after all blocks have been freed to
3607 * avoid creation of new <vfsid, inum, lbn> triples
3608 * before the old ones have been deleted.
3611 while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
3612 WORKLIST_REMOVE(wk);
3613 switch (wk->wk_type) {
3617 * We defer adding filefree to the worklist until
3618 * all other additions have been made to ensure
3619 * that it will be done after all the old blocks
3622 if (filefree != NULL) {
3623 panic("handle_written_inodeblock: filefree");
3629 handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
3633 diradd_inode_written(WK_DIRADD(wk), inodedep);
3637 wk->wk_state |= COMPLETE;
3638 if ((wk->wk_state & ALLCOMPLETE) != ALLCOMPLETE)
3640 /* -- fall through -- */
3643 add_to_worklist(wk);
3647 panic("handle_written_inodeblock: Unknown type %s",
3648 TYPENAME(wk->wk_type));
3652 if (filefree != NULL) {
3653 if (free_inodedep(inodedep) == 0) {
3654 panic("handle_written_inodeblock: live inodedep");
3656 add_to_worklist(filefree);
3661 * If no outstanding dependencies, free it.
3663 if (free_inodedep(inodedep) || TAILQ_FIRST(&inodedep->id_inoupdt) == NULL)
3665 return (hadchanges);
3669 * Process a diradd entry after its dependent inode has been written.
3670 * This routine must be called with splbio interrupts blocked.
3673 diradd_inode_written(struct diradd *dap, struct inodedep *inodedep)
3675 struct pagedep *pagedep;
3677 dap->da_state |= COMPLETE;
3678 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3679 if (dap->da_state & DIRCHG)
3680 pagedep = dap->da_previous->dm_pagedep;
3682 pagedep = dap->da_pagedep;
3683 LIST_REMOVE(dap, da_pdlist);
3684 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3686 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
3690 * Handle the completion of a mkdir dependency.
3693 handle_written_mkdir(struct mkdir *mkdir, int type)
3696 struct pagedep *pagedep;
3698 if (mkdir->md_state != type) {
3699 panic("handle_written_mkdir: bad type");
3701 dap = mkdir->md_diradd;
3702 dap->da_state &= ~type;
3703 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
3704 dap->da_state |= DEPCOMPLETE;
3705 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3706 if (dap->da_state & DIRCHG)
3707 pagedep = dap->da_previous->dm_pagedep;
3709 pagedep = dap->da_pagedep;
3710 LIST_REMOVE(dap, da_pdlist);
3711 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3713 LIST_REMOVE(mkdir, md_mkdirs);
3714 WORKITEM_FREE(mkdir, D_MKDIR);
3718 * Called from within softdep_disk_write_complete above.
3719 * A write operation was just completed. Removed inodes can
3720 * now be freed and associated block pointers may be committed.
3721 * Note that this routine is always called from interrupt level
3722 * with further splbio interrupts blocked.
3725 * bp: buffer containing the written page
3728 handle_written_filepage(struct pagedep *pagedep, struct buf *bp)
3730 struct dirrem *dirrem;
3731 struct diradd *dap, *nextdap;
3735 if ((pagedep->pd_state & IOSTARTED) == 0) {
3736 panic("handle_written_filepage: not started");
3738 pagedep->pd_state &= ~IOSTARTED;
3740 * Process any directory removals that have been committed.
3742 while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
3743 LIST_REMOVE(dirrem, dm_next);
3744 dirrem->dm_dirinum = pagedep->pd_ino;
3745 add_to_worklist(&dirrem->dm_list);
3748 * Free any directory additions that have been committed.
3750 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
3753 * Uncommitted directory entries must be restored.
3755 for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
3756 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
3758 nextdap = LIST_NEXT(dap, da_pdlist);
3759 if (dap->da_state & ATTACHED) {
3760 panic("handle_written_filepage: attached");
3762 ep = (struct direct *)
3763 ((char *)bp->b_data + dap->da_offset);
3764 ep->d_ino = dap->da_newinum;
3765 dap->da_state &= ~UNDONE;
3766 dap->da_state |= ATTACHED;
3769 * If the inode referenced by the directory has
3770 * been written out, then the dependency can be
3771 * moved to the pending list.
3773 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3774 LIST_REMOVE(dap, da_pdlist);
3775 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
3781 * If there were any rollbacks in the directory, then it must be
3782 * marked dirty so that its will eventually get written back in
3786 if ((bp->b_flags & B_DELWRI) == 0)
3791 * If no dependencies remain, the pagedep will be freed.
3792 * Otherwise it will remain to update the page before it
3793 * is written back to disk.
3795 if (LIST_FIRST(&pagedep->pd_pendinghd) == NULL) {
3796 for (i = 0; i < DAHASHSZ; i++)
3797 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) != NULL)
3799 if (i == DAHASHSZ) {
3800 LIST_REMOVE(pagedep, pd_hash);
3801 WORKITEM_FREE(pagedep, D_PAGEDEP);
3809 * Writing back in-core inode structures.
3811 * The filesystem only accesses an inode's contents when it occupies an
3812 * "in-core" inode structure. These "in-core" structures are separate from
3813 * the page frames used to cache inode blocks. Only the latter are
3814 * transferred to/from the disk. So, when the updated contents of the
3815 * "in-core" inode structure are copied to the corresponding in-memory inode
3816 * block, the dependencies are also transferred. The following procedure is
3817 * called when copying a dirty "in-core" inode to a cached inode block.
3821 * Called when an inode is loaded from disk. If the effective link count
3822 * differed from the actual link count when it was last flushed, then we
3823 * need to ensure that the correct effective link count is put back.
3826 * ip: the "in_core" copy of the inode
3829 softdep_load_inodeblock(struct inode *ip)
3831 struct inodedep *inodedep;
3834 * Check for alternate nlink count.
3836 ip->i_effnlink = ip->i_nlink;
3838 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3842 ip->i_effnlink -= inodedep->id_nlinkdelta;
3847 * This routine is called just before the "in-core" inode
3848 * information is to be copied to the in-memory inode block.
3849 * Recall that an inode block contains several inodes. If
3850 * the force flag is set, then the dependencies will be
3851 * cleared so that the update can always be made. Note that
3852 * the buffer is locked when this routine is called, so we
3853 * will never be in the middle of writing the inode block
3857 * ip: the "in_core" copy of the inode
3858 * bp: the buffer containing the inode block
3859 * waitfor: nonzero => update must be allowed
3862 softdep_update_inodeblock(struct inode *ip, struct buf *bp,
3865 struct inodedep *inodedep;
3866 struct worklist *wk;
3871 * If the effective link count is not equal to the actual link
3872 * count, then we must track the difference in an inodedep while
3873 * the inode is (potentially) tossed out of the cache. Otherwise,
3874 * if there is no existing inodedep, then there are no dependencies
3878 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3880 if (ip->i_effnlink != ip->i_nlink)
3881 panic("softdep_update_inodeblock: bad link count");
3884 if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink) {
3885 panic("softdep_update_inodeblock: bad delta");
3888 * Changes have been initiated. Anything depending on these
3889 * changes cannot occur until this inode has been written.
3891 inodedep->id_state &= ~COMPLETE;
3892 if ((inodedep->id_state & ONWORKLIST) == 0)
3893 WORKLIST_INSERT_BP(bp, &inodedep->id_list);
3895 * Any new dependencies associated with the incore inode must
3896 * now be moved to the list associated with the buffer holding
3897 * the in-memory copy of the inode. Once merged process any
3898 * allocdirects that are completed by the merger.
3900 merge_inode_lists(inodedep);
3901 if (TAILQ_FIRST(&inodedep->id_inoupdt) != NULL)
3902 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt));
3904 * Now that the inode has been pushed into the buffer, the
3905 * operations dependent on the inode being written to disk
3906 * can be moved to the id_bufwait so that they will be
3907 * processed when the buffer I/O completes.
3909 while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
3910 WORKLIST_REMOVE(wk);
3911 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
3914 * Newly allocated inodes cannot be written until the bitmap
3915 * that allocates them have been written (indicated by
3916 * DEPCOMPLETE being set in id_state). If we are doing a
3917 * forced sync (e.g., an fsync on a file), we force the bitmap
3918 * to be written so that the update can be done.
3925 if ((inodedep->id_state & DEPCOMPLETE) != 0) {
3929 gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
3931 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) != 0)
3936 ibp = inodedep->id_buf;
3938 if ((error = bwrite(ibp)) != 0)
3939 softdep_error("softdep_update_inodeblock: bwrite", error);
3943 * Merge the new inode dependency list (id_newinoupdt) into the old
3944 * inode dependency list (id_inoupdt). This routine must be called
3945 * with splbio interrupts blocked.
3948 merge_inode_lists(struct inodedep *inodedep)
3950 struct allocdirect *listadp, *newadp;
3952 newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3953 for (listadp = TAILQ_FIRST(&inodedep->id_inoupdt); listadp && newadp;) {
3954 if (listadp->ad_lbn < newadp->ad_lbn) {
3955 listadp = TAILQ_NEXT(listadp, ad_next);
3958 TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3959 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
3960 if (listadp->ad_lbn == newadp->ad_lbn) {
3961 allocdirect_merge(&inodedep->id_inoupdt, newadp,
3965 newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3967 while ((newadp = TAILQ_FIRST(&inodedep->id_newinoupdt)) != NULL) {
3968 TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3969 TAILQ_INSERT_TAIL(&inodedep->id_inoupdt, newadp, ad_next);
3974 * If we are doing an fsync, then we must ensure that any directory
3975 * entries for the inode have been written after the inode gets to disk.
3977 * bioops callback - hold io_token
3980 * vp: the "in_core" copy of the inode
3983 softdep_fsync(struct vnode *vp)
3985 struct inodedep *inodedep;
3986 struct pagedep *pagedep;
3987 struct worklist *wk;
3994 int error, flushparent;
3999 * Move check from original kernel code, possibly not needed any
4000 * more with the per-mount bioops.
4002 if ((vp->v_mount->mnt_flag & MNT_SOFTDEP) == 0)
4008 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0) {
4012 if (LIST_FIRST(&inodedep->id_inowait) != NULL ||
4013 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
4014 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
4015 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL) {
4016 panic("softdep_fsync: pending ops");
4018 for (error = 0, flushparent = 0; ; ) {
4019 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
4021 if (wk->wk_type != D_DIRADD) {
4022 panic("softdep_fsync: Unexpected type %s",
4023 TYPENAME(wk->wk_type));
4025 dap = WK_DIRADD(wk);
4027 * Flush our parent if this directory entry
4028 * has a MKDIR_PARENT dependency.
4030 if (dap->da_state & DIRCHG)
4031 pagedep = dap->da_previous->dm_pagedep;
4033 pagedep = dap->da_pagedep;
4034 mnt = pagedep->pd_mnt;
4035 parentino = pagedep->pd_ino;
4036 lbn = pagedep->pd_lbn;
4037 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE) {
4038 panic("softdep_fsync: dirty");
4040 flushparent = dap->da_state & MKDIR_PARENT;
4042 * If we are being fsync'ed as part of vgone'ing this vnode,
4043 * then we will not be able to release and recover the
4044 * vnode below, so we just have to give up on writing its
4045 * directory entry out. It will eventually be written, just
4046 * not now, but then the user was not asking to have it
4047 * written, so we are not breaking any promises.
4049 if (vp->v_flag & VRECLAIMED)
4052 * We prevent deadlock by always fetching inodes from the
4053 * root, moving down the directory tree. Thus, when fetching
4054 * our parent directory, we must unlock ourselves before
4055 * requesting the lock on our parent. See the comment in
4056 * ufs_lookup for details on possible races.
4060 error = VFS_VGET(mnt, NULL, parentino, &pvp);
4061 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4066 if ((error = ffs_update(pvp, 1)) != 0) {
4072 * Flush directory page containing the inode's name.
4074 error = bread(pvp, lblktodoff(fs, lbn), blksize(fs, VTOI(pvp), lbn), &bp);
4082 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0)
4090 * Flush all the dirty bitmaps associated with the block device
4091 * before flushing the rest of the dirty blocks so as to reduce
4092 * the number of dependencies that will have to be rolled back.
4094 static int softdep_fsync_mountdev_bp(struct buf *bp, void *data);
4097 softdep_fsync_mountdev(struct vnode *vp)
4099 if (!vn_isdisk(vp, NULL))
4100 panic("softdep_fsync_mountdev: vnode not a disk");
4102 lwkt_gettoken(&vp->v_token);
4103 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
4104 softdep_fsync_mountdev_bp, vp);
4105 lwkt_reltoken(&vp->v_token);
4106 drain_output(vp, 1);
4111 softdep_fsync_mountdev_bp(struct buf *bp, void *data)
4113 struct worklist *wk;
4114 struct vnode *vp = data;
4117 * If it is already scheduled, skip to the next buffer.
4119 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT))
4121 if (bp->b_vp != vp || (bp->b_flags & B_DELWRI) == 0) {
4123 kprintf("softdep_fsync_mountdev_bp: warning, buffer %p ripped out from under vnode %p\n", bp, vp);
4127 * We are only interested in bitmaps with outstanding
4130 if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
4131 wk->wk_type != D_BMSAFEMAP) {
4143 * This routine is called when we are trying to synchronously flush a
4144 * file. This routine must eliminate any filesystem metadata dependencies
4145 * so that the syncing routine can succeed by pushing the dirty blocks
4146 * associated with the file. If any I/O errors occur, they are returned.
4148 struct softdep_sync_metadata_info {
4153 static int softdep_sync_metadata_bp(struct buf *bp, void *data);
4156 softdep_sync_metadata(struct vnode *vp, struct thread *td)
4158 struct softdep_sync_metadata_info info;
4162 * Check whether this vnode is involved in a filesystem
4163 * that is doing soft dependency processing.
4165 if (!vn_isdisk(vp, NULL)) {
4166 if (!DOINGSOFTDEP(vp))
4169 if (vp->v_rdev->si_mountpoint == NULL ||
4170 (vp->v_rdev->si_mountpoint->mnt_flag & MNT_SOFTDEP) == 0)
4173 * Ensure that any direct block dependencies have been cleared.
4176 if ((error = flush_inodedep_deps(VTOI(vp)->i_fs, VTOI(vp)->i_number))) {
4181 * For most files, the only metadata dependencies are the
4182 * cylinder group maps that allocate their inode or blocks.
4183 * The block allocation dependencies can be found by traversing
4184 * the dependency lists for any buffers that remain on their
4185 * dirty buffer list. The inode allocation dependency will
4186 * be resolved when the inode is updated with MNT_WAIT.
4187 * This work is done in two passes. The first pass grabs most
4188 * of the buffers and begins asynchronously writing them. The
4189 * only way to wait for these asynchronous writes is to sleep
4190 * on the filesystem vnode which may stay busy for a long time
4191 * if the filesystem is active. So, instead, we make a second
4192 * pass over the dependencies blocking on each write. In the
4193 * usual case we will be blocking against a write that we
4194 * initiated, so when it is done the dependency will have been
4195 * resolved. Thus the second pass is expected to end quickly.
4197 waitfor = MNT_NOWAIT;
4200 * We must wait for any I/O in progress to finish so that
4201 * all potential buffers on the dirty list will be visible.
4203 drain_output(vp, 1);
4206 info.waitfor = waitfor;
4207 lwkt_gettoken(&vp->v_token);
4208 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
4209 softdep_sync_metadata_bp, &info);
4210 lwkt_reltoken(&vp->v_token);
4213 return(-error); /* error code */
4217 * The brief unlock is to allow any pent up dependency
4218 * processing to be done. Then proceed with the second pass.
4220 if (waitfor & MNT_NOWAIT) {
4228 * If we have managed to get rid of all the dirty buffers,
4229 * then we are done. For certain directories and block
4230 * devices, we may need to do further work.
4232 * We must wait for any I/O in progress to finish so that
4233 * all potential buffers on the dirty list will be visible.
4235 drain_output(vp, 1);
4236 if (RB_EMPTY(&vp->v_rbdirty_tree)) {
4243 * If we are trying to sync a block device, some of its buffers may
4244 * contain metadata that cannot be written until the contents of some
4245 * partially written files have been written to disk. The only easy
4246 * way to accomplish this is to sync the entire filesystem (luckily
4247 * this happens rarely).
4249 if (vn_isdisk(vp, NULL) &&
4251 vp->v_rdev->si_mountpoint && !vn_islocked(vp) &&
4252 (error = VFS_SYNC(vp->v_rdev->si_mountpoint, MNT_WAIT)) != 0)
4258 softdep_sync_metadata_bp(struct buf *bp, void *data)
4260 struct softdep_sync_metadata_info *info = data;
4261 struct pagedep *pagedep;
4262 struct allocdirect *adp;
4263 struct allocindir *aip;
4264 struct worklist *wk;
4269 if (getdirtybuf(&bp, MNT_WAIT) == 0) {
4270 kprintf("softdep_sync_metadata_bp(1): caught buf %p going away\n", bp);
4273 if (bp->b_vp != info->vp || (bp->b_flags & B_DELWRI) == 0) {
4274 kprintf("softdep_sync_metadata_bp(2): caught buf %p going away vp %p\n", bp, info->vp);
4280 * As we hold the buffer locked, none of its dependencies
4283 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4284 switch (wk->wk_type) {
4287 adp = WK_ALLOCDIRECT(wk);
4288 if (adp->ad_state & DEPCOMPLETE)
4291 if (getdirtybuf(&nbp, info->waitfor) == 0)
4294 if (info->waitfor & MNT_NOWAIT) {
4296 } else if ((error = bwrite(nbp)) != 0) {
4305 aip = WK_ALLOCINDIR(wk);
4306 if (aip->ai_state & DEPCOMPLETE)
4309 if (getdirtybuf(&nbp, info->waitfor) == 0)
4312 if (info->waitfor & MNT_NOWAIT) {
4314 } else if ((error = bwrite(nbp)) != 0) {
4325 LIST_FOREACH(aip, &WK_INDIRDEP(wk)->ir_deplisthd, ai_next) {
4326 if (aip->ai_state & DEPCOMPLETE)
4329 if (getdirtybuf(&nbp, MNT_WAIT) == 0)
4332 if ((error = bwrite(nbp)) != 0) {
4343 if ((error = flush_inodedep_deps(WK_INODEDEP(wk)->id_fs,
4344 WK_INODEDEP(wk)->id_ino)) != 0) {
4354 * We are trying to sync a directory that may
4355 * have dependencies on both its own metadata
4356 * and/or dependencies on the inodes of any
4357 * recently allocated files. We walk its diradd
4358 * lists pushing out the associated inode.
4360 pagedep = WK_PAGEDEP(wk);
4361 for (i = 0; i < DAHASHSZ; i++) {
4362 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL)
4365 flush_pagedep_deps(info->vp,
4367 &pagedep->pd_diraddhd[i]))) {
4378 * This case should never happen if the vnode has
4379 * been properly sync'ed. However, if this function
4380 * is used at a place where the vnode has not yet
4381 * been sync'ed, this dependency can show up. So,
4382 * rather than panic, just flush it.
4384 nbp = WK_MKDIR(wk)->md_buf;
4385 if (getdirtybuf(&nbp, info->waitfor) == 0)
4388 if (info->waitfor & MNT_NOWAIT) {
4390 } else if ((error = bwrite(nbp)) != 0) {
4400 * This case should never happen if the vnode has
4401 * been properly sync'ed. However, if this function
4402 * is used at a place where the vnode has not yet
4403 * been sync'ed, this dependency can show up. So,
4404 * rather than panic, just flush it.
4406 * nbp can wind up == bp if a device node for the
4407 * same filesystem is being fsynced at the same time,
4408 * leading to a panic if we don't catch the case.
4410 nbp = WK_BMSAFEMAP(wk)->sm_buf;
4413 if (getdirtybuf(&nbp, info->waitfor) == 0)
4416 if (info->waitfor & MNT_NOWAIT) {
4418 } else if ((error = bwrite(nbp)) != 0) {
4427 panic("softdep_sync_metadata: Unknown type %s",
4428 TYPENAME(wk->wk_type));
4439 * Flush the dependencies associated with an inodedep.
4440 * Called with splbio blocked.
4443 flush_inodedep_deps(struct fs *fs, ino_t ino)
4445 struct inodedep *inodedep;
4446 struct allocdirect *adp;
4451 * This work is done in two passes. The first pass grabs most
4452 * of the buffers and begins asynchronously writing them. The
4453 * only way to wait for these asynchronous writes is to sleep
4454 * on the filesystem vnode which may stay busy for a long time
4455 * if the filesystem is active. So, instead, we make a second
4456 * pass over the dependencies blocking on each write. In the
4457 * usual case we will be blocking against a write that we
4458 * initiated, so when it is done the dependency will have been
4459 * resolved. Thus the second pass is expected to end quickly.
4460 * We give a brief window at the top of the loop to allow
4461 * any pending I/O to complete.
4463 for (waitfor = MNT_NOWAIT; ; ) {
4466 if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4468 TAILQ_FOREACH(adp, &inodedep->id_inoupdt, ad_next) {
4469 if (adp->ad_state & DEPCOMPLETE)
4472 if (getdirtybuf(&bp, waitfor) == 0) {
4473 if (waitfor & MNT_NOWAIT)
4478 if (waitfor & MNT_NOWAIT) {
4480 } else if ((error = bwrite(bp)) != 0) {
4489 TAILQ_FOREACH(adp, &inodedep->id_newinoupdt, ad_next) {
4490 if (adp->ad_state & DEPCOMPLETE)
4493 if (getdirtybuf(&bp, waitfor) == 0) {
4494 if (waitfor & MNT_NOWAIT)
4499 if (waitfor & MNT_NOWAIT) {
4501 } else if ((error = bwrite(bp)) != 0) {
4511 * If pass2, we are done, otherwise do pass 2.
4513 if (waitfor == MNT_WAIT)
4518 * Try freeing inodedep in case all dependencies have been removed.
4520 if (inodedep_lookup(fs, ino, 0, &inodedep) != 0)
4521 (void) free_inodedep(inodedep);
4526 * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
4527 * Called with splbio blocked.
4530 flush_pagedep_deps(struct vnode *pvp, struct mount *mp,
4531 struct diraddhd *diraddhdp)
4533 struct inodedep *inodedep;
4534 struct ufsmount *ump;
4536 struct worklist *wk;
4538 int gotit, error = 0;
4543 while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
4545 * Flush ourselves if this directory entry
4546 * has a MKDIR_PARENT dependency.
4548 if (dap->da_state & MKDIR_PARENT) {
4550 if ((error = ffs_update(pvp, 1)) != 0)
4554 * If that cleared dependencies, go on to next.
4556 if (dap != LIST_FIRST(diraddhdp))
4558 if (dap->da_state & MKDIR_PARENT) {
4559 panic("flush_pagedep_deps: MKDIR_PARENT");
4563 * A newly allocated directory must have its "." and
4564 * ".." entries written out before its name can be
4565 * committed in its parent. We do not want or need
4566 * the full semantics of a synchronous VOP_FSYNC as
4567 * that may end up here again, once for each directory
4568 * level in the filesystem. Instead, we push the blocks
4569 * and wait for them to clear. We have to fsync twice
4570 * because the first call may choose to defer blocks
4571 * that still have dependencies, but deferral will
4572 * happen at most once.
4574 inum = dap->da_newinum;
4575 if (dap->da_state & MKDIR_BODY) {
4577 if ((error = VFS_VGET(mp, NULL, inum, &vp)) != 0)
4579 if ((error=VOP_FSYNC(vp, MNT_NOWAIT, 0)) ||
4580 (error=VOP_FSYNC(vp, MNT_NOWAIT, 0))) {
4584 drain_output(vp, 0);
4586 * If first block is still dirty with a D_MKDIR
4587 * dependency then it needs to be written now.
4591 bp = findblk(vp, 0, FINDBLK_TEST);
4594 goto mkdir_body_continue;
4596 LIST_FOREACH(wk, &bp->b_dep, wk_list)
4597 if (wk->wk_type == D_MKDIR) {
4598 gotit = getdirtybuf(&bp, MNT_WAIT);
4600 if (gotit && (error = bwrite(bp)) != 0)
4601 goto mkdir_body_continue;
4606 mkdir_body_continue:
4608 /* Flushing of first block failed. */
4613 * If that cleared dependencies, go on to next.
4615 if (dap != LIST_FIRST(diraddhdp))
4617 if (dap->da_state & MKDIR_BODY) {
4618 panic("flush_pagedep_deps: %p MKDIR_BODY", dap);
4622 * Flush the inode on which the directory entry depends.
4623 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
4624 * the only remaining dependency is that the updated inode
4625 * count must get pushed to disk. The inode has already
4626 * been pushed into its inode buffer (via VOP_UPDATE) at
4627 * the time of the reference count change. So we need only
4628 * locate that buffer, ensure that there will be no rollback
4629 * caused by a bitmap dependency, then write the inode buffer.
4632 if (inodedep_lookup(ump->um_fs, inum, 0, &inodedep) == 0) {
4633 panic("flush_pagedep_deps: lost inode");
4636 * If the inode still has bitmap dependencies,
4637 * push them to disk.
4639 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4640 gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
4644 if (gotit && (error = bwrite(inodedep->id_buf)) != 0)
4647 if (dap != LIST_FIRST(diraddhdp))
4651 * If the inode is still sitting in a buffer waiting
4652 * to be written, push it to disk.
4655 if ((error = bread(ump->um_devvp,
4656 fsbtodoff(ump->um_fs, ino_to_fsba(ump->um_fs, inum)),
4657 (int)ump->um_fs->fs_bsize, &bp)) != 0)
4659 if ((error = bwrite(bp)) != 0)
4663 * If we have failed to get rid of all the dependencies
4664 * then something is seriously wrong.
4666 if (dap == LIST_FIRST(diraddhdp)) {
4667 panic("flush_pagedep_deps: flush failed");
4676 * A large burst of file addition or deletion activity can drive the
4677 * memory load excessively high. First attempt to slow things down
4678 * using the techniques below. If that fails, this routine requests
4679 * the offending operations to fall back to running synchronously
4680 * until the memory load returns to a reasonable level.
4683 softdep_slowdown(struct vnode *vp)
4685 int max_softdeps_hard;
4687 max_softdeps_hard = max_softdeps * 11 / 10;
4688 if (num_dirrem < max_softdeps_hard / 2 &&
4689 num_inodedep < max_softdeps_hard)
4691 stat_sync_limit_hit += 1;
4696 * If memory utilization has gotten too high, deliberately slow things
4697 * down and speed up the I/O processing.
4700 request_cleanup(int resource)
4702 struct thread *td = curthread; /* XXX */
4704 KKASSERT(lock_held(&lk) > 0);
4707 * We never hold up the filesystem syncer process.
4709 if (td == filesys_syncer)
4712 * First check to see if the work list has gotten backlogged.
4713 * If it has, co-opt this process to help clean up two entries.
4714 * Because this process may hold inodes locked, we cannot
4715 * handle any remove requests that might block on a locked
4716 * inode as that could lead to deadlock.
4718 if (num_on_worklist > max_softdeps / 10) {
4719 process_worklist_item(NULL, LK_NOWAIT);
4720 process_worklist_item(NULL, LK_NOWAIT);
4721 stat_worklist_push += 2;
4726 * If we are resource constrained on inode dependencies, try
4727 * flushing some dirty inodes. Otherwise, we are constrained
4728 * by file deletions, so try accelerating flushes of directories
4729 * with removal dependencies. We would like to do the cleanup
4730 * here, but we probably hold an inode locked at this point and
4731 * that might deadlock against one that we try to clean. So,
4732 * the best that we can do is request the syncer daemon to do
4733 * the cleanup for us.
4738 stat_ino_limit_push += 1;
4739 req_clear_inodedeps += 1;
4740 stat_countp = &stat_ino_limit_hit;
4744 stat_blk_limit_push += 1;
4745 req_clear_remove += 1;
4746 stat_countp = &stat_blk_limit_hit;
4750 panic("request_cleanup: unknown type");
4753 * Hopefully the syncer daemon will catch up and awaken us.
4754 * We wait at most tickdelay before proceeding in any case.
4756 lksleep(&proc_waiting, &lk, 0, "softupdate",
4757 tickdelay > 2 ? tickdelay : 2);
4762 * Flush out a directory with at least one removal dependency in an effort to
4763 * reduce the number of dirrem, freefile, and freeblks dependency structures.
4766 clear_remove(struct thread *td)
4768 struct pagedep_hashhead *pagedephd;
4769 struct pagedep *pagedep;
4770 static int next = 0;
4777 for (cnt = 0; cnt < pagedep_hash; cnt++) {
4778 pagedephd = &pagedep_hashtbl[next++];
4779 if (next >= pagedep_hash)
4781 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
4782 if (LIST_FIRST(&pagedep->pd_dirremhd) == NULL)
4784 mp = pagedep->pd_mnt;
4785 ino = pagedep->pd_ino;
4787 if ((error = VFS_VGET(mp, NULL, ino, &vp)) != 0) {
4788 softdep_error("clear_remove: vget", error);
4791 if ((error = VOP_FSYNC(vp, MNT_NOWAIT, 0)))
4792 softdep_error("clear_remove: fsync", error);
4793 drain_output(vp, 0);
4802 * Clear out a block of dirty inodes in an effort to reduce
4803 * the number of inodedep dependency structures.
4805 struct clear_inodedeps_info {
4811 clear_inodedeps_mountlist_callback(struct mount *mp, void *data)
4813 struct clear_inodedeps_info *info = data;
4815 if ((mp->mnt_flag & MNT_SOFTDEP) && info->fs == VFSTOUFS(mp)->um_fs) {
4823 clear_inodedeps(struct thread *td)
4825 struct clear_inodedeps_info info;
4826 struct inodedep_hashhead *inodedephd;
4827 struct inodedep *inodedep;
4828 static int next = 0;
4832 ino_t firstino, lastino, ino;
4836 * Pick a random inode dependency to be cleared.
4837 * We will then gather up all the inodes in its block
4838 * that have dependencies and flush them out.
4840 for (cnt = 0; cnt < inodedep_hash; cnt++) {
4841 inodedephd = &inodedep_hashtbl[next++];
4842 if (next >= inodedep_hash)
4844 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
4847 if (inodedep == NULL) {
4852 * Ugly code to find mount point given pointer to superblock.
4854 fs = inodedep->id_fs;
4857 mountlist_scan(clear_inodedeps_mountlist_callback,
4858 &info, MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
4860 * Find the last inode in the block with dependencies.
4862 firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
4863 for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
4864 if (inodedep_lookup(fs, lastino, 0, &inodedep) != 0)
4867 * Asynchronously push all but the last inode with dependencies.
4868 * Synchronously push the last inode with dependencies to ensure
4869 * that the inode block gets written to free up the inodedeps.
4871 for (ino = firstino; ino <= lastino; ino++) {
4872 if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4875 if ((error = VFS_VGET(info.mp, NULL, ino, &vp)) != 0) {
4876 softdep_error("clear_inodedeps: vget", error);
4879 if (ino == lastino) {
4880 if ((error = VOP_FSYNC(vp, MNT_WAIT, 0)))
4881 softdep_error("clear_inodedeps: fsync1", error);
4883 if ((error = VOP_FSYNC(vp, MNT_NOWAIT, 0)))
4884 softdep_error("clear_inodedeps: fsync2", error);
4885 drain_output(vp, 0);
4894 * Function to determine if the buffer has outstanding dependencies
4895 * that will cause a roll-back if the buffer is written. If wantcount
4896 * is set, return number of dependencies, otherwise just yes or no.
4898 * bioops callback - hold io_token
4901 softdep_count_dependencies(struct buf *bp, int wantcount)
4903 struct worklist *wk;
4904 struct inodedep *inodedep;
4905 struct indirdep *indirdep;
4906 struct allocindir *aip;
4907 struct pagedep *pagedep;
4914 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4915 switch (wk->wk_type) {
4918 inodedep = WK_INODEDEP(wk);
4919 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4920 /* bitmap allocation dependency */
4925 if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
4926 /* direct block pointer dependency */
4934 indirdep = WK_INDIRDEP(wk);
4936 LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
4937 /* indirect block pointer dependency */
4945 pagedep = WK_PAGEDEP(wk);
4946 for (i = 0; i < DAHASHSZ; i++) {
4948 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
4949 /* directory entry dependency */
4961 /* never a dependency on these blocks */
4965 panic("softdep_check_for_rollback: Unexpected type %s",
4966 TYPENAME(wk->wk_type));
4977 * Acquire exclusive access to a buffer. Requires softdep lock
4978 * to be held on entry. If waitfor is MNT_WAIT, may release/reacquire
4981 * Returns 1 if the buffer was locked, 0 if it was not locked or
4982 * if we had to block.
4984 * NOTE! In order to return 1 we must acquire the buffer lock prior
4985 * to any release of &lk. Once we release &lk it's all over.
4986 * We may still have to block on the (type-stable) bp in that
4987 * case, but we must then unlock it and return 0.
4990 getdirtybuf(struct buf **bpp, int waitfor)
4996 * If the contents of *bpp is NULL the caller presumably lost a race.
5003 * Try to obtain the buffer lock without deadlocking on &lk.
5005 KKASSERT(lock_held(&lk) > 0);
5006 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT);
5009 * If the buffer is no longer dirty the OS already wrote it
5010 * out, return failure.
5012 if ((bp->b_flags & B_DELWRI) == 0) {
5018 * Finish nominal buffer locking sequence return success.
5027 * If we are not being asked to wait, return 0 immediately.
5029 if (waitfor != MNT_WAIT)
5033 * Once we release the softdep lock we can never return success,
5034 * but we still have to block on the type-stable buf for the caller
5035 * to be able to retry without livelocking the system.
5037 * The caller will normally retry in this case.
5040 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL);
5048 * Wait for pending output on a vnode to complete.
5049 * Must be called with vnode locked.
5052 drain_output(struct vnode *vp, int islocked)
5057 while (bio_track_active(&vp->v_track_write)) {
5059 bio_track_wait(&vp->v_track_write, 0, 0);
5067 * Called whenever a buffer that is being invalidated or reallocated
5068 * contains dependencies. This should only happen if an I/O error has
5069 * occurred. The routine is called with the buffer locked.
5071 * bioops callback - hold io_token
5074 softdep_deallocate_dependencies(struct buf *bp)
5076 /* nothing to do, mp lock not needed */
5077 if ((bp->b_flags & B_ERROR) == 0)
5078 panic("softdep_deallocate_dependencies: dangling deps");
5079 softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntfromname, bp->b_error);
5080 panic("softdep_deallocate_dependencies: unrecovered I/O error");
5084 * Function to handle asynchronous write errors in the filesystem.
5087 softdep_error(char *func, int error)
5089 /* XXX should do something better! */
5090 kprintf("%s: got error %d while accessing filesystem\n", func, error);