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/mplock2.h>
74 #include <sys/thread2.h>
78 * These definitions need to be adapted to the system to which
79 * this file is being ported.
82 * malloc types defined for the softdep system.
84 MALLOC_DEFINE(M_PAGEDEP, "pagedep","File page dependencies");
85 MALLOC_DEFINE(M_INODEDEP, "inodedep","Inode dependencies");
86 MALLOC_DEFINE(M_NEWBLK, "newblk","New block allocation");
87 MALLOC_DEFINE(M_BMSAFEMAP, "bmsafemap","Block or frag allocated from cyl group map");
88 MALLOC_DEFINE(M_ALLOCDIRECT, "allocdirect","Block or frag dependency for an inode");
89 MALLOC_DEFINE(M_INDIRDEP, "indirdep","Indirect block dependencies");
90 MALLOC_DEFINE(M_ALLOCINDIR, "allocindir","Block dependency for an indirect block");
91 MALLOC_DEFINE(M_FREEFRAG, "freefrag","Previously used frag for an inode");
92 MALLOC_DEFINE(M_FREEBLKS, "freeblks","Blocks freed from an inode");
93 MALLOC_DEFINE(M_FREEFILE, "freefile","Inode deallocated");
94 MALLOC_DEFINE(M_DIRADD, "diradd","New directory entry");
95 MALLOC_DEFINE(M_MKDIR, "mkdir","New directory");
96 MALLOC_DEFINE(M_DIRREM, "dirrem","Directory entry deleted");
98 #define M_SOFTDEP_FLAGS (M_WAITOK | M_USE_RESERVE)
103 #define D_BMSAFEMAP 3
104 #define D_ALLOCDIRECT 4
106 #define D_ALLOCINDIR 6
113 #define D_LAST D_DIRREM
116 * translate from workitem type to memory type
117 * MUST match the defines above, such that memtype[D_XXX] == M_XXX
119 static struct malloc_type *memtype[] = {
135 #define DtoM(type) (memtype[type])
138 * Names of malloc types.
140 #define TYPENAME(type) \
141 ((unsigned)(type) < D_LAST ? memtype[type]->ks_shortdesc : "???")
143 * End system adaptaion definitions.
147 * Internal function prototypes.
149 static void softdep_error(char *, int);
150 static void drain_output(struct vnode *, int);
151 static int getdirtybuf(struct buf **, int);
152 static void clear_remove(struct thread *);
153 static void clear_inodedeps(struct thread *);
154 static int flush_pagedep_deps(struct vnode *, struct mount *,
156 static int flush_inodedep_deps(struct fs *, ino_t);
157 static int handle_written_filepage(struct pagedep *, struct buf *);
158 static void diradd_inode_written(struct diradd *, struct inodedep *);
159 static int handle_written_inodeblock(struct inodedep *, struct buf *);
160 static void handle_allocdirect_partdone(struct allocdirect *);
161 static void handle_allocindir_partdone(struct allocindir *);
162 static void initiate_write_filepage(struct pagedep *, struct buf *);
163 static void handle_written_mkdir(struct mkdir *, int);
164 static void initiate_write_inodeblock(struct inodedep *, struct buf *);
165 static void handle_workitem_freefile(struct freefile *);
166 static void handle_workitem_remove(struct dirrem *);
167 static struct dirrem *newdirrem(struct buf *, struct inode *,
168 struct inode *, int, struct dirrem **);
169 static void free_diradd(struct diradd *);
170 static void free_allocindir(struct allocindir *, struct inodedep *);
171 static int indir_trunc (struct inode *, off_t, int, ufs_lbn_t, long *);
172 static void deallocate_dependencies(struct buf *, struct inodedep *);
173 static void free_allocdirect(struct allocdirectlst *,
174 struct allocdirect *, int);
175 static int check_inode_unwritten(struct inodedep *);
176 static int free_inodedep(struct inodedep *);
177 static void handle_workitem_freeblocks(struct freeblks *);
178 static void merge_inode_lists(struct inodedep *);
179 static void setup_allocindir_phase2(struct buf *, struct inode *,
180 struct allocindir *);
181 static struct allocindir *newallocindir(struct inode *, int, ufs_daddr_t,
183 static void handle_workitem_freefrag(struct freefrag *);
184 static struct freefrag *newfreefrag(struct inode *, ufs_daddr_t, long);
185 static void allocdirect_merge(struct allocdirectlst *,
186 struct allocdirect *, struct allocdirect *);
187 static struct bmsafemap *bmsafemap_lookup(struct buf *);
188 static int newblk_lookup(struct fs *, ufs_daddr_t, int,
190 static int inodedep_lookup(struct fs *, ino_t, int, struct inodedep **);
191 static int pagedep_lookup(struct inode *, ufs_lbn_t, int,
193 static void pause_timer(void *);
194 static int request_cleanup(int, int);
195 static int process_worklist_item(struct mount *, int);
196 static void add_to_worklist(struct worklist *);
199 * Exported softdep operations.
201 static void softdep_disk_io_initiation(struct buf *);
202 static void softdep_disk_write_complete(struct buf *);
203 static void softdep_deallocate_dependencies(struct buf *);
204 static int softdep_fsync(struct vnode *);
205 static int softdep_process_worklist(struct mount *);
206 static void softdep_move_dependencies(struct buf *, struct buf *);
207 static int softdep_count_dependencies(struct buf *bp, int);
208 static int softdep_checkread(struct buf *bp);
209 static int softdep_checkwrite(struct buf *bp);
211 static struct bio_ops softdep_bioops = {
212 .io_start = softdep_disk_io_initiation,
213 .io_complete = softdep_disk_write_complete,
214 .io_deallocate = softdep_deallocate_dependencies,
215 .io_fsync = softdep_fsync,
216 .io_sync = softdep_process_worklist,
217 .io_movedeps = softdep_move_dependencies,
218 .io_countdeps = softdep_count_dependencies,
219 .io_checkread = softdep_checkread,
220 .io_checkwrite = softdep_checkwrite
224 * Locking primitives.
226 static void acquire_lock(struct lock *);
227 static void free_lock(struct lock *);
229 static int lock_held(struct lock *);
231 static int interlocked_sleep(struct lock *, void *, int,
234 static struct lock lk;
236 #define ACQUIRE_LOCK(lkp) acquire_lock(lkp)
237 #define FREE_LOCK(lkp) free_lock(lkp)
240 acquire_lock(struct lock *lkp)
242 lockmgr(lkp, LK_EXCLUSIVE);
246 free_lock(struct lock *lkp)
248 lockmgr(lkp, LK_RELEASE);
253 lock_held(struct lock *lkp)
255 return lockcountnb(lkp);
260 interlocked_sleep(struct lock *lkp, void *ident, int flags,
261 const char *wmesg, int timo)
265 KKASSERT(lock_held(lkp) > 0);
266 retval = lksleep(ident, lkp, flags, wmesg, timo);
271 * Place holder for real semaphores.
280 static void sema_init(struct sema *, char *, int, int);
281 static int sema_get(struct sema *, struct lock *);
282 static void sema_release(struct sema *);
284 #define NOHOLDER ((struct thread *) -1)
287 sema_init(struct sema *semap, char *name, int prio, int timo)
290 semap->holder = NOHOLDER;
298 sema_get(struct sema *semap, struct lock *interlock)
301 if (semap->value++ > 0) {
302 if (interlock != NULL) {
303 interlocked_sleep(interlock, (caddr_t)semap,
304 semap->prio, semap->name, semap->timo);
305 FREE_LOCK(interlock);
307 tsleep((caddr_t)semap, semap->prio, semap->name,
312 semap->holder = curthread;
313 if (interlock != NULL)
314 FREE_LOCK(interlock);
319 sema_release(struct sema *semap)
322 if (semap->value <= 0 || semap->holder != curthread) {
323 panic("sema_release: not held");
325 if (--semap->value > 0) {
329 semap->holder = NOHOLDER;
333 * Worklist queue management.
334 * These routines require that the lock be held.
336 static void worklist_insert(struct workhead *, struct worklist *);
337 static void worklist_remove(struct worklist *);
338 static void workitem_free(struct worklist *, int);
340 #define WORKLIST_INSERT_BP(bp, item) do { \
341 (bp)->b_ops = &softdep_bioops; \
342 worklist_insert(&(bp)->b_dep, item); \
345 #define WORKLIST_INSERT(head, item) worklist_insert(head, item)
346 #define WORKLIST_REMOVE(item) worklist_remove(item)
347 #define WORKITEM_FREE(item, type) workitem_free((struct worklist *)item, type)
350 worklist_insert(struct workhead *head, struct worklist *item)
353 KKASSERT(lock_held(&lk) > 0);
355 if (item->wk_state & ONWORKLIST) {
356 panic("worklist_insert: already on list");
358 item->wk_state |= ONWORKLIST;
359 LIST_INSERT_HEAD(head, item, wk_list);
363 worklist_remove(struct worklist *item)
366 KKASSERT(lock_held(&lk));
367 if ((item->wk_state & ONWORKLIST) == 0)
368 panic("worklist_remove: not on list");
370 item->wk_state &= ~ONWORKLIST;
371 LIST_REMOVE(item, wk_list);
375 workitem_free(struct worklist *item, int type)
378 if (item->wk_state & ONWORKLIST)
379 panic("workitem_free: still on list");
380 if (item->wk_type != type)
381 panic("workitem_free: type mismatch");
383 kfree(item, DtoM(type));
387 * Workitem queue management
389 static struct workhead softdep_workitem_pending;
390 static int num_on_worklist; /* number of worklist items to be processed */
391 static int softdep_worklist_busy; /* 1 => trying to do unmount */
392 static int softdep_worklist_req; /* serialized waiters */
393 static int max_softdeps; /* maximum number of structs before slowdown */
394 static int tickdelay = 2; /* number of ticks to pause during slowdown */
395 static int *stat_countp; /* statistic to count in proc_waiting timeout */
396 static int proc_waiting; /* tracks whether we have a timeout posted */
397 static struct callout handle; /* handle on posted proc_waiting timeout */
398 static struct thread *filesys_syncer; /* proc of filesystem syncer process */
399 static int req_clear_inodedeps; /* syncer process flush some inodedeps */
400 #define FLUSH_INODES 1
401 static int req_clear_remove; /* syncer process flush some freeblks */
402 #define FLUSH_REMOVE 2
406 static int stat_worklist_push; /* number of worklist cleanups */
407 static int stat_blk_limit_push; /* number of times block limit neared */
408 static int stat_ino_limit_push; /* number of times inode limit neared */
409 static int stat_blk_limit_hit; /* number of times block slowdown imposed */
410 static int stat_ino_limit_hit; /* number of times inode slowdown imposed */
411 static int stat_sync_limit_hit; /* number of synchronous slowdowns imposed */
412 static int stat_indir_blk_ptrs; /* bufs redirtied as indir ptrs not written */
413 static int stat_inode_bitmap; /* bufs redirtied as inode bitmap not written */
414 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
415 static int stat_dir_entry; /* bufs redirtied as dir entry cannot write */
418 #include <sys/sysctl.h>
419 SYSCTL_INT(_debug, OID_AUTO, max_softdeps, CTLFLAG_RW, &max_softdeps, 0,
420 "Maximum soft dependencies before slowdown occurs");
421 SYSCTL_INT(_debug, OID_AUTO, tickdelay, CTLFLAG_RW, &tickdelay, 0,
422 "Ticks to delay before allocating during slowdown");
423 SYSCTL_INT(_debug, OID_AUTO, worklist_push, CTLFLAG_RW, &stat_worklist_push, 0,
424 "Number of worklist cleanups");
425 SYSCTL_INT(_debug, OID_AUTO, blk_limit_push, CTLFLAG_RW, &stat_blk_limit_push, 0,
426 "Number of times block limit neared");
427 SYSCTL_INT(_debug, OID_AUTO, ino_limit_push, CTLFLAG_RW, &stat_ino_limit_push, 0,
428 "Number of times inode limit neared");
429 SYSCTL_INT(_debug, OID_AUTO, blk_limit_hit, CTLFLAG_RW, &stat_blk_limit_hit, 0,
430 "Number of times block slowdown imposed");
431 SYSCTL_INT(_debug, OID_AUTO, ino_limit_hit, CTLFLAG_RW, &stat_ino_limit_hit, 0,
432 "Number of times inode slowdown imposed ");
433 SYSCTL_INT(_debug, OID_AUTO, sync_limit_hit, CTLFLAG_RW, &stat_sync_limit_hit, 0,
434 "Number of synchronous slowdowns imposed");
435 SYSCTL_INT(_debug, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW, &stat_indir_blk_ptrs, 0,
436 "Bufs redirtied as indir ptrs not written");
437 SYSCTL_INT(_debug, OID_AUTO, inode_bitmap, CTLFLAG_RW, &stat_inode_bitmap, 0,
438 "Bufs redirtied as inode bitmap not written");
439 SYSCTL_INT(_debug, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW, &stat_direct_blk_ptrs, 0,
440 "Bufs redirtied as direct ptrs not written");
441 SYSCTL_INT(_debug, OID_AUTO, dir_entry, CTLFLAG_RW, &stat_dir_entry, 0,
442 "Bufs redirtied as dir entry cannot write");
446 * Add an item to the end of the work queue.
447 * This routine requires that the lock be held.
448 * This is the only routine that adds items to the list.
449 * The following routine is the only one that removes items
450 * and does so in order from first to last.
453 add_to_worklist(struct worklist *wk)
455 static struct worklist *worklist_tail;
457 if (wk->wk_state & ONWORKLIST) {
458 panic("add_to_worklist: already on list");
460 wk->wk_state |= ONWORKLIST;
461 if (LIST_FIRST(&softdep_workitem_pending) == NULL)
462 LIST_INSERT_HEAD(&softdep_workitem_pending, wk, wk_list);
464 LIST_INSERT_AFTER(worklist_tail, wk, wk_list);
466 num_on_worklist += 1;
470 * Process that runs once per second to handle items in the background queue.
472 * Note that we ensure that everything is done in the order in which they
473 * appear in the queue. The code below depends on this property to ensure
474 * that blocks of a file are freed before the inode itself is freed. This
475 * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
476 * until all the old ones have been purged from the dependency lists.
478 * bioops callback - hold io_token
481 softdep_process_worklist(struct mount *matchmnt)
483 thread_t td = curthread;
484 int matchcnt, loopcount;
490 * Record the process identifier of our caller so that we can give
491 * this process preferential treatment in request_cleanup below.
497 * There is no danger of having multiple processes run this
498 * code, but we have to single-thread it when softdep_flushfiles()
499 * is in operation to get an accurate count of the number of items
500 * related to its mount point that are in the list.
502 if (matchmnt == NULL) {
503 if (softdep_worklist_busy < 0) {
507 softdep_worklist_busy += 1;
511 * If requested, try removing inode or removal dependencies.
513 if (req_clear_inodedeps) {
515 req_clear_inodedeps -= 1;
516 wakeup_one(&proc_waiting);
518 if (req_clear_remove) {
520 req_clear_remove -= 1;
521 wakeup_one(&proc_waiting);
524 starttime = time_second;
525 while (num_on_worklist > 0) {
526 matchcnt += process_worklist_item(matchmnt, 0);
529 * If a umount operation wants to run the worklist
532 if (softdep_worklist_req && matchmnt == NULL) {
538 * If requested, try removing inode or removal dependencies.
540 if (req_clear_inodedeps) {
542 req_clear_inodedeps -= 1;
543 wakeup_one(&proc_waiting);
545 if (req_clear_remove) {
547 req_clear_remove -= 1;
548 wakeup_one(&proc_waiting);
551 * We do not generally want to stop for buffer space, but if
552 * we are really being a buffer hog, we will stop and wait.
554 if (loopcount++ % 128 == 0)
557 * Never allow processing to run for more than one
558 * second. Otherwise the other syncer tasks may get
559 * excessively backlogged.
561 if (starttime != time_second && matchmnt == NULL) {
566 if (matchmnt == NULL) {
567 --softdep_worklist_busy;
568 if (softdep_worklist_req && softdep_worklist_busy == 0)
569 wakeup(&softdep_worklist_req);
577 * Process one item on the worklist.
580 process_worklist_item(struct mount *matchmnt, int flags)
583 struct dirrem *dirrem;
589 if (matchmnt != NULL)
590 matchfs = VFSTOUFS(matchmnt)->um_fs;
593 * Normally we just process each item on the worklist in order.
594 * However, if we are in a situation where we cannot lock any
595 * inodes, we have to skip over any dirrem requests whose
596 * vnodes are resident and locked.
598 LIST_FOREACH(wk, &softdep_workitem_pending, wk_list) {
599 if ((flags & LK_NOWAIT) == 0 || wk->wk_type != D_DIRREM)
601 dirrem = WK_DIRREM(wk);
602 vp = ufs_ihashlookup(VFSTOUFS(dirrem->dm_mnt)->um_dev,
604 if (vp == NULL || !vn_islocked(vp))
612 num_on_worklist -= 1;
614 switch (wk->wk_type) {
617 /* removal of a directory entry */
618 if (WK_DIRREM(wk)->dm_mnt == matchmnt)
620 handle_workitem_remove(WK_DIRREM(wk));
624 /* releasing blocks and/or fragments from a file */
625 if (WK_FREEBLKS(wk)->fb_fs == matchfs)
627 handle_workitem_freeblocks(WK_FREEBLKS(wk));
631 /* releasing a fragment when replaced as a file grows */
632 if (WK_FREEFRAG(wk)->ff_fs == matchfs)
634 handle_workitem_freefrag(WK_FREEFRAG(wk));
638 /* releasing an inode when its link count drops to 0 */
639 if (WK_FREEFILE(wk)->fx_fs == matchfs)
641 handle_workitem_freefile(WK_FREEFILE(wk));
645 panic("%s_process_worklist: Unknown type %s",
646 "softdep", TYPENAME(wk->wk_type));
653 * Move dependencies from one buffer to another.
655 * bioops callback - hold io_token
658 softdep_move_dependencies(struct buf *oldbp, struct buf *newbp)
660 struct worklist *wk, *wktail;
663 if (LIST_FIRST(&newbp->b_dep) != NULL)
664 panic("softdep_move_dependencies: need merge code");
667 while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
668 LIST_REMOVE(wk, wk_list);
670 LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
672 LIST_INSERT_AFTER(wktail, wk, wk_list);
674 newbp->b_ops = &softdep_bioops;
681 * Purge the work list of all items associated with a particular mount point.
684 softdep_flushfiles(struct mount *oldmnt, int flags)
690 * Await our turn to clear out the queue, then serialize access.
693 while (softdep_worklist_busy != 0) {
694 softdep_worklist_req += 1;
695 lksleep(&softdep_worklist_req, &lk, 0, "softflush", 0);
696 softdep_worklist_req -= 1;
698 softdep_worklist_busy = -1;
701 if ((error = ffs_flushfiles(oldmnt, flags)) != 0) {
702 softdep_worklist_busy = 0;
703 if (softdep_worklist_req)
704 wakeup(&softdep_worklist_req);
708 * Alternately flush the block device associated with the mount
709 * point and process any dependencies that the flushing
710 * creates. In theory, this loop can happen at most twice,
711 * but we give it a few extra just to be sure.
713 devvp = VFSTOUFS(oldmnt)->um_devvp;
714 for (loopcnt = 10; loopcnt > 0; ) {
715 if (softdep_process_worklist(oldmnt) == 0) {
718 * Do another flush in case any vnodes were brought in
719 * as part of the cleanup operations.
721 if ((error = ffs_flushfiles(oldmnt, flags)) != 0)
724 * If we still found nothing to do, we are really done.
726 if (softdep_process_worklist(oldmnt) == 0)
729 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
730 error = VOP_FSYNC(devvp, MNT_WAIT, 0);
736 softdep_worklist_busy = 0;
737 if (softdep_worklist_req)
738 wakeup(&softdep_worklist_req);
742 * If we are unmounting then it is an error to fail. If we
743 * are simply trying to downgrade to read-only, then filesystem
744 * activity can keep us busy forever, so we just fail with EBUSY.
747 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
748 panic("softdep_flushfiles: looping");
757 * There are three types of structures that can be looked up:
758 * 1) pagedep structures identified by mount point, inode number,
760 * 2) inodedep structures identified by mount point and inode number.
761 * 3) newblk structures identified by mount point and
762 * physical block number.
764 * The "pagedep" and "inodedep" dependency structures are hashed
765 * separately from the file blocks and inodes to which they correspond.
766 * This separation helps when the in-memory copy of an inode or
767 * file block must be replaced. It also obviates the need to access
768 * an inode or file page when simply updating (or de-allocating)
769 * dependency structures. Lookup of newblk structures is needed to
770 * find newly allocated blocks when trying to associate them with
771 * their allocdirect or allocindir structure.
773 * The lookup routines optionally create and hash a new instance when
774 * an existing entry is not found.
776 #define DEPALLOC 0x0001 /* allocate structure if lookup fails */
777 #define NODELAY 0x0002 /* cannot do background work */
780 * Structures and routines associated with pagedep caching.
782 LIST_HEAD(pagedep_hashhead, pagedep) *pagedep_hashtbl;
783 u_long pagedep_hash; /* size of hash table - 1 */
784 #define PAGEDEP_HASH(mp, inum, lbn) \
785 (&pagedep_hashtbl[((((register_t)(mp)) >> 13) + (inum) + (lbn)) & \
787 static struct sema pagedep_in_progress;
790 * Helper routine for pagedep_lookup()
794 pagedep_find(struct pagedep_hashhead *pagedephd, ino_t ino, ufs_lbn_t lbn,
797 struct pagedep *pagedep;
799 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
800 if (ino == pagedep->pd_ino &&
801 lbn == pagedep->pd_lbn &&
802 mp == pagedep->pd_mnt) {
810 * Look up a pagedep. Return 1 if found, 0 if not found.
811 * If not found, allocate if DEPALLOC flag is passed.
812 * Found or allocated entry is returned in pagedeppp.
813 * This routine must be called with splbio interrupts blocked.
816 pagedep_lookup(struct inode *ip, ufs_lbn_t lbn, int flags,
817 struct pagedep **pagedeppp)
819 struct pagedep *pagedep;
820 struct pagedep_hashhead *pagedephd;
824 KKASSERT(lock_held(&lk) > 0);
826 mp = ITOV(ip)->v_mount;
827 pagedephd = PAGEDEP_HASH(mp, ip->i_number, lbn);
829 *pagedeppp = pagedep_find(pagedephd, ip->i_number, lbn, mp);
832 if ((flags & DEPALLOC) == 0)
834 if (sema_get(&pagedep_in_progress, &lk) == 0) {
838 pagedep = kmalloc(sizeof(struct pagedep), M_PAGEDEP,
839 M_SOFTDEP_FLAGS | M_ZERO);
841 if (pagedep_find(pagedephd, ip->i_number, lbn, mp)) {
842 kprintf("pagedep_lookup: blocking race avoided\n");
844 sema_release(&pagedep_in_progress);
845 kfree(pagedep, M_PAGEDEP);
849 pagedep->pd_list.wk_type = D_PAGEDEP;
850 pagedep->pd_mnt = mp;
851 pagedep->pd_ino = ip->i_number;
852 pagedep->pd_lbn = lbn;
853 LIST_INIT(&pagedep->pd_dirremhd);
854 LIST_INIT(&pagedep->pd_pendinghd);
855 for (i = 0; i < DAHASHSZ; i++)
856 LIST_INIT(&pagedep->pd_diraddhd[i]);
858 LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
859 sema_release(&pagedep_in_progress);
860 *pagedeppp = pagedep;
865 * Structures and routines associated with inodedep caching.
867 LIST_HEAD(inodedep_hashhead, inodedep) *inodedep_hashtbl;
868 static u_long inodedep_hash; /* size of hash table - 1 */
869 static long num_inodedep; /* number of inodedep allocated */
870 #define INODEDEP_HASH(fs, inum) \
871 (&inodedep_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & inodedep_hash])
872 static struct sema inodedep_in_progress;
875 * Helper routine for inodedep_lookup()
879 inodedep_find(struct inodedep_hashhead *inodedephd, struct fs *fs, ino_t inum)
881 struct inodedep *inodedep;
883 LIST_FOREACH(inodedep, inodedephd, id_hash) {
884 if (inum == inodedep->id_ino && fs == inodedep->id_fs)
891 * Look up a inodedep. Return 1 if found, 0 if not found.
892 * If not found, allocate if DEPALLOC flag is passed.
893 * Found or allocated entry is returned in inodedeppp.
894 * This routine must be called with splbio interrupts blocked.
897 inodedep_lookup(struct fs *fs, ino_t inum, int flags,
898 struct inodedep **inodedeppp)
900 struct inodedep *inodedep;
901 struct inodedep_hashhead *inodedephd;
904 KKASSERT(lock_held(&lk) > 0);
907 inodedephd = INODEDEP_HASH(fs, inum);
909 *inodedeppp = inodedep_find(inodedephd, fs, inum);
912 if ((flags & DEPALLOC) == 0)
915 * If we are over our limit, try to improve the situation.
917 if (num_inodedep > max_softdeps && firsttry &&
918 speedup_syncer() == 0 && (flags & NODELAY) == 0 &&
919 request_cleanup(FLUSH_INODES, 1)) {
923 if (sema_get(&inodedep_in_progress, &lk) == 0) {
927 inodedep = kmalloc(sizeof(struct inodedep), M_INODEDEP,
928 M_SOFTDEP_FLAGS | M_ZERO);
929 if (inodedep_find(inodedephd, fs, inum)) {
930 kprintf("inodedep_lookup: blocking race avoided\n");
932 sema_release(&inodedep_in_progress);
933 kfree(inodedep, M_INODEDEP);
936 inodedep->id_list.wk_type = D_INODEDEP;
937 inodedep->id_fs = fs;
938 inodedep->id_ino = inum;
939 inodedep->id_state = ALLCOMPLETE;
940 inodedep->id_nlinkdelta = 0;
941 inodedep->id_savedino = NULL;
942 inodedep->id_savedsize = -1;
943 inodedep->id_buf = NULL;
944 LIST_INIT(&inodedep->id_pendinghd);
945 LIST_INIT(&inodedep->id_inowait);
946 LIST_INIT(&inodedep->id_bufwait);
947 TAILQ_INIT(&inodedep->id_inoupdt);
948 TAILQ_INIT(&inodedep->id_newinoupdt);
951 LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
952 sema_release(&inodedep_in_progress);
953 *inodedeppp = inodedep;
958 * Structures and routines associated with newblk caching.
960 LIST_HEAD(newblk_hashhead, newblk) *newblk_hashtbl;
961 u_long newblk_hash; /* size of hash table - 1 */
962 #define NEWBLK_HASH(fs, inum) \
963 (&newblk_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & newblk_hash])
964 static struct sema newblk_in_progress;
967 * Helper routine for newblk_lookup()
971 newblk_find(struct newblk_hashhead *newblkhd, struct fs *fs,
972 ufs_daddr_t newblkno)
974 struct newblk *newblk;
976 LIST_FOREACH(newblk, newblkhd, nb_hash) {
977 if (newblkno == newblk->nb_newblkno && fs == newblk->nb_fs)
984 * Look up a newblk. Return 1 if found, 0 if not found.
985 * If not found, allocate if DEPALLOC flag is passed.
986 * Found or allocated entry is returned in newblkpp.
989 newblk_lookup(struct fs *fs, ufs_daddr_t newblkno, int flags,
990 struct newblk **newblkpp)
992 struct newblk *newblk;
993 struct newblk_hashhead *newblkhd;
995 newblkhd = NEWBLK_HASH(fs, newblkno);
997 *newblkpp = newblk_find(newblkhd, fs, newblkno);
1000 if ((flags & DEPALLOC) == 0)
1002 if (sema_get(&newblk_in_progress, 0) == 0)
1004 newblk = kmalloc(sizeof(struct newblk), M_NEWBLK,
1005 M_SOFTDEP_FLAGS | M_ZERO);
1007 if (newblk_find(newblkhd, fs, newblkno)) {
1008 kprintf("newblk_lookup: blocking race avoided\n");
1009 sema_release(&pagedep_in_progress);
1010 kfree(newblk, M_NEWBLK);
1013 newblk->nb_state = 0;
1015 newblk->nb_newblkno = newblkno;
1016 LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
1017 sema_release(&newblk_in_progress);
1023 * Executed during filesystem system initialization before
1024 * mounting any filesystems.
1027 softdep_initialize(void)
1029 callout_init(&handle);
1031 LIST_INIT(&mkdirlisthd);
1032 LIST_INIT(&softdep_workitem_pending);
1033 max_softdeps = min(desiredvnodes * 8,
1034 M_INODEDEP->ks_limit / (2 * sizeof(struct inodedep)));
1035 pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
1037 lockinit(&lk, "ffs_softdep", 0, LK_CANRECURSE);
1038 sema_init(&pagedep_in_progress, "pagedep", 0, 0);
1039 inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP, &inodedep_hash);
1040 sema_init(&inodedep_in_progress, "inodedep", 0, 0);
1041 newblk_hashtbl = hashinit(64, M_NEWBLK, &newblk_hash);
1042 sema_init(&newblk_in_progress, "newblk", 0, 0);
1043 add_bio_ops(&softdep_bioops);
1047 * Called at mount time to notify the dependency code that a
1048 * filesystem wishes to use it.
1051 softdep_mount(struct vnode *devvp, struct mount *mp, struct fs *fs)
1053 struct csum cstotal;
1058 mp->mnt_flag &= ~MNT_ASYNC;
1059 mp->mnt_flag |= MNT_SOFTDEP;
1060 mp->mnt_bioops = &softdep_bioops;
1062 * When doing soft updates, the counters in the
1063 * superblock may have gotten out of sync, so we have
1064 * to scan the cylinder groups and recalculate them.
1066 if (fs->fs_clean != 0)
1068 bzero(&cstotal, sizeof cstotal);
1069 for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
1070 if ((error = bread(devvp, fsbtodoff(fs, cgtod(fs, cyl)),
1071 fs->fs_cgsize, &bp)) != 0) {
1075 cgp = (struct cg *)bp->b_data;
1076 cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
1077 cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
1078 cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
1079 cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
1080 fs->fs_cs(fs, cyl) = cgp->cg_cs;
1084 if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
1085 kprintf("ffs_mountfs: superblock updated for soft updates\n");
1087 bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
1092 * Protecting the freemaps (or bitmaps).
1094 * To eliminate the need to execute fsck before mounting a filesystem
1095 * after a power failure, one must (conservatively) guarantee that the
1096 * on-disk copy of the bitmaps never indicate that a live inode or block is
1097 * free. So, when a block or inode is allocated, the bitmap should be
1098 * updated (on disk) before any new pointers. When a block or inode is
1099 * freed, the bitmap should not be updated until all pointers have been
1100 * reset. The latter dependency is handled by the delayed de-allocation
1101 * approach described below for block and inode de-allocation. The former
1102 * dependency is handled by calling the following procedure when a block or
1103 * inode is allocated. When an inode is allocated an "inodedep" is created
1104 * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
1105 * Each "inodedep" is also inserted into the hash indexing structure so
1106 * that any additional link additions can be made dependent on the inode
1109 * The ufs filesystem maintains a number of free block counts (e.g., per
1110 * cylinder group, per cylinder and per <cylinder, rotational position> pair)
1111 * in addition to the bitmaps. These counts are used to improve efficiency
1112 * during allocation and therefore must be consistent with the bitmaps.
1113 * There is no convenient way to guarantee post-crash consistency of these
1114 * counts with simple update ordering, for two main reasons: (1) The counts
1115 * and bitmaps for a single cylinder group block are not in the same disk
1116 * sector. If a disk write is interrupted (e.g., by power failure), one may
1117 * be written and the other not. (2) Some of the counts are located in the
1118 * superblock rather than the cylinder group block. So, we focus our soft
1119 * updates implementation on protecting the bitmaps. When mounting a
1120 * filesystem, we recompute the auxiliary counts from the bitmaps.
1124 * Called just after updating the cylinder group block to allocate an inode.
1127 * bp: buffer for cylgroup block with inode map
1128 * ip: inode related to allocation
1129 * newinum: new inode number being allocated
1132 softdep_setup_inomapdep(struct buf *bp, struct inode *ip, ino_t newinum)
1134 struct inodedep *inodedep;
1135 struct bmsafemap *bmsafemap;
1138 * Create a dependency for the newly allocated inode.
1139 * Panic if it already exists as something is seriously wrong.
1140 * Otherwise add it to the dependency list for the buffer holding
1141 * the cylinder group map from which it was allocated.
1144 if ((inodedep_lookup(ip->i_fs, newinum, DEPALLOC|NODELAY, &inodedep))) {
1146 panic("softdep_setup_inomapdep: found inode");
1148 inodedep->id_buf = bp;
1149 inodedep->id_state &= ~DEPCOMPLETE;
1150 bmsafemap = bmsafemap_lookup(bp);
1151 LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
1156 * Called just after updating the cylinder group block to
1157 * allocate block or fragment.
1160 * bp: buffer for cylgroup block with block map
1161 * fs: filesystem doing allocation
1162 * newblkno: number of newly allocated block
1165 softdep_setup_blkmapdep(struct buf *bp, struct fs *fs,
1166 ufs_daddr_t newblkno)
1168 struct newblk *newblk;
1169 struct bmsafemap *bmsafemap;
1172 * Create a dependency for the newly allocated block.
1173 * Add it to the dependency list for the buffer holding
1174 * the cylinder group map from which it was allocated.
1176 if (newblk_lookup(fs, newblkno, DEPALLOC, &newblk) != 0)
1177 panic("softdep_setup_blkmapdep: found block");
1179 newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(bp);
1180 LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
1185 * Find the bmsafemap associated with a cylinder group buffer.
1186 * If none exists, create one. The buffer must be locked when
1187 * this routine is called and this routine must be called with
1188 * splbio interrupts blocked.
1190 static struct bmsafemap *
1191 bmsafemap_lookup(struct buf *bp)
1193 struct bmsafemap *bmsafemap;
1194 struct worklist *wk;
1196 KKASSERT(lock_held(&lk) > 0);
1198 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
1199 if (wk->wk_type == D_BMSAFEMAP)
1200 return (WK_BMSAFEMAP(wk));
1203 bmsafemap = kmalloc(sizeof(struct bmsafemap), M_BMSAFEMAP,
1205 bmsafemap->sm_list.wk_type = D_BMSAFEMAP;
1206 bmsafemap->sm_list.wk_state = 0;
1207 bmsafemap->sm_buf = bp;
1208 LIST_INIT(&bmsafemap->sm_allocdirecthd);
1209 LIST_INIT(&bmsafemap->sm_allocindirhd);
1210 LIST_INIT(&bmsafemap->sm_inodedephd);
1211 LIST_INIT(&bmsafemap->sm_newblkhd);
1213 WORKLIST_INSERT_BP(bp, &bmsafemap->sm_list);
1218 * Direct block allocation dependencies.
1220 * When a new block is allocated, the corresponding disk locations must be
1221 * initialized (with zeros or new data) before the on-disk inode points to
1222 * them. Also, the freemap from which the block was allocated must be
1223 * updated (on disk) before the inode's pointer. These two dependencies are
1224 * independent of each other and are needed for all file blocks and indirect
1225 * blocks that are pointed to directly by the inode. Just before the
1226 * "in-core" version of the inode is updated with a newly allocated block
1227 * number, a procedure (below) is called to setup allocation dependency
1228 * structures. These structures are removed when the corresponding
1229 * dependencies are satisfied or when the block allocation becomes obsolete
1230 * (i.e., the file is deleted, the block is de-allocated, or the block is a
1231 * fragment that gets upgraded). All of these cases are handled in
1232 * procedures described later.
1234 * When a file extension causes a fragment to be upgraded, either to a larger
1235 * fragment or to a full block, the on-disk location may change (if the
1236 * previous fragment could not simply be extended). In this case, the old
1237 * fragment must be de-allocated, but not until after the inode's pointer has
1238 * been updated. In most cases, this is handled by later procedures, which
1239 * will construct a "freefrag" structure to be added to the workitem queue
1240 * when the inode update is complete (or obsolete). The main exception to
1241 * this is when an allocation occurs while a pending allocation dependency
1242 * (for the same block pointer) remains. This case is handled in the main
1243 * allocation dependency setup procedure by immediately freeing the
1244 * unreferenced fragments.
1247 * ip: inode to which block is being added
1248 * lbn: block pointer within inode
1249 * newblkno: disk block number being added
1250 * oldblkno: previous block number, 0 unless frag
1251 * newsize: size of new block
1252 * oldsize: size of new block
1253 * bp: bp for allocated block
1256 softdep_setup_allocdirect(struct inode *ip, ufs_lbn_t lbn, ufs_daddr_t newblkno,
1257 ufs_daddr_t oldblkno, long newsize, long oldsize,
1260 struct allocdirect *adp, *oldadp;
1261 struct allocdirectlst *adphead;
1262 struct bmsafemap *bmsafemap;
1263 struct inodedep *inodedep;
1264 struct pagedep *pagedep;
1265 struct newblk *newblk;
1267 adp = kmalloc(sizeof(struct allocdirect), M_ALLOCDIRECT,
1268 M_SOFTDEP_FLAGS | M_ZERO);
1269 adp->ad_list.wk_type = D_ALLOCDIRECT;
1271 adp->ad_newblkno = newblkno;
1272 adp->ad_oldblkno = oldblkno;
1273 adp->ad_newsize = newsize;
1274 adp->ad_oldsize = oldsize;
1275 adp->ad_state = ATTACHED;
1276 if (newblkno == oldblkno)
1277 adp->ad_freefrag = NULL;
1279 adp->ad_freefrag = newfreefrag(ip, oldblkno, oldsize);
1281 if (newblk_lookup(ip->i_fs, newblkno, 0, &newblk) == 0)
1282 panic("softdep_setup_allocdirect: lost block");
1285 inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC | NODELAY, &inodedep);
1286 adp->ad_inodedep = inodedep;
1288 if (newblk->nb_state == DEPCOMPLETE) {
1289 adp->ad_state |= DEPCOMPLETE;
1292 bmsafemap = newblk->nb_bmsafemap;
1293 adp->ad_buf = bmsafemap->sm_buf;
1294 LIST_REMOVE(newblk, nb_deps);
1295 LIST_INSERT_HEAD(&bmsafemap->sm_allocdirecthd, adp, ad_deps);
1297 LIST_REMOVE(newblk, nb_hash);
1298 kfree(newblk, M_NEWBLK);
1300 WORKLIST_INSERT_BP(bp, &adp->ad_list);
1301 if (lbn >= NDADDR) {
1302 /* allocating an indirect block */
1303 if (oldblkno != 0) {
1305 panic("softdep_setup_allocdirect: non-zero indir");
1309 * Allocating a direct block.
1311 * If we are allocating a directory block, then we must
1312 * allocate an associated pagedep to track additions and
1315 if ((ip->i_mode & IFMT) == IFDIR &&
1316 pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0) {
1317 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
1321 * The list of allocdirects must be kept in sorted and ascending
1322 * order so that the rollback routines can quickly determine the
1323 * first uncommitted block (the size of the file stored on disk
1324 * ends at the end of the lowest committed fragment, or if there
1325 * are no fragments, at the end of the highest committed block).
1326 * Since files generally grow, the typical case is that the new
1327 * block is to be added at the end of the list. We speed this
1328 * special case by checking against the last allocdirect in the
1329 * list before laboriously traversing the list looking for the
1332 adphead = &inodedep->id_newinoupdt;
1333 oldadp = TAILQ_LAST(adphead, allocdirectlst);
1334 if (oldadp == NULL || oldadp->ad_lbn <= lbn) {
1335 /* insert at end of list */
1336 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
1337 if (oldadp != NULL && oldadp->ad_lbn == lbn)
1338 allocdirect_merge(adphead, adp, oldadp);
1342 TAILQ_FOREACH(oldadp, adphead, ad_next) {
1343 if (oldadp->ad_lbn >= lbn)
1346 if (oldadp == NULL) {
1348 panic("softdep_setup_allocdirect: lost entry");
1350 /* insert in middle of list */
1351 TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
1352 if (oldadp->ad_lbn == lbn)
1353 allocdirect_merge(adphead, adp, oldadp);
1358 * Replace an old allocdirect dependency with a newer one.
1359 * This routine must be called with splbio interrupts blocked.
1362 * adphead: head of list holding allocdirects
1363 * newadp: allocdirect being added
1364 * oldadp: existing allocdirect being checked
1367 allocdirect_merge(struct allocdirectlst *adphead,
1368 struct allocdirect *newadp,
1369 struct allocdirect *oldadp)
1371 struct freefrag *freefrag;
1373 KKASSERT(lock_held(&lk) > 0);
1375 if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
1376 newadp->ad_oldsize != oldadp->ad_newsize ||
1377 newadp->ad_lbn >= NDADDR) {
1379 panic("allocdirect_check: old %d != new %d || lbn %ld >= %d",
1380 newadp->ad_oldblkno, oldadp->ad_newblkno, newadp->ad_lbn,
1383 newadp->ad_oldblkno = oldadp->ad_oldblkno;
1384 newadp->ad_oldsize = oldadp->ad_oldsize;
1386 * If the old dependency had a fragment to free or had never
1387 * previously had a block allocated, then the new dependency
1388 * can immediately post its freefrag and adopt the old freefrag.
1389 * This action is done by swapping the freefrag dependencies.
1390 * The new dependency gains the old one's freefrag, and the
1391 * old one gets the new one and then immediately puts it on
1392 * the worklist when it is freed by free_allocdirect. It is
1393 * not possible to do this swap when the old dependency had a
1394 * non-zero size but no previous fragment to free. This condition
1395 * arises when the new block is an extension of the old block.
1396 * Here, the first part of the fragment allocated to the new
1397 * dependency is part of the block currently claimed on disk by
1398 * the old dependency, so cannot legitimately be freed until the
1399 * conditions for the new dependency are fulfilled.
1401 if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
1402 freefrag = newadp->ad_freefrag;
1403 newadp->ad_freefrag = oldadp->ad_freefrag;
1404 oldadp->ad_freefrag = freefrag;
1406 free_allocdirect(adphead, oldadp, 0);
1410 * Allocate a new freefrag structure if needed.
1412 static struct freefrag *
1413 newfreefrag(struct inode *ip, ufs_daddr_t blkno, long size)
1415 struct freefrag *freefrag;
1421 if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
1422 panic("newfreefrag: frag size");
1423 freefrag = kmalloc(sizeof(struct freefrag), M_FREEFRAG,
1425 freefrag->ff_list.wk_type = D_FREEFRAG;
1426 freefrag->ff_state = ip->i_uid & ~ONWORKLIST; /* XXX - used below */
1427 freefrag->ff_inum = ip->i_number;
1428 freefrag->ff_fs = fs;
1429 freefrag->ff_devvp = ip->i_devvp;
1430 freefrag->ff_blkno = blkno;
1431 freefrag->ff_fragsize = size;
1436 * This workitem de-allocates fragments that were replaced during
1437 * file block allocation.
1440 handle_workitem_freefrag(struct freefrag *freefrag)
1444 tip.i_fs = freefrag->ff_fs;
1445 tip.i_devvp = freefrag->ff_devvp;
1446 tip.i_dev = freefrag->ff_devvp->v_rdev;
1447 tip.i_number = freefrag->ff_inum;
1448 tip.i_uid = freefrag->ff_state & ~ONWORKLIST; /* XXX - set above */
1449 ffs_blkfree(&tip, freefrag->ff_blkno, freefrag->ff_fragsize);
1450 kfree(freefrag, M_FREEFRAG);
1454 * Indirect block allocation dependencies.
1456 * The same dependencies that exist for a direct block also exist when
1457 * a new block is allocated and pointed to by an entry in a block of
1458 * indirect pointers. The undo/redo states described above are also
1459 * used here. Because an indirect block contains many pointers that
1460 * may have dependencies, a second copy of the entire in-memory indirect
1461 * block is kept. The buffer cache copy is always completely up-to-date.
1462 * The second copy, which is used only as a source for disk writes,
1463 * contains only the safe pointers (i.e., those that have no remaining
1464 * update dependencies). The second copy is freed when all pointers
1465 * are safe. The cache is not allowed to replace indirect blocks with
1466 * pending update dependencies. If a buffer containing an indirect
1467 * block with dependencies is written, these routines will mark it
1468 * dirty again. It can only be successfully written once all the
1469 * dependencies are removed. The ffs_fsync routine in conjunction with
1470 * softdep_sync_metadata work together to get all the dependencies
1471 * removed so that a file can be successfully written to disk. Three
1472 * procedures are used when setting up indirect block pointer
1473 * dependencies. The division is necessary because of the organization
1474 * of the "balloc" routine and because of the distinction between file
1475 * pages and file metadata blocks.
1479 * Allocate a new allocindir structure.
1482 * ip: inode for file being extended
1483 * ptrno: offset of pointer in indirect block
1484 * newblkno: disk block number being added
1485 * oldblkno: previous block number, 0 if none
1487 static struct allocindir *
1488 newallocindir(struct inode *ip, int ptrno, ufs_daddr_t newblkno,
1489 ufs_daddr_t oldblkno)
1491 struct allocindir *aip;
1493 aip = kmalloc(sizeof(struct allocindir), M_ALLOCINDIR,
1494 M_SOFTDEP_FLAGS | M_ZERO);
1495 aip->ai_list.wk_type = D_ALLOCINDIR;
1496 aip->ai_state = ATTACHED;
1497 aip->ai_offset = ptrno;
1498 aip->ai_newblkno = newblkno;
1499 aip->ai_oldblkno = oldblkno;
1500 aip->ai_freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize);
1505 * Called just before setting an indirect block pointer
1506 * to a newly allocated file page.
1509 * ip: inode for file being extended
1510 * lbn: allocated block number within file
1511 * bp: buffer with indirect blk referencing page
1512 * ptrno: offset of pointer in indirect block
1513 * newblkno: disk block number being added
1514 * oldblkno: previous block number, 0 if none
1515 * nbp: buffer holding allocated page
1518 softdep_setup_allocindir_page(struct inode *ip, ufs_lbn_t lbn,
1519 struct buf *bp, int ptrno,
1520 ufs_daddr_t newblkno, ufs_daddr_t oldblkno,
1523 struct allocindir *aip;
1524 struct pagedep *pagedep;
1526 aip = newallocindir(ip, ptrno, newblkno, oldblkno);
1529 * If we are allocating a directory page, then we must
1530 * allocate an associated pagedep to track additions and
1533 if ((ip->i_mode & IFMT) == IFDIR &&
1534 pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0)
1535 WORKLIST_INSERT_BP(nbp, &pagedep->pd_list);
1536 WORKLIST_INSERT_BP(nbp, &aip->ai_list);
1538 setup_allocindir_phase2(bp, ip, aip);
1542 * Called just before setting an indirect block pointer to a
1543 * newly allocated indirect block.
1545 * nbp: newly allocated indirect block
1546 * ip: inode for file being extended
1547 * bp: indirect block referencing allocated block
1548 * ptrno: offset of pointer in indirect block
1549 * newblkno: disk block number being added
1552 softdep_setup_allocindir_meta(struct buf *nbp, struct inode *ip,
1553 struct buf *bp, int ptrno,
1554 ufs_daddr_t newblkno)
1556 struct allocindir *aip;
1558 aip = newallocindir(ip, ptrno, newblkno, 0);
1560 WORKLIST_INSERT_BP(nbp, &aip->ai_list);
1562 setup_allocindir_phase2(bp, ip, aip);
1566 * Called to finish the allocation of the "aip" allocated
1567 * by one of the two routines above.
1570 * bp: in-memory copy of the indirect block
1571 * ip: inode for file being extended
1572 * aip: allocindir allocated by the above routines
1575 setup_allocindir_phase2(struct buf *bp, struct inode *ip,
1576 struct allocindir *aip)
1578 struct worklist *wk;
1579 struct indirdep *indirdep, *newindirdep;
1580 struct bmsafemap *bmsafemap;
1581 struct allocindir *oldaip;
1582 struct freefrag *freefrag;
1583 struct newblk *newblk;
1585 if (bp->b_loffset >= 0)
1586 panic("setup_allocindir_phase2: not indir blk");
1587 for (indirdep = NULL, newindirdep = NULL; ; ) {
1589 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
1590 if (wk->wk_type != D_INDIRDEP)
1592 indirdep = WK_INDIRDEP(wk);
1595 if (indirdep == NULL && newindirdep) {
1596 indirdep = newindirdep;
1597 WORKLIST_INSERT_BP(bp, &indirdep->ir_list);
1602 if (newblk_lookup(ip->i_fs, aip->ai_newblkno, 0,
1604 panic("setup_allocindir: lost block");
1606 if (newblk->nb_state == DEPCOMPLETE) {
1607 aip->ai_state |= DEPCOMPLETE;
1610 bmsafemap = newblk->nb_bmsafemap;
1611 aip->ai_buf = bmsafemap->sm_buf;
1612 LIST_REMOVE(newblk, nb_deps);
1613 LIST_INSERT_HEAD(&bmsafemap->sm_allocindirhd,
1616 LIST_REMOVE(newblk, nb_hash);
1617 kfree(newblk, M_NEWBLK);
1618 aip->ai_indirdep = indirdep;
1620 * Check to see if there is an existing dependency
1621 * for this block. If there is, merge the old
1622 * dependency into the new one.
1624 if (aip->ai_oldblkno == 0)
1628 LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next)
1629 if (oldaip->ai_offset == aip->ai_offset)
1631 if (oldaip != NULL) {
1632 if (oldaip->ai_newblkno != aip->ai_oldblkno) {
1634 panic("setup_allocindir_phase2: blkno");
1636 aip->ai_oldblkno = oldaip->ai_oldblkno;
1637 freefrag = oldaip->ai_freefrag;
1638 oldaip->ai_freefrag = aip->ai_freefrag;
1639 aip->ai_freefrag = freefrag;
1640 free_allocindir(oldaip, NULL);
1642 LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
1643 ((ufs_daddr_t *)indirdep->ir_savebp->b_data)
1644 [aip->ai_offset] = aip->ai_oldblkno;
1649 * Avoid any possibility of data corruption by
1650 * ensuring that our old version is thrown away.
1652 newindirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
1653 brelse(newindirdep->ir_savebp);
1654 WORKITEM_FREE((caddr_t)newindirdep, D_INDIRDEP);
1658 newindirdep = kmalloc(sizeof(struct indirdep), M_INDIRDEP,
1660 newindirdep->ir_list.wk_type = D_INDIRDEP;
1661 newindirdep->ir_state = ATTACHED;
1662 LIST_INIT(&newindirdep->ir_deplisthd);
1663 LIST_INIT(&newindirdep->ir_donehd);
1664 if (bp->b_bio2.bio_offset == NOOFFSET) {
1665 VOP_BMAP(bp->b_vp, bp->b_bio1.bio_offset,
1666 &bp->b_bio2.bio_offset, NULL, NULL,
1669 KKASSERT(bp->b_bio2.bio_offset != NOOFFSET);
1670 newindirdep->ir_savebp = getblk(ip->i_devvp,
1671 bp->b_bio2.bio_offset,
1672 bp->b_bcount, 0, 0);
1673 BUF_KERNPROC(newindirdep->ir_savebp);
1674 bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
1679 * Block de-allocation dependencies.
1681 * When blocks are de-allocated, the on-disk pointers must be nullified before
1682 * the blocks are made available for use by other files. (The true
1683 * requirement is that old pointers must be nullified before new on-disk
1684 * pointers are set. We chose this slightly more stringent requirement to
1685 * reduce complexity.) Our implementation handles this dependency by updating
1686 * the inode (or indirect block) appropriately but delaying the actual block
1687 * de-allocation (i.e., freemap and free space count manipulation) until
1688 * after the updated versions reach stable storage. After the disk is
1689 * updated, the blocks can be safely de-allocated whenever it is convenient.
1690 * This implementation handles only the common case of reducing a file's
1691 * length to zero. Other cases are handled by the conventional synchronous
1694 * The ffs implementation with which we worked double-checks
1695 * the state of the block pointers and file size as it reduces
1696 * a file's length. Some of this code is replicated here in our
1697 * soft updates implementation. The freeblks->fb_chkcnt field is
1698 * used to transfer a part of this information to the procedure
1699 * that eventually de-allocates the blocks.
1701 * This routine should be called from the routine that shortens
1702 * a file's length, before the inode's size or block pointers
1703 * are modified. It will save the block pointer information for
1704 * later release and zero the inode so that the calling routine
1707 struct softdep_setup_freeblocks_info {
1712 static int softdep_setup_freeblocks_bp(struct buf *bp, void *data);
1716 * ip: The inode whose length is to be reduced
1717 * length: The new length for the file
1720 softdep_setup_freeblocks(struct inode *ip, off_t length)
1722 struct softdep_setup_freeblocks_info info;
1723 struct freeblks *freeblks;
1724 struct inodedep *inodedep;
1725 struct allocdirect *adp;
1729 int i, error, delay;
1734 panic("softde_setup_freeblocks: non-zero length");
1735 freeblks = kmalloc(sizeof(struct freeblks), M_FREEBLKS,
1736 M_SOFTDEP_FLAGS | M_ZERO);
1737 freeblks->fb_list.wk_type = D_FREEBLKS;
1738 freeblks->fb_state = ATTACHED;
1739 freeblks->fb_uid = ip->i_uid;
1740 freeblks->fb_previousinum = ip->i_number;
1741 freeblks->fb_devvp = ip->i_devvp;
1742 freeblks->fb_fs = fs;
1743 freeblks->fb_oldsize = ip->i_size;
1744 freeblks->fb_newsize = length;
1745 freeblks->fb_chkcnt = ip->i_blocks;
1746 for (i = 0; i < NDADDR; i++) {
1747 freeblks->fb_dblks[i] = ip->i_db[i];
1750 for (i = 0; i < NIADDR; i++) {
1751 freeblks->fb_iblks[i] = ip->i_ib[i];
1757 * Push the zero'ed inode to to its disk buffer so that we are free
1758 * to delete its dependencies below. Once the dependencies are gone
1759 * the buffer can be safely released.
1761 if ((error = bread(ip->i_devvp,
1762 fsbtodoff(fs, ino_to_fsba(fs, ip->i_number)),
1763 (int)fs->fs_bsize, &bp)) != 0)
1764 softdep_error("softdep_setup_freeblocks", error);
1765 *((struct ufs1_dinode *)bp->b_data + ino_to_fsbo(fs, ip->i_number)) =
1768 * Find and eliminate any inode dependencies.
1771 (void) inodedep_lookup(fs, ip->i_number, DEPALLOC, &inodedep);
1772 if ((inodedep->id_state & IOSTARTED) != 0) {
1774 panic("softdep_setup_freeblocks: inode busy");
1777 * Add the freeblks structure to the list of operations that
1778 * must await the zero'ed inode being written to disk. If we
1779 * still have a bitmap dependency (delay == 0), then the inode
1780 * has never been written to disk, so we can process the
1781 * freeblks below once we have deleted the dependencies.
1783 delay = (inodedep->id_state & DEPCOMPLETE);
1785 WORKLIST_INSERT(&inodedep->id_bufwait, &freeblks->fb_list);
1787 * Because the file length has been truncated to zero, any
1788 * pending block allocation dependency structures associated
1789 * with this inode are obsolete and can simply be de-allocated.
1790 * We must first merge the two dependency lists to get rid of
1791 * any duplicate freefrag structures, then purge the merged list.
1793 merge_inode_lists(inodedep);
1794 while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
1795 free_allocdirect(&inodedep->id_inoupdt, adp, 1);
1799 * We must wait for any I/O in progress to finish so that
1800 * all potential buffers on the dirty list will be visible.
1801 * Once they are all there, walk the list and get rid of
1806 drain_output(vp, 1);
1810 lwkt_gettoken(&vp->v_token);
1812 count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
1813 softdep_setup_freeblocks_bp, &info);
1814 } while (count != 0);
1815 lwkt_reltoken(&vp->v_token);
1817 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) != 0)
1818 (void)free_inodedep(inodedep);
1821 freeblks->fb_state |= DEPCOMPLETE;
1823 * If the inode with zeroed block pointers is now on disk
1824 * we can start freeing blocks. Add freeblks to the worklist
1825 * instead of calling handle_workitem_freeblocks directly as
1826 * it is more likely that additional IO is needed to complete
1827 * the request here than in the !delay case.
1829 if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
1830 add_to_worklist(&freeblks->fb_list);
1835 * If the inode has never been written to disk (delay == 0),
1836 * then we can process the freeblks now that we have deleted
1840 handle_workitem_freeblocks(freeblks);
1844 softdep_setup_freeblocks_bp(struct buf *bp, void *data)
1846 struct softdep_setup_freeblocks_info *info = data;
1847 struct inodedep *inodedep;
1849 if (getdirtybuf(&bp, MNT_WAIT) == 0) {
1850 kprintf("softdep_setup_freeblocks_bp(1): caught bp %p going away\n", bp);
1853 if (bp->b_vp != ITOV(info->ip) || (bp->b_flags & B_DELWRI) == 0) {
1854 kprintf("softdep_setup_freeblocks_bp(2): caught bp %p going away\n", bp);
1858 (void) inodedep_lookup(info->fs, info->ip->i_number, 0, &inodedep);
1859 deallocate_dependencies(bp, inodedep);
1860 bp->b_flags |= B_INVAL | B_NOCACHE;
1868 * Reclaim any dependency structures from a buffer that is about to
1869 * be reallocated to a new vnode. The buffer must be locked, thus,
1870 * no I/O completion operations can occur while we are manipulating
1871 * its associated dependencies. The mutex is held so that other I/O's
1872 * associated with related dependencies do not occur.
1875 deallocate_dependencies(struct buf *bp, struct inodedep *inodedep)
1877 struct worklist *wk;
1878 struct indirdep *indirdep;
1879 struct allocindir *aip;
1880 struct pagedep *pagedep;
1881 struct dirrem *dirrem;
1885 while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
1886 switch (wk->wk_type) {
1889 indirdep = WK_INDIRDEP(wk);
1891 * None of the indirect pointers will ever be visible,
1892 * so they can simply be tossed. GOINGAWAY ensures
1893 * that allocated pointers will be saved in the buffer
1894 * cache until they are freed. Note that they will
1895 * only be able to be found by their physical address
1896 * since the inode mapping the logical address will
1897 * be gone. The save buffer used for the safe copy
1898 * was allocated in setup_allocindir_phase2 using
1899 * the physical address so it could be used for this
1900 * purpose. Hence we swap the safe copy with the real
1901 * copy, allowing the safe copy to be freed and holding
1902 * on to the real copy for later use in indir_trunc.
1904 * NOTE: ir_savebp is relative to the block device
1905 * so b_bio1 contains the device block number.
1907 if (indirdep->ir_state & GOINGAWAY) {
1909 panic("deallocate_dependencies: already gone");
1911 indirdep->ir_state |= GOINGAWAY;
1912 while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
1913 free_allocindir(aip, inodedep);
1914 if (bp->b_bio1.bio_offset >= 0 ||
1915 bp->b_bio2.bio_offset != indirdep->ir_savebp->b_bio1.bio_offset) {
1917 panic("deallocate_dependencies: not indir");
1919 bcopy(bp->b_data, indirdep->ir_savebp->b_data,
1921 WORKLIST_REMOVE(wk);
1922 WORKLIST_INSERT_BP(indirdep->ir_savebp, wk);
1926 pagedep = WK_PAGEDEP(wk);
1928 * None of the directory additions will ever be
1929 * visible, so they can simply be tossed.
1931 for (i = 0; i < DAHASHSZ; i++)
1933 LIST_FIRST(&pagedep->pd_diraddhd[i])))
1935 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
1938 * Copy any directory remove dependencies to the list
1939 * to be processed after the zero'ed inode is written.
1940 * If the inode has already been written, then they
1941 * can be dumped directly onto the work list.
1943 LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
1944 LIST_REMOVE(dirrem, dm_next);
1945 dirrem->dm_dirinum = pagedep->pd_ino;
1946 if (inodedep == NULL ||
1947 (inodedep->id_state & ALLCOMPLETE) ==
1949 add_to_worklist(&dirrem->dm_list);
1951 WORKLIST_INSERT(&inodedep->id_bufwait,
1954 WORKLIST_REMOVE(&pagedep->pd_list);
1955 LIST_REMOVE(pagedep, pd_hash);
1956 WORKITEM_FREE(pagedep, D_PAGEDEP);
1960 free_allocindir(WK_ALLOCINDIR(wk), inodedep);
1966 panic("deallocate_dependencies: Unexpected type %s",
1967 TYPENAME(wk->wk_type));
1972 panic("deallocate_dependencies: Unknown type %s",
1973 TYPENAME(wk->wk_type));
1980 * Free an allocdirect. Generate a new freefrag work request if appropriate.
1981 * This routine must be called with splbio interrupts blocked.
1984 free_allocdirect(struct allocdirectlst *adphead,
1985 struct allocdirect *adp, int delay)
1987 KKASSERT(lock_held(&lk) > 0);
1989 if ((adp->ad_state & DEPCOMPLETE) == 0)
1990 LIST_REMOVE(adp, ad_deps);
1991 TAILQ_REMOVE(adphead, adp, ad_next);
1992 if ((adp->ad_state & COMPLETE) == 0)
1993 WORKLIST_REMOVE(&adp->ad_list);
1994 if (adp->ad_freefrag != NULL) {
1996 WORKLIST_INSERT(&adp->ad_inodedep->id_bufwait,
1997 &adp->ad_freefrag->ff_list);
1999 add_to_worklist(&adp->ad_freefrag->ff_list);
2001 WORKITEM_FREE(adp, D_ALLOCDIRECT);
2005 * Prepare an inode to be freed. The actual free operation is not
2006 * done until the zero'ed inode has been written to disk.
2009 softdep_freefile(struct vnode *pvp, ino_t ino, int mode)
2011 struct inode *ip = VTOI(pvp);
2012 struct inodedep *inodedep;
2013 struct freefile *freefile;
2016 * This sets up the inode de-allocation dependency.
2018 freefile = kmalloc(sizeof(struct freefile), M_FREEFILE,
2020 freefile->fx_list.wk_type = D_FREEFILE;
2021 freefile->fx_list.wk_state = 0;
2022 freefile->fx_mode = mode;
2023 freefile->fx_oldinum = ino;
2024 freefile->fx_devvp = ip->i_devvp;
2025 freefile->fx_fs = ip->i_fs;
2028 * If the inodedep does not exist, then the zero'ed inode has
2029 * been written to disk. If the allocated inode has never been
2030 * written to disk, then the on-disk inode is zero'ed. In either
2031 * case we can free the file immediately.
2034 if (inodedep_lookup(ip->i_fs, ino, 0, &inodedep) == 0 ||
2035 check_inode_unwritten(inodedep)) {
2037 handle_workitem_freefile(freefile);
2040 WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
2045 * Check to see if an inode has never been written to disk. If
2046 * so free the inodedep and return success, otherwise return failure.
2047 * This routine must be called with splbio interrupts blocked.
2049 * If we still have a bitmap dependency, then the inode has never
2050 * been written to disk. Drop the dependency as it is no longer
2051 * necessary since the inode is being deallocated. We set the
2052 * ALLCOMPLETE flags since the bitmap now properly shows that the
2053 * inode is not allocated. Even if the inode is actively being
2054 * written, it has been rolled back to its zero'ed state, so we
2055 * are ensured that a zero inode is what is on the disk. For short
2056 * lived files, this change will usually result in removing all the
2057 * dependencies from the inode so that it can be freed immediately.
2060 check_inode_unwritten(struct inodedep *inodedep)
2063 if ((inodedep->id_state & DEPCOMPLETE) != 0 ||
2064 LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2065 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2066 LIST_FIRST(&inodedep->id_inowait) != NULL ||
2067 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2068 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2069 inodedep->id_nlinkdelta != 0)
2073 * Another process might be in initiate_write_inodeblock
2074 * trying to allocate memory without holding "Softdep Lock".
2076 if ((inodedep->id_state & IOSTARTED) != 0 &&
2077 inodedep->id_savedino == NULL)
2080 inodedep->id_state |= ALLCOMPLETE;
2081 LIST_REMOVE(inodedep, id_deps);
2082 inodedep->id_buf = NULL;
2083 if (inodedep->id_state & ONWORKLIST)
2084 WORKLIST_REMOVE(&inodedep->id_list);
2085 if (inodedep->id_savedino != NULL) {
2086 kfree(inodedep->id_savedino, M_INODEDEP);
2087 inodedep->id_savedino = NULL;
2089 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) {
2229 panic("indir_trunc: lost indirdep");
2231 WORKLIST_REMOVE(wk);
2232 WORKITEM_FREE(indirdep, D_INDIRDEP);
2233 if (LIST_FIRST(&bp->b_dep) != NULL) {
2235 panic("indir_trunc: dangling dep");
2240 error = bread(ip->i_devvp, doffset, (int)fs->fs_bsize, &bp);
2245 * Recursively free indirect blocks.
2247 bap = (ufs_daddr_t *)bp->b_data;
2248 nblocks = btodb(fs->fs_bsize);
2249 for (i = NINDIR(fs) - 1; i >= 0; i--) {
2250 if ((nb = bap[i]) == 0)
2253 if ((error = indir_trunc(ip, fsbtodoff(fs, nb),
2254 level - 1, lbn + (i * lbnadd), countp)) != 0)
2257 ffs_blkfree(ip, nb, fs->fs_bsize);
2260 bp->b_flags |= B_INVAL | B_NOCACHE;
2266 * Free an allocindir.
2267 * This routine must be called with splbio interrupts blocked.
2270 free_allocindir(struct allocindir *aip, struct inodedep *inodedep)
2272 struct freefrag *freefrag;
2274 KKASSERT(lock_held(&lk) > 0);
2276 if ((aip->ai_state & DEPCOMPLETE) == 0)
2277 LIST_REMOVE(aip, ai_deps);
2278 if (aip->ai_state & ONWORKLIST)
2279 WORKLIST_REMOVE(&aip->ai_list);
2280 LIST_REMOVE(aip, ai_next);
2281 if ((freefrag = aip->ai_freefrag) != NULL) {
2282 if (inodedep == NULL)
2283 add_to_worklist(&freefrag->ff_list);
2285 WORKLIST_INSERT(&inodedep->id_bufwait,
2286 &freefrag->ff_list);
2288 WORKITEM_FREE(aip, D_ALLOCINDIR);
2292 * Directory entry addition dependencies.
2294 * When adding a new directory entry, the inode (with its incremented link
2295 * count) must be written to disk before the directory entry's pointer to it.
2296 * Also, if the inode is newly allocated, the corresponding freemap must be
2297 * updated (on disk) before the directory entry's pointer. These requirements
2298 * are met via undo/redo on the directory entry's pointer, which consists
2299 * simply of the inode number.
2301 * As directory entries are added and deleted, the free space within a
2302 * directory block can become fragmented. The ufs filesystem will compact
2303 * a fragmented directory block to make space for a new entry. When this
2304 * occurs, the offsets of previously added entries change. Any "diradd"
2305 * dependency structures corresponding to these entries must be updated with
2310 * This routine is called after the in-memory inode's link
2311 * count has been incremented, but before the directory entry's
2312 * pointer to the inode has been set.
2315 * bp: buffer containing directory block
2316 * dp: inode for directory
2317 * diroffset: offset of new entry in directory
2318 * newinum: inode referenced by new directory entry
2319 * newdirbp: non-NULL => contents of new mkdir
2322 softdep_setup_directory_add(struct buf *bp, struct inode *dp, off_t diroffset,
2323 ino_t newinum, struct buf *newdirbp)
2325 int offset; /* offset of new entry within directory block */
2326 ufs_lbn_t lbn; /* block in directory containing new entry */
2329 struct pagedep *pagedep;
2330 struct inodedep *inodedep;
2331 struct mkdir *mkdir1, *mkdir2;
2334 * Whiteouts have no dependencies.
2336 if (newinum == WINO) {
2337 if (newdirbp != NULL)
2343 lbn = lblkno(fs, diroffset);
2344 offset = blkoff(fs, diroffset);
2345 dap = kmalloc(sizeof(struct diradd), M_DIRADD,
2346 M_SOFTDEP_FLAGS | M_ZERO);
2347 dap->da_list.wk_type = D_DIRADD;
2348 dap->da_offset = offset;
2349 dap->da_newinum = newinum;
2350 dap->da_state = ATTACHED;
2351 if (newdirbp == NULL) {
2352 dap->da_state |= DEPCOMPLETE;
2355 dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
2356 mkdir1 = kmalloc(sizeof(struct mkdir), M_MKDIR,
2358 mkdir1->md_list.wk_type = D_MKDIR;
2359 mkdir1->md_state = MKDIR_BODY;
2360 mkdir1->md_diradd = dap;
2361 mkdir2 = kmalloc(sizeof(struct mkdir), M_MKDIR,
2363 mkdir2->md_list.wk_type = D_MKDIR;
2364 mkdir2->md_state = MKDIR_PARENT;
2365 mkdir2->md_diradd = dap;
2367 * Dependency on "." and ".." being written to disk.
2369 mkdir1->md_buf = newdirbp;
2371 LIST_INSERT_HEAD(&mkdirlisthd, mkdir1, md_mkdirs);
2372 WORKLIST_INSERT_BP(newdirbp, &mkdir1->md_list);
2376 * Dependency on link count increase for parent directory
2379 if (inodedep_lookup(dp->i_fs, dp->i_number, 0, &inodedep) == 0
2380 || (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2381 dap->da_state &= ~MKDIR_PARENT;
2382 WORKITEM_FREE(mkdir2, D_MKDIR);
2384 LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
2385 WORKLIST_INSERT(&inodedep->id_bufwait,&mkdir2->md_list);
2389 * Link into parent directory pagedep to await its being written.
2391 if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2392 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
2393 dap->da_pagedep = pagedep;
2394 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
2397 * Link into its inodedep. Put it on the id_bufwait list if the inode
2398 * is not yet written. If it is written, do the post-inode write
2399 * processing to put it on the id_pendinghd list.
2401 (void) inodedep_lookup(fs, newinum, DEPALLOC, &inodedep);
2402 if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
2403 diradd_inode_written(dap, inodedep);
2405 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2410 * This procedure is called to change the offset of a directory
2411 * entry when compacting a directory block which must be owned
2412 * exclusively by the caller. Note that the actual entry movement
2413 * must be done in this procedure to ensure that no I/O completions
2414 * occur while the move is in progress.
2417 * dp: inode for directory
2418 * base: address of dp->i_offset
2419 * oldloc: address of old directory location
2420 * newloc: address of new directory location
2421 * entrysize: size of directory entry
2424 softdep_change_directoryentry_offset(struct inode *dp, caddr_t base,
2425 caddr_t oldloc, caddr_t newloc,
2428 int offset, oldoffset, newoffset;
2429 struct pagedep *pagedep;
2434 lbn = lblkno(dp->i_fs, dp->i_offset);
2435 offset = blkoff(dp->i_fs, dp->i_offset);
2436 if (pagedep_lookup(dp, lbn, 0, &pagedep) == 0)
2438 oldoffset = offset + (oldloc - base);
2439 newoffset = offset + (newloc - base);
2441 LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(oldoffset)], da_pdlist) {
2442 if (dap->da_offset != oldoffset)
2444 dap->da_offset = newoffset;
2445 if (DIRADDHASH(newoffset) == DIRADDHASH(oldoffset))
2447 LIST_REMOVE(dap, da_pdlist);
2448 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(newoffset)],
2454 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist) {
2455 if (dap->da_offset == oldoffset) {
2456 dap->da_offset = newoffset;
2462 bcopy(oldloc, newloc, entrysize);
2467 * Free a diradd dependency structure. This routine must be called
2468 * with splbio interrupts blocked.
2471 free_diradd(struct diradd *dap)
2473 struct dirrem *dirrem;
2474 struct pagedep *pagedep;
2475 struct inodedep *inodedep;
2476 struct mkdir *mkdir, *nextmd;
2478 KKASSERT(lock_held(&lk) > 0);
2480 WORKLIST_REMOVE(&dap->da_list);
2481 LIST_REMOVE(dap, da_pdlist);
2482 if ((dap->da_state & DIRCHG) == 0) {
2483 pagedep = dap->da_pagedep;
2485 dirrem = dap->da_previous;
2486 pagedep = dirrem->dm_pagedep;
2487 dirrem->dm_dirinum = pagedep->pd_ino;
2488 add_to_worklist(&dirrem->dm_list);
2490 if (inodedep_lookup(VFSTOUFS(pagedep->pd_mnt)->um_fs, dap->da_newinum,
2492 (void) free_inodedep(inodedep);
2493 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
2494 for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
2495 nextmd = LIST_NEXT(mkdir, md_mkdirs);
2496 if (mkdir->md_diradd != dap)
2498 dap->da_state &= ~mkdir->md_state;
2499 WORKLIST_REMOVE(&mkdir->md_list);
2500 LIST_REMOVE(mkdir, md_mkdirs);
2501 WORKITEM_FREE(mkdir, D_MKDIR);
2503 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
2505 panic("free_diradd: unfound ref");
2508 WORKITEM_FREE(dap, D_DIRADD);
2512 * Directory entry removal dependencies.
2514 * When removing a directory entry, the entry's inode pointer must be
2515 * zero'ed on disk before the corresponding inode's link count is decremented
2516 * (possibly freeing the inode for re-use). This dependency is handled by
2517 * updating the directory entry but delaying the inode count reduction until
2518 * after the directory block has been written to disk. After this point, the
2519 * inode count can be decremented whenever it is convenient.
2523 * This routine should be called immediately after removing
2524 * a directory entry. The inode's link count should not be
2525 * decremented by the calling procedure -- the soft updates
2526 * code will do this task when it is safe.
2529 * bp: buffer containing directory block
2530 * dp: inode for the directory being modified
2531 * ip: inode for directory entry being removed
2532 * isrmdir: indicates if doing RMDIR
2535 softdep_setup_remove(struct buf *bp, struct inode *dp, struct inode *ip,
2538 struct dirrem *dirrem, *prevdirrem;
2541 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.
2543 dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
2546 * If the COMPLETE flag is clear, then there were no active
2547 * entries and we want to roll back to a zeroed entry until
2548 * the new inode is committed to disk. If the COMPLETE flag is
2549 * set then we have deleted an entry that never made it to
2550 * disk. If the entry we deleted resulted from a name change,
2551 * then the old name still resides on disk. We cannot delete
2552 * its inode (returned to us in prevdirrem) until the zeroed
2553 * directory entry gets to disk. The new inode has never been
2554 * referenced on the disk, so can be deleted immediately.
2556 if ((dirrem->dm_state & COMPLETE) == 0) {
2557 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
2561 if (prevdirrem != NULL)
2562 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
2563 prevdirrem, dm_next);
2564 dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
2566 handle_workitem_remove(dirrem);
2571 * Allocate a new dirrem if appropriate and return it along with
2572 * its associated pagedep. Called without a lock, returns with lock.
2574 static long num_dirrem; /* number of dirrem allocated */
2578 * bp: buffer containing directory block
2579 * dp: inode for the directory being modified
2580 * ip: inode for directory entry being removed
2581 * isrmdir: indicates if doing RMDIR
2582 * prevdirremp: previously referenced inode, if any
2584 static struct dirrem *
2585 newdirrem(struct buf *bp, struct inode *dp, struct inode *ip,
2586 int isrmdir, struct dirrem **prevdirremp)
2591 struct dirrem *dirrem;
2592 struct pagedep *pagedep;
2595 * Whiteouts have no deletion dependencies.
2598 panic("newdirrem: whiteout");
2600 * If we are over our limit, try to improve the situation.
2601 * Limiting the number of dirrem structures will also limit
2602 * the number of freefile and freeblks structures.
2604 if (num_dirrem > max_softdeps / 2 && speedup_syncer() == 0)
2605 (void) request_cleanup(FLUSH_REMOVE, 0);
2607 dirrem = kmalloc(sizeof(struct dirrem), M_DIRREM,
2608 M_SOFTDEP_FLAGS | M_ZERO);
2609 dirrem->dm_list.wk_type = D_DIRREM;
2610 dirrem->dm_state = isrmdir ? RMDIR : 0;
2611 dirrem->dm_mnt = ITOV(ip)->v_mount;
2612 dirrem->dm_oldinum = ip->i_number;
2613 *prevdirremp = NULL;
2616 lbn = lblkno(dp->i_fs, dp->i_offset);
2617 offset = blkoff(dp->i_fs, dp->i_offset);
2618 if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2619 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
2620 dirrem->dm_pagedep = pagedep;
2622 * Check for a diradd dependency for the same directory entry.
2623 * If present, then both dependencies become obsolete and can
2624 * be de-allocated. Check for an entry on both the pd_dirraddhd
2625 * list and the pd_pendinghd list.
2628 LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
2629 if (dap->da_offset == offset)
2633 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
2634 if (dap->da_offset == offset)
2640 * Must be ATTACHED at this point.
2642 if ((dap->da_state & ATTACHED) == 0) {
2644 panic("newdirrem: not ATTACHED");
2646 if (dap->da_newinum != ip->i_number) {
2648 panic("newdirrem: inum %"PRId64" should be %"PRId64,
2649 ip->i_number, dap->da_newinum);
2652 * If we are deleting a changed name that never made it to disk,
2653 * then return the dirrem describing the previous inode (which
2654 * represents the inode currently referenced from this entry on disk).
2656 if ((dap->da_state & DIRCHG) != 0) {
2657 *prevdirremp = dap->da_previous;
2658 dap->da_state &= ~DIRCHG;
2659 dap->da_pagedep = pagedep;
2662 * We are deleting an entry that never made it to disk.
2663 * Mark it COMPLETE so we can delete its inode immediately.
2665 dirrem->dm_state |= COMPLETE;
2671 * Directory entry change dependencies.
2673 * Changing an existing directory entry requires that an add operation
2674 * be completed first followed by a deletion. The semantics for the addition
2675 * are identical to the description of adding a new entry above except
2676 * that the rollback is to the old inode number rather than zero. Once
2677 * the addition dependency is completed, the removal is done as described
2678 * in the removal routine above.
2682 * This routine should be called immediately after changing
2683 * a directory entry. The inode's link count should not be
2684 * decremented by the calling procedure -- the soft updates
2685 * code will perform this task when it is safe.
2688 * bp: buffer containing directory block
2689 * dp: inode for the directory being modified
2690 * ip: inode for directory entry being removed
2691 * newinum: new inode number for changed entry
2692 * isrmdir: indicates if doing RMDIR
2695 softdep_setup_directory_change(struct buf *bp, struct inode *dp,
2696 struct inode *ip, ino_t newinum,
2700 struct diradd *dap = NULL;
2701 struct dirrem *dirrem, *prevdirrem;
2702 struct pagedep *pagedep;
2703 struct inodedep *inodedep;
2705 offset = blkoff(dp->i_fs, dp->i_offset);
2708 * Whiteouts do not need diradd dependencies.
2710 if (newinum != WINO) {
2711 dap = kmalloc(sizeof(struct diradd), M_DIRADD,
2712 M_SOFTDEP_FLAGS | M_ZERO);
2713 dap->da_list.wk_type = D_DIRADD;
2714 dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
2715 dap->da_offset = offset;
2716 dap->da_newinum = newinum;
2720 * Allocate a new dirrem and ACQUIRE_LOCK.
2722 dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
2723 pagedep = dirrem->dm_pagedep;
2725 * The possible values for isrmdir:
2726 * 0 - non-directory file rename
2727 * 1 - directory rename within same directory
2728 * inum - directory rename to new directory of given inode number
2729 * When renaming to a new directory, we are both deleting and
2730 * creating a new directory entry, so the link count on the new
2731 * directory should not change. Thus we do not need the followup
2732 * dirrem which is usually done in handle_workitem_remove. We set
2733 * the DIRCHG flag to tell handle_workitem_remove to skip the
2737 dirrem->dm_state |= DIRCHG;
2740 * Whiteouts have no additional dependencies,
2741 * so just put the dirrem on the correct list.
2743 if (newinum == WINO) {
2744 if ((dirrem->dm_state & COMPLETE) == 0) {
2745 LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
2748 dirrem->dm_dirinum = pagedep->pd_ino;
2749 add_to_worklist(&dirrem->dm_list);
2756 * If the COMPLETE flag is clear, then there were no active
2757 * entries and we want to roll back to the previous inode until
2758 * the new inode is committed to disk. If the COMPLETE flag is
2759 * set, then we have deleted an entry that never made it to disk.
2760 * If the entry we deleted resulted from a name change, then the old
2761 * inode reference still resides on disk. Any rollback that we do
2762 * needs to be to that old inode (returned to us in prevdirrem). If
2763 * the entry we deleted resulted from a create, then there is
2764 * no entry on the disk, so we want to roll back to zero rather
2765 * than the uncommitted inode. In either of the COMPLETE cases we
2766 * want to immediately free the unwritten and unreferenced inode.
2768 if ((dirrem->dm_state & COMPLETE) == 0) {
2769 dap->da_previous = dirrem;
2771 if (prevdirrem != NULL) {
2772 dap->da_previous = prevdirrem;
2774 dap->da_state &= ~DIRCHG;
2775 dap->da_pagedep = pagedep;
2777 dirrem->dm_dirinum = pagedep->pd_ino;
2778 add_to_worklist(&dirrem->dm_list);
2781 * Link into its inodedep. Put it on the id_bufwait list if the inode
2782 * is not yet written. If it is written, do the post-inode write
2783 * processing to put it on the id_pendinghd list.
2785 if (inodedep_lookup(dp->i_fs, newinum, DEPALLOC, &inodedep) == 0 ||
2786 (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2787 dap->da_state |= COMPLETE;
2788 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
2789 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
2791 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
2793 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2799 * Called whenever the link count on an inode is changed.
2800 * It creates an inode dependency so that the new reference(s)
2801 * to the inode cannot be committed to disk until the updated
2802 * inode has been written.
2805 * ip: the inode with the increased link count
2808 softdep_change_linkcnt(struct inode *ip)
2810 struct inodedep *inodedep;
2813 (void) inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC, &inodedep);
2814 if (ip->i_nlink < ip->i_effnlink) {
2816 panic("softdep_change_linkcnt: bad delta");
2818 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2823 * This workitem decrements the inode's link count.
2824 * If the link count reaches zero, the file is removed.
2827 handle_workitem_remove(struct dirrem *dirrem)
2829 struct inodedep *inodedep;
2835 error = VFS_VGET(dirrem->dm_mnt, NULL, dirrem->dm_oldinum, &vp);
2837 softdep_error("handle_workitem_remove: vget", error);
2842 if ((inodedep_lookup(ip->i_fs, dirrem->dm_oldinum, 0, &inodedep)) == 0){
2844 panic("handle_workitem_remove: lost inodedep");
2847 * Normal file deletion.
2849 if ((dirrem->dm_state & RMDIR) == 0) {
2851 ip->i_flag |= IN_CHANGE;
2852 if (ip->i_nlink < ip->i_effnlink) {
2854 panic("handle_workitem_remove: bad file delta");
2856 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2860 WORKITEM_FREE(dirrem, D_DIRREM);
2864 * Directory deletion. Decrement reference count for both the
2865 * just deleted parent directory entry and the reference for ".".
2866 * Next truncate the directory to length zero. When the
2867 * truncation completes, arrange to have the reference count on
2868 * the parent decremented to account for the loss of "..".
2871 ip->i_flag |= IN_CHANGE;
2872 if (ip->i_nlink < ip->i_effnlink) {
2874 panic("handle_workitem_remove: bad dir delta");
2876 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2878 if ((error = ffs_truncate(vp, (off_t)0, 0, proc0.p_ucred)) != 0)
2879 softdep_error("handle_workitem_remove: truncate", error);
2881 * Rename a directory to a new parent. Since, we are both deleting
2882 * and creating a new directory entry, the link count on the new
2883 * directory should not change. Thus we skip the followup dirrem.
2885 if (dirrem->dm_state & DIRCHG) {
2888 WORKITEM_FREE(dirrem, D_DIRREM);
2892 * If the inodedep does not exist, then the zero'ed inode has
2893 * been written to disk. If the allocated inode has never been
2894 * written to disk, then the on-disk inode is zero'ed. In either
2895 * case we can remove the file immediately.
2898 dirrem->dm_state = 0;
2899 oldinum = dirrem->dm_oldinum;
2900 dirrem->dm_oldinum = dirrem->dm_dirinum;
2901 if (inodedep_lookup(ip->i_fs, oldinum, 0, &inodedep) == 0 ||
2902 check_inode_unwritten(inodedep)) {
2905 handle_workitem_remove(dirrem);
2908 WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
2910 ip->i_flag |= IN_CHANGE;
2916 * Inode de-allocation dependencies.
2918 * When an inode's link count is reduced to zero, it can be de-allocated. We
2919 * found it convenient to postpone de-allocation until after the inode is
2920 * written to disk with its new link count (zero). At this point, all of the
2921 * on-disk inode's block pointers are nullified and, with careful dependency
2922 * list ordering, all dependencies related to the inode will be satisfied and
2923 * the corresponding dependency structures de-allocated. So, if/when the
2924 * inode is reused, there will be no mixing of old dependencies with new
2925 * ones. This artificial dependency is set up by the block de-allocation
2926 * procedure above (softdep_setup_freeblocks) and completed by the
2927 * following procedure.
2930 handle_workitem_freefile(struct freefile *freefile)
2934 struct inodedep *idp;
2939 error = inodedep_lookup(freefile->fx_fs, freefile->fx_oldinum, 0, &idp);
2942 panic("handle_workitem_freefile: inodedep survived");
2944 tip.i_devvp = freefile->fx_devvp;
2945 tip.i_dev = freefile->fx_devvp->v_rdev;
2946 tip.i_fs = freefile->fx_fs;
2948 if ((error = ffs_freefile(&vp, freefile->fx_oldinum, freefile->fx_mode)) != 0)
2949 softdep_error("handle_workitem_freefile", error);
2950 WORKITEM_FREE(freefile, D_FREEFILE);
2954 * Helper function which unlinks marker element from work list and returns
2955 * the next element on the list.
2957 static __inline struct worklist *
2958 markernext(struct worklist *marker)
2960 struct worklist *next;
2962 next = LIST_NEXT(marker, wk_list);
2963 LIST_REMOVE(marker, wk_list);
2968 * checkread, checkwrite
2970 * bioops callback - hold io_token
2973 softdep_checkread(struct buf *bp)
2975 /* nothing to do, mp lock not needed */
2980 * bioops callback - hold io_token
2983 softdep_checkwrite(struct buf *bp)
2985 /* nothing to do, mp lock not needed */
2992 * The dependency structures constructed above are most actively used when file
2993 * system blocks are written to disk. No constraints are placed on when a
2994 * block can be written, but unsatisfied update dependencies are made safe by
2995 * modifying (or replacing) the source memory for the duration of the disk
2996 * write. When the disk write completes, the memory block is again brought
2999 * In-core inode structure reclamation.
3001 * Because there are a finite number of "in-core" inode structures, they are
3002 * reused regularly. By transferring all inode-related dependencies to the
3003 * in-memory inode block and indexing them separately (via "inodedep"s), we
3004 * can allow "in-core" inode structures to be reused at any time and avoid
3005 * any increase in contention.
3007 * Called just before entering the device driver to initiate a new disk I/O.
3008 * The buffer must be locked, thus, no I/O completion operations can occur
3009 * while we are manipulating its associated dependencies.
3011 * bioops callback - hold io_token
3014 * bp: structure describing disk write to occur
3017 softdep_disk_io_initiation(struct buf *bp)
3019 struct worklist *wk;
3020 struct worklist marker;
3021 struct indirdep *indirdep;
3024 * We only care about write operations. There should never
3025 * be dependencies for reads.
3027 if (bp->b_cmd == BUF_CMD_READ)
3028 panic("softdep_disk_io_initiation: read");
3032 marker.wk_type = D_LAST + 1; /* Not a normal workitem */
3035 * Do any necessary pre-I/O processing.
3037 for (wk = LIST_FIRST(&bp->b_dep); wk; wk = markernext(&marker)) {
3038 LIST_INSERT_AFTER(wk, &marker, wk_list);
3040 switch (wk->wk_type) {
3042 initiate_write_filepage(WK_PAGEDEP(wk), bp);
3046 initiate_write_inodeblock(WK_INODEDEP(wk), bp);
3050 indirdep = WK_INDIRDEP(wk);
3051 if (indirdep->ir_state & GOINGAWAY)
3052 panic("disk_io_initiation: indirdep gone");
3054 * If there are no remaining dependencies, this
3055 * will be writing the real pointers, so the
3056 * dependency can be freed.
3058 if (LIST_FIRST(&indirdep->ir_deplisthd) == NULL) {
3059 indirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
3060 brelse(indirdep->ir_savebp);
3061 /* inline expand WORKLIST_REMOVE(wk); */
3062 wk->wk_state &= ~ONWORKLIST;
3063 LIST_REMOVE(wk, wk_list);
3064 WORKITEM_FREE(indirdep, D_INDIRDEP);
3068 * Replace up-to-date version with safe version.
3070 indirdep->ir_saveddata = kmalloc(bp->b_bcount,
3074 indirdep->ir_state &= ~ATTACHED;
3075 indirdep->ir_state |= UNDONE;
3076 bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
3077 bcopy(indirdep->ir_savebp->b_data, bp->b_data,
3089 panic("handle_disk_io_initiation: Unexpected type %s",
3090 TYPENAME(wk->wk_type));
3099 * Called from within the procedure above to deal with unsatisfied
3100 * allocation dependencies in a directory. The buffer must be locked,
3101 * thus, no I/O completion operations can occur while we are
3102 * manipulating its associated dependencies.
3105 initiate_write_filepage(struct pagedep *pagedep, struct buf *bp)
3111 if (pagedep->pd_state & IOSTARTED) {
3113 * This can only happen if there is a driver that does not
3114 * understand chaining. Here biodone will reissue the call
3115 * to strategy for the incomplete buffers.
3117 kprintf("initiate_write_filepage: already started\n");
3120 pagedep->pd_state |= IOSTARTED;
3122 for (i = 0; i < DAHASHSZ; i++) {
3123 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
3124 ep = (struct direct *)
3125 ((char *)bp->b_data + dap->da_offset);
3126 if (ep->d_ino != dap->da_newinum) {
3128 panic("%s: dir inum %d != new %"PRId64,
3129 "initiate_write_filepage",
3130 ep->d_ino, dap->da_newinum);
3132 if (dap->da_state & DIRCHG)
3133 ep->d_ino = dap->da_previous->dm_oldinum;
3136 dap->da_state &= ~ATTACHED;
3137 dap->da_state |= UNDONE;
3144 * Called from within the procedure above to deal with unsatisfied
3145 * allocation dependencies in an inodeblock. The buffer must be
3146 * locked, thus, no I/O completion operations can occur while we
3147 * are manipulating its associated dependencies.
3150 * bp: The inode block
3153 initiate_write_inodeblock(struct inodedep *inodedep, struct buf *bp)
3155 struct allocdirect *adp, *lastadp;
3156 struct ufs1_dinode *dp;
3157 struct ufs1_dinode *sip;
3159 ufs_lbn_t prevlbn = 0;
3162 if (inodedep->id_state & IOSTARTED)
3163 panic("initiate_write_inodeblock: already started");
3164 inodedep->id_state |= IOSTARTED;
3165 fs = inodedep->id_fs;
3166 dp = (struct ufs1_dinode *)bp->b_data +
3167 ino_to_fsbo(fs, inodedep->id_ino);
3169 * If the bitmap is not yet written, then the allocated
3170 * inode cannot be written to disk.
3172 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
3173 if (inodedep->id_savedino != NULL)
3174 panic("initiate_write_inodeblock: already doing I/O");
3175 sip = kmalloc(sizeof(struct ufs1_dinode), M_INODEDEP,
3177 inodedep->id_savedino = sip;
3178 *inodedep->id_savedino = *dp;
3179 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
3180 dp->di_gen = inodedep->id_savedino->di_gen;
3184 * If no dependencies, then there is nothing to roll back.
3186 inodedep->id_savedsize = dp->di_size;
3187 if (TAILQ_FIRST(&inodedep->id_inoupdt) == NULL)
3190 * Set the dependencies to busy.
3193 for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3194 adp = TAILQ_NEXT(adp, ad_next)) {
3196 if (deplist != 0 && prevlbn >= adp->ad_lbn) {
3198 panic("softdep_write_inodeblock: lbn order");
3200 prevlbn = adp->ad_lbn;
3201 if (adp->ad_lbn < NDADDR &&
3202 dp->di_db[adp->ad_lbn] != adp->ad_newblkno) {
3204 panic("%s: direct pointer #%ld mismatch %d != %d",
3205 "softdep_write_inodeblock", adp->ad_lbn,
3206 dp->di_db[adp->ad_lbn], adp->ad_newblkno);
3208 if (adp->ad_lbn >= NDADDR &&
3209 dp->di_ib[adp->ad_lbn - NDADDR] != adp->ad_newblkno) {
3211 panic("%s: indirect pointer #%ld mismatch %d != %d",
3212 "softdep_write_inodeblock", adp->ad_lbn - NDADDR,
3213 dp->di_ib[adp->ad_lbn - NDADDR], adp->ad_newblkno);
3215 deplist |= 1 << adp->ad_lbn;
3216 if ((adp->ad_state & ATTACHED) == 0) {
3218 panic("softdep_write_inodeblock: Unknown state 0x%x",
3221 #endif /* DIAGNOSTIC */
3222 adp->ad_state &= ~ATTACHED;
3223 adp->ad_state |= UNDONE;
3226 * The on-disk inode cannot claim to be any larger than the last
3227 * fragment that has been written. Otherwise, the on-disk inode
3228 * might have fragments that were not the last block in the file
3229 * which would corrupt the filesystem.
3231 for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3232 lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
3233 if (adp->ad_lbn >= NDADDR)
3235 dp->di_db[adp->ad_lbn] = adp->ad_oldblkno;
3236 /* keep going until hitting a rollback to a frag */
3237 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
3239 dp->di_size = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
3240 for (i = adp->ad_lbn + 1; i < NDADDR; i++) {
3242 if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0) {
3244 panic("softdep_write_inodeblock: lost dep1");
3246 #endif /* DIAGNOSTIC */
3249 for (i = 0; i < NIADDR; i++) {
3251 if (dp->di_ib[i] != 0 &&
3252 (deplist & ((1 << NDADDR) << i)) == 0) {
3254 panic("softdep_write_inodeblock: lost dep2");
3256 #endif /* DIAGNOSTIC */
3263 * If we have zero'ed out the last allocated block of the file,
3264 * roll back the size to the last currently allocated block.
3265 * We know that this last allocated block is a full-sized as
3266 * we already checked for fragments in the loop above.
3268 if (lastadp != NULL &&
3269 dp->di_size <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
3270 for (i = lastadp->ad_lbn; i >= 0; i--)
3271 if (dp->di_db[i] != 0)
3273 dp->di_size = (i + 1) * fs->fs_bsize;
3276 * The only dependencies are for indirect blocks.
3278 * The file size for indirect block additions is not guaranteed.
3279 * Such a guarantee would be non-trivial to achieve. The conventional
3280 * synchronous write implementation also does not make this guarantee.
3281 * Fsck should catch and fix discrepancies. Arguably, the file size
3282 * can be over-estimated without destroying integrity when the file
3283 * moves into the indirect blocks (i.e., is large). If we want to
3284 * postpone fsck, we are stuck with this argument.
3286 for (; adp; adp = TAILQ_NEXT(adp, ad_next))
3287 dp->di_ib[adp->ad_lbn - NDADDR] = 0;
3292 * This routine is called during the completion interrupt
3293 * service routine for a disk write (from the procedure called
3294 * by the device driver to inform the filesystem caches of
3295 * a request completion). It should be called early in this
3296 * procedure, before the block is made available to other
3297 * processes or other routines are called.
3299 * bioops callback - hold io_token
3302 * bp: describes the completed disk write
3305 softdep_disk_write_complete(struct buf *bp)
3307 struct worklist *wk;
3308 struct workhead reattach;
3309 struct newblk *newblk;
3310 struct allocindir *aip;
3311 struct allocdirect *adp;
3312 struct indirdep *indirdep;
3313 struct inodedep *inodedep;
3314 struct bmsafemap *bmsafemap;
3318 LIST_INIT(&reattach);
3319 while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
3320 WORKLIST_REMOVE(wk);
3321 switch (wk->wk_type) {
3324 if (handle_written_filepage(WK_PAGEDEP(wk), bp))
3325 WORKLIST_INSERT(&reattach, wk);
3329 if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
3330 WORKLIST_INSERT(&reattach, wk);
3334 bmsafemap = WK_BMSAFEMAP(wk);
3335 while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkhd))) {
3336 newblk->nb_state |= DEPCOMPLETE;
3337 newblk->nb_bmsafemap = NULL;
3338 LIST_REMOVE(newblk, nb_deps);
3341 LIST_FIRST(&bmsafemap->sm_allocdirecthd))) {
3342 adp->ad_state |= DEPCOMPLETE;
3344 LIST_REMOVE(adp, ad_deps);
3345 handle_allocdirect_partdone(adp);
3348 LIST_FIRST(&bmsafemap->sm_allocindirhd))) {
3349 aip->ai_state |= DEPCOMPLETE;
3351 LIST_REMOVE(aip, ai_deps);
3352 handle_allocindir_partdone(aip);
3355 LIST_FIRST(&bmsafemap->sm_inodedephd)) != NULL) {
3356 inodedep->id_state |= DEPCOMPLETE;
3357 LIST_REMOVE(inodedep, id_deps);
3358 inodedep->id_buf = NULL;
3360 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
3364 handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
3368 adp = WK_ALLOCDIRECT(wk);
3369 adp->ad_state |= COMPLETE;
3370 handle_allocdirect_partdone(adp);
3374 aip = WK_ALLOCINDIR(wk);
3375 aip->ai_state |= COMPLETE;
3376 handle_allocindir_partdone(aip);
3380 indirdep = WK_INDIRDEP(wk);
3381 if (indirdep->ir_state & GOINGAWAY) {
3382 panic("disk_write_complete: indirdep gone");
3384 bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
3385 kfree(indirdep->ir_saveddata, M_INDIRDEP);
3386 indirdep->ir_saveddata = 0;
3387 indirdep->ir_state &= ~UNDONE;
3388 indirdep->ir_state |= ATTACHED;
3389 while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
3390 handle_allocindir_partdone(aip);
3391 if (aip == LIST_FIRST(&indirdep->ir_donehd)) {
3392 panic("disk_write_complete: not gone");
3395 WORKLIST_INSERT(&reattach, wk);
3396 if ((bp->b_flags & B_DELWRI) == 0)
3397 stat_indir_blk_ptrs++;
3402 panic("handle_disk_write_complete: Unknown type %s",
3403 TYPENAME(wk->wk_type));
3408 * Reattach any requests that must be redone.
3410 while ((wk = LIST_FIRST(&reattach)) != NULL) {
3411 WORKLIST_REMOVE(wk);
3412 WORKLIST_INSERT_BP(bp, wk);
3419 * Called from within softdep_disk_write_complete above. Note that
3420 * this routine is always called from interrupt level with further
3421 * splbio interrupts blocked.
3424 * adp: the completed allocdirect
3427 handle_allocdirect_partdone(struct allocdirect *adp)
3429 struct allocdirect *listadp;
3430 struct inodedep *inodedep;
3433 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3435 if (adp->ad_buf != NULL)
3436 panic("handle_allocdirect_partdone: dangling dep");
3439 * The on-disk inode cannot claim to be any larger than the last
3440 * fragment that has been written. Otherwise, the on-disk inode
3441 * might have fragments that were not the last block in the file
3442 * which would corrupt the filesystem. Thus, we cannot free any
3443 * allocdirects after one whose ad_oldblkno claims a fragment as
3444 * these blocks must be rolled back to zero before writing the inode.
3445 * We check the currently active set of allocdirects in id_inoupdt.
3447 inodedep = adp->ad_inodedep;
3448 bsize = inodedep->id_fs->fs_bsize;
3449 TAILQ_FOREACH(listadp, &inodedep->id_inoupdt, ad_next) {
3450 /* found our block */
3453 /* continue if ad_oldlbn is not a fragment */
3454 if (listadp->ad_oldsize == 0 ||
3455 listadp->ad_oldsize == bsize)
3457 /* hit a fragment */
3461 * If we have reached the end of the current list without
3462 * finding the just finished dependency, then it must be
3463 * on the future dependency list. Future dependencies cannot
3464 * be freed until they are moved to the current list.
3466 if (listadp == NULL) {
3468 TAILQ_FOREACH(listadp, &inodedep->id_newinoupdt, ad_next)
3469 /* found our block */
3472 if (listadp == NULL)
3473 panic("handle_allocdirect_partdone: lost dep");
3478 * If we have found the just finished dependency, then free
3479 * it along with anything that follows it that is complete.
3481 for (; adp; adp = listadp) {
3482 listadp = TAILQ_NEXT(adp, ad_next);
3483 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3485 free_allocdirect(&inodedep->id_inoupdt, adp, 1);
3490 * Called from within softdep_disk_write_complete above. Note that
3491 * this routine is always called from interrupt level with further
3492 * splbio interrupts blocked.
3495 * aip: the completed allocindir
3498 handle_allocindir_partdone(struct allocindir *aip)
3500 struct indirdep *indirdep;
3502 if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
3504 if (aip->ai_buf != NULL)
3505 panic("handle_allocindir_partdone: dangling dependency");
3507 indirdep = aip->ai_indirdep;
3508 if (indirdep->ir_state & UNDONE) {
3509 LIST_REMOVE(aip, ai_next);
3510 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
3513 ((ufs_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
3515 LIST_REMOVE(aip, ai_next);
3516 if (aip->ai_freefrag != NULL)
3517 add_to_worklist(&aip->ai_freefrag->ff_list);
3518 WORKITEM_FREE(aip, D_ALLOCINDIR);
3522 * Called from within softdep_disk_write_complete above to restore
3523 * in-memory inode block contents to their most up-to-date state. Note
3524 * that this routine is always called from interrupt level with further
3525 * splbio interrupts blocked.
3528 * bp: buffer containing the inode block
3531 handle_written_inodeblock(struct inodedep *inodedep, struct buf *bp)
3533 struct worklist *wk, *filefree;
3534 struct allocdirect *adp, *nextadp;
3535 struct ufs1_dinode *dp;
3538 if ((inodedep->id_state & IOSTARTED) == 0)
3539 panic("handle_written_inodeblock: not started");
3541 inodedep->id_state &= ~IOSTARTED;
3542 dp = (struct ufs1_dinode *)bp->b_data +
3543 ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
3545 * If we had to rollback the inode allocation because of
3546 * bitmaps being incomplete, then simply restore it.
3547 * Keep the block dirty so that it will not be reclaimed until
3548 * all associated dependencies have been cleared and the
3549 * corresponding updates written to disk.
3551 if (inodedep->id_savedino != NULL) {
3552 *dp = *inodedep->id_savedino;
3553 kfree(inodedep->id_savedino, M_INODEDEP);
3554 inodedep->id_savedino = NULL;
3555 if ((bp->b_flags & B_DELWRI) == 0)
3556 stat_inode_bitmap++;
3560 inodedep->id_state |= COMPLETE;
3562 * Roll forward anything that had to be rolled back before
3563 * the inode could be updated.
3566 for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
3567 nextadp = TAILQ_NEXT(adp, ad_next);
3568 if (adp->ad_state & ATTACHED)
3569 panic("handle_written_inodeblock: new entry");
3571 if (adp->ad_lbn < NDADDR) {
3572 if (dp->di_db[adp->ad_lbn] != adp->ad_oldblkno) {
3573 panic("%s: %s #%ld mismatch %d != %d",
3574 "handle_written_inodeblock",
3575 "direct pointer", adp->ad_lbn,
3576 dp->di_db[adp->ad_lbn], adp->ad_oldblkno);
3578 dp->di_db[adp->ad_lbn] = adp->ad_newblkno;
3580 if (dp->di_ib[adp->ad_lbn - NDADDR] != 0) {
3581 panic("%s: %s #%ld allocated as %d",
3582 "handle_written_inodeblock",
3583 "indirect pointer", adp->ad_lbn - NDADDR,
3584 dp->di_ib[adp->ad_lbn - NDADDR]);
3586 dp->di_ib[adp->ad_lbn - NDADDR] = adp->ad_newblkno;
3588 adp->ad_state &= ~UNDONE;
3589 adp->ad_state |= ATTACHED;
3592 if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
3593 stat_direct_blk_ptrs++;
3595 * Reset the file size to its most up-to-date value.
3597 if (inodedep->id_savedsize == -1) {
3598 panic("handle_written_inodeblock: bad size");
3600 if (dp->di_size != inodedep->id_savedsize) {
3601 dp->di_size = inodedep->id_savedsize;
3604 inodedep->id_savedsize = -1;
3606 * If there were any rollbacks in the inode block, then it must be
3607 * marked dirty so that its will eventually get written back in
3613 * Process any allocdirects that completed during the update.
3615 if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
3616 handle_allocdirect_partdone(adp);
3618 * Process deallocations that were held pending until the
3619 * inode had been written to disk. Freeing of the inode
3620 * is delayed until after all blocks have been freed to
3621 * avoid creation of new <vfsid, inum, lbn> triples
3622 * before the old ones have been deleted.
3625 while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
3626 WORKLIST_REMOVE(wk);
3627 switch (wk->wk_type) {
3631 * We defer adding filefree to the worklist until
3632 * all other additions have been made to ensure
3633 * that it will be done after all the old blocks
3636 if (filefree != NULL) {
3637 panic("handle_written_inodeblock: filefree");
3643 handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
3647 diradd_inode_written(WK_DIRADD(wk), inodedep);
3651 wk->wk_state |= COMPLETE;
3652 if ((wk->wk_state & ALLCOMPLETE) != ALLCOMPLETE)
3654 /* -- fall through -- */
3657 add_to_worklist(wk);
3661 panic("handle_written_inodeblock: Unknown type %s",
3662 TYPENAME(wk->wk_type));
3666 if (filefree != NULL) {
3667 if (free_inodedep(inodedep) == 0) {
3668 panic("handle_written_inodeblock: live inodedep");
3670 add_to_worklist(filefree);
3675 * If no outstanding dependencies, free it.
3677 if (free_inodedep(inodedep) || TAILQ_FIRST(&inodedep->id_inoupdt) == 0)
3679 return (hadchanges);
3683 * Process a diradd entry after its dependent inode has been written.
3684 * This routine must be called with splbio interrupts blocked.
3687 diradd_inode_written(struct diradd *dap, struct inodedep *inodedep)
3689 struct pagedep *pagedep;
3691 dap->da_state |= COMPLETE;
3692 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3693 if (dap->da_state & DIRCHG)
3694 pagedep = dap->da_previous->dm_pagedep;
3696 pagedep = dap->da_pagedep;
3697 LIST_REMOVE(dap, da_pdlist);
3698 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3700 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
3704 * Handle the completion of a mkdir dependency.
3707 handle_written_mkdir(struct mkdir *mkdir, int type)
3710 struct pagedep *pagedep;
3712 if (mkdir->md_state != type) {
3713 panic("handle_written_mkdir: bad type");
3715 dap = mkdir->md_diradd;
3716 dap->da_state &= ~type;
3717 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
3718 dap->da_state |= DEPCOMPLETE;
3719 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3720 if (dap->da_state & DIRCHG)
3721 pagedep = dap->da_previous->dm_pagedep;
3723 pagedep = dap->da_pagedep;
3724 LIST_REMOVE(dap, da_pdlist);
3725 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3727 LIST_REMOVE(mkdir, md_mkdirs);
3728 WORKITEM_FREE(mkdir, D_MKDIR);
3732 * Called from within softdep_disk_write_complete above.
3733 * A write operation was just completed. Removed inodes can
3734 * now be freed and associated block pointers may be committed.
3735 * Note that this routine is always called from interrupt level
3736 * with further splbio interrupts blocked.
3739 * bp: buffer containing the written page
3742 handle_written_filepage(struct pagedep *pagedep, struct buf *bp)
3744 struct dirrem *dirrem;
3745 struct diradd *dap, *nextdap;
3749 if ((pagedep->pd_state & IOSTARTED) == 0) {
3750 panic("handle_written_filepage: not started");
3752 pagedep->pd_state &= ~IOSTARTED;
3754 * Process any directory removals that have been committed.
3756 while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
3757 LIST_REMOVE(dirrem, dm_next);
3758 dirrem->dm_dirinum = pagedep->pd_ino;
3759 add_to_worklist(&dirrem->dm_list);
3762 * Free any directory additions that have been committed.
3764 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
3767 * Uncommitted directory entries must be restored.
3769 for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
3770 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
3772 nextdap = LIST_NEXT(dap, da_pdlist);
3773 if (dap->da_state & ATTACHED) {
3774 panic("handle_written_filepage: attached");
3776 ep = (struct direct *)
3777 ((char *)bp->b_data + dap->da_offset);
3778 ep->d_ino = dap->da_newinum;
3779 dap->da_state &= ~UNDONE;
3780 dap->da_state |= ATTACHED;
3783 * If the inode referenced by the directory has
3784 * been written out, then the dependency can be
3785 * moved to the pending list.
3787 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3788 LIST_REMOVE(dap, da_pdlist);
3789 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
3795 * If there were any rollbacks in the directory, then it must be
3796 * marked dirty so that its will eventually get written back in
3800 if ((bp->b_flags & B_DELWRI) == 0)
3805 * If no dependencies remain, the pagedep will be freed.
3806 * Otherwise it will remain to update the page before it
3807 * is written back to disk.
3809 if (LIST_FIRST(&pagedep->pd_pendinghd) == 0) {
3810 for (i = 0; i < DAHASHSZ; i++)
3811 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) != NULL)
3813 if (i == DAHASHSZ) {
3814 LIST_REMOVE(pagedep, pd_hash);
3815 WORKITEM_FREE(pagedep, D_PAGEDEP);
3823 * Writing back in-core inode structures.
3825 * The filesystem only accesses an inode's contents when it occupies an
3826 * "in-core" inode structure. These "in-core" structures are separate from
3827 * the page frames used to cache inode blocks. Only the latter are
3828 * transferred to/from the disk. So, when the updated contents of the
3829 * "in-core" inode structure are copied to the corresponding in-memory inode
3830 * block, the dependencies are also transferred. The following procedure is
3831 * called when copying a dirty "in-core" inode to a cached inode block.
3835 * Called when an inode is loaded from disk. If the effective link count
3836 * differed from the actual link count when it was last flushed, then we
3837 * need to ensure that the correct effective link count is put back.
3840 * ip: the "in_core" copy of the inode
3843 softdep_load_inodeblock(struct inode *ip)
3845 struct inodedep *inodedep;
3848 * Check for alternate nlink count.
3850 ip->i_effnlink = ip->i_nlink;
3852 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3856 ip->i_effnlink -= inodedep->id_nlinkdelta;
3861 * This routine is called just before the "in-core" inode
3862 * information is to be copied to the in-memory inode block.
3863 * Recall that an inode block contains several inodes. If
3864 * the force flag is set, then the dependencies will be
3865 * cleared so that the update can always be made. Note that
3866 * the buffer is locked when this routine is called, so we
3867 * will never be in the middle of writing the inode block
3871 * ip: the "in_core" copy of the inode
3872 * bp: the buffer containing the inode block
3873 * waitfor: nonzero => update must be allowed
3876 softdep_update_inodeblock(struct inode *ip, struct buf *bp,
3879 struct inodedep *inodedep;
3880 struct worklist *wk;
3884 * If the effective link count is not equal to the actual link
3885 * count, then we must track the difference in an inodedep while
3886 * the inode is (potentially) tossed out of the cache. Otherwise,
3887 * if there is no existing inodedep, then there are no dependencies
3891 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3893 if (ip->i_effnlink != ip->i_nlink)
3894 panic("softdep_update_inodeblock: bad link count");
3897 if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink) {
3899 panic("softdep_update_inodeblock: bad delta");
3902 * Changes have been initiated. Anything depending on these
3903 * changes cannot occur until this inode has been written.
3905 inodedep->id_state &= ~COMPLETE;
3906 if ((inodedep->id_state & ONWORKLIST) == 0)
3907 WORKLIST_INSERT_BP(bp, &inodedep->id_list);
3909 * Any new dependencies associated with the incore inode must
3910 * now be moved to the list associated with the buffer holding
3911 * the in-memory copy of the inode. Once merged process any
3912 * allocdirects that are completed by the merger.
3914 merge_inode_lists(inodedep);
3915 if (TAILQ_FIRST(&inodedep->id_inoupdt) != NULL)
3916 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt));
3918 * Now that the inode has been pushed into the buffer, the
3919 * operations dependent on the inode being written to disk
3920 * can be moved to the id_bufwait so that they will be
3921 * processed when the buffer I/O completes.
3923 while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
3924 WORKLIST_REMOVE(wk);
3925 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
3928 * Newly allocated inodes cannot be written until the bitmap
3929 * that allocates them have been written (indicated by
3930 * DEPCOMPLETE being set in id_state). If we are doing a
3931 * forced sync (e.g., an fsync on a file), we force the bitmap
3932 * to be written so that the update can be done.
3939 if ((inodedep->id_state & DEPCOMPLETE) != 0) {
3943 gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
3945 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) != 0)
3951 if ((error = bwrite(inodedep->id_buf)) != 0)
3952 softdep_error("softdep_update_inodeblock: bwrite", error);
3956 * Merge the new inode dependency list (id_newinoupdt) into the old
3957 * inode dependency list (id_inoupdt). This routine must be called
3958 * with splbio interrupts blocked.
3961 merge_inode_lists(struct inodedep *inodedep)
3963 struct allocdirect *listadp, *newadp;
3965 newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3966 for (listadp = TAILQ_FIRST(&inodedep->id_inoupdt); listadp && newadp;) {
3967 if (listadp->ad_lbn < newadp->ad_lbn) {
3968 listadp = TAILQ_NEXT(listadp, ad_next);
3971 TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3972 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
3973 if (listadp->ad_lbn == newadp->ad_lbn) {
3974 allocdirect_merge(&inodedep->id_inoupdt, newadp,
3978 newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3980 while ((newadp = TAILQ_FIRST(&inodedep->id_newinoupdt)) != NULL) {
3981 TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3982 TAILQ_INSERT_TAIL(&inodedep->id_inoupdt, newadp, ad_next);
3987 * If we are doing an fsync, then we must ensure that any directory
3988 * entries for the inode have been written after the inode gets to disk.
3990 * bioops callback - hold io_token
3993 * vp: the "in_core" copy of the inode
3996 softdep_fsync(struct vnode *vp)
3998 struct inodedep *inodedep;
3999 struct pagedep *pagedep;
4000 struct worklist *wk;
4007 int error, flushparent;
4012 * Move check from original kernel code, possibly not needed any
4013 * more with the per-mount bioops.
4015 if ((vp->v_mount->mnt_flag & MNT_SOFTDEP) == 0)
4022 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0) {
4027 if (LIST_FIRST(&inodedep->id_inowait) != NULL ||
4028 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
4029 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
4030 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL) {
4032 panic("softdep_fsync: pending ops");
4034 for (error = 0, flushparent = 0; ; ) {
4035 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
4037 if (wk->wk_type != D_DIRADD) {
4039 panic("softdep_fsync: Unexpected type %s",
4040 TYPENAME(wk->wk_type));
4042 dap = WK_DIRADD(wk);
4044 * Flush our parent if this directory entry
4045 * has a MKDIR_PARENT dependency.
4047 if (dap->da_state & DIRCHG)
4048 pagedep = dap->da_previous->dm_pagedep;
4050 pagedep = dap->da_pagedep;
4051 mnt = pagedep->pd_mnt;
4052 parentino = pagedep->pd_ino;
4053 lbn = pagedep->pd_lbn;
4054 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE) {
4056 panic("softdep_fsync: dirty");
4058 flushparent = dap->da_state & MKDIR_PARENT;
4060 * If we are being fsync'ed as part of vgone'ing this vnode,
4061 * then we will not be able to release and recover the
4062 * vnode below, so we just have to give up on writing its
4063 * directory entry out. It will eventually be written, just
4064 * not now, but then the user was not asking to have it
4065 * written, so we are not breaking any promises.
4067 if (vp->v_flag & VRECLAIMED)
4070 * We prevent deadlock by always fetching inodes from the
4071 * root, moving down the directory tree. Thus, when fetching
4072 * our parent directory, we must unlock ourselves before
4073 * requesting the lock on our parent. See the comment in
4074 * ufs_lookup for details on possible races.
4078 error = VFS_VGET(mnt, NULL, parentino, &pvp);
4079 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4085 if ((error = ffs_update(pvp, 1)) != 0) {
4092 * Flush directory page containing the inode's name.
4094 error = bread(pvp, lblktodoff(fs, lbn), blksize(fs, VTOI(pvp), lbn), &bp);
4103 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0)
4112 * Flush all the dirty bitmaps associated with the block device
4113 * before flushing the rest of the dirty blocks so as to reduce
4114 * the number of dependencies that will have to be rolled back.
4116 static int softdep_fsync_mountdev_bp(struct buf *bp, void *data);
4119 softdep_fsync_mountdev(struct vnode *vp)
4121 if (!vn_isdisk(vp, NULL))
4122 panic("softdep_fsync_mountdev: vnode not a disk");
4124 lwkt_gettoken(&vp->v_token);
4125 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
4126 softdep_fsync_mountdev_bp, vp);
4127 lwkt_reltoken(&vp->v_token);
4128 drain_output(vp, 1);
4133 softdep_fsync_mountdev_bp(struct buf *bp, void *data)
4135 struct worklist *wk;
4136 struct vnode *vp = data;
4139 * If it is already scheduled, skip to the next buffer.
4141 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT))
4143 if (bp->b_vp != vp || (bp->b_flags & B_DELWRI) == 0) {
4145 kprintf("softdep_fsync_mountdev_bp: warning, buffer %p ripped out from under vnode %p\n", bp, vp);
4149 * We are only interested in bitmaps with outstanding
4152 if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
4153 wk->wk_type != D_BMSAFEMAP) {
4165 * This routine is called when we are trying to synchronously flush a
4166 * file. This routine must eliminate any filesystem metadata dependencies
4167 * so that the syncing routine can succeed by pushing the dirty blocks
4168 * associated with the file. If any I/O errors occur, they are returned.
4170 struct softdep_sync_metadata_info {
4175 static int softdep_sync_metadata_bp(struct buf *bp, void *data);
4178 softdep_sync_metadata(struct vnode *vp, struct thread *td)
4180 struct softdep_sync_metadata_info info;
4184 * Check whether this vnode is involved in a filesystem
4185 * that is doing soft dependency processing.
4187 if (!vn_isdisk(vp, NULL)) {
4188 if (!DOINGSOFTDEP(vp))
4191 if (vp->v_rdev->si_mountpoint == NULL ||
4192 (vp->v_rdev->si_mountpoint->mnt_flag & MNT_SOFTDEP) == 0)
4195 * Ensure that any direct block dependencies have been cleared.
4198 if ((error = flush_inodedep_deps(VTOI(vp)->i_fs, VTOI(vp)->i_number))) {
4203 * For most files, the only metadata dependencies are the
4204 * cylinder group maps that allocate their inode or blocks.
4205 * The block allocation dependencies can be found by traversing
4206 * the dependency lists for any buffers that remain on their
4207 * dirty buffer list. The inode allocation dependency will
4208 * be resolved when the inode is updated with MNT_WAIT.
4209 * This work is done in two passes. The first pass grabs most
4210 * of the buffers and begins asynchronously writing them. The
4211 * only way to wait for these asynchronous writes is to sleep
4212 * on the filesystem vnode which may stay busy for a long time
4213 * if the filesystem is active. So, instead, we make a second
4214 * pass over the dependencies blocking on each write. In the
4215 * usual case we will be blocking against a write that we
4216 * initiated, so when it is done the dependency will have been
4217 * resolved. Thus the second pass is expected to end quickly.
4219 waitfor = MNT_NOWAIT;
4222 * We must wait for any I/O in progress to finish so that
4223 * all potential buffers on the dirty list will be visible.
4225 drain_output(vp, 1);
4228 info.waitfor = waitfor;
4229 lwkt_gettoken(&vp->v_token);
4230 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
4231 softdep_sync_metadata_bp, &info);
4232 lwkt_reltoken(&vp->v_token);
4235 return(-error); /* error code */
4239 * The brief unlock is to allow any pent up dependency
4240 * processing to be done. Then proceed with the second pass.
4242 if (waitfor & MNT_NOWAIT) {
4250 * If we have managed to get rid of all the dirty buffers,
4251 * then we are done. For certain directories and block
4252 * devices, we may need to do further work.
4254 * We must wait for any I/O in progress to finish so that
4255 * all potential buffers on the dirty list will be visible.
4257 drain_output(vp, 1);
4258 if (RB_EMPTY(&vp->v_rbdirty_tree)) {
4265 * If we are trying to sync a block device, some of its buffers may
4266 * contain metadata that cannot be written until the contents of some
4267 * partially written files have been written to disk. The only easy
4268 * way to accomplish this is to sync the entire filesystem (luckily
4269 * this happens rarely).
4271 if (vn_isdisk(vp, NULL) &&
4273 vp->v_rdev->si_mountpoint && !vn_islocked(vp) &&
4274 (error = VFS_SYNC(vp->v_rdev->si_mountpoint, MNT_WAIT)) != 0)
4280 softdep_sync_metadata_bp(struct buf *bp, void *data)
4282 struct softdep_sync_metadata_info *info = data;
4283 struct pagedep *pagedep;
4284 struct allocdirect *adp;
4285 struct allocindir *aip;
4286 struct worklist *wk;
4291 if (getdirtybuf(&bp, MNT_WAIT) == 0) {
4292 kprintf("softdep_sync_metadata_bp(1): caught buf %p going away\n", bp);
4295 if (bp->b_vp != info->vp || (bp->b_flags & B_DELWRI) == 0) {
4296 kprintf("softdep_sync_metadata_bp(2): caught buf %p going away vp %p\n", bp, info->vp);
4302 * As we hold the buffer locked, none of its dependencies
4305 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4306 switch (wk->wk_type) {
4309 adp = WK_ALLOCDIRECT(wk);
4310 if (adp->ad_state & DEPCOMPLETE)
4313 if (getdirtybuf(&nbp, info->waitfor) == 0)
4316 if (info->waitfor & MNT_NOWAIT) {
4318 } else if ((error = bwrite(nbp)) != 0) {
4327 aip = WK_ALLOCINDIR(wk);
4328 if (aip->ai_state & DEPCOMPLETE)
4331 if (getdirtybuf(&nbp, info->waitfor) == 0)
4334 if (info->waitfor & MNT_NOWAIT) {
4336 } else if ((error = bwrite(nbp)) != 0) {
4347 LIST_FOREACH(aip, &WK_INDIRDEP(wk)->ir_deplisthd, ai_next) {
4348 if (aip->ai_state & DEPCOMPLETE)
4351 if (getdirtybuf(&nbp, MNT_WAIT) == 0)
4354 if ((error = bwrite(nbp)) != 0) {
4365 if ((error = flush_inodedep_deps(WK_INODEDEP(wk)->id_fs,
4366 WK_INODEDEP(wk)->id_ino)) != 0) {
4376 * We are trying to sync a directory that may
4377 * have dependencies on both its own metadata
4378 * and/or dependencies on the inodes of any
4379 * recently allocated files. We walk its diradd
4380 * lists pushing out the associated inode.
4382 pagedep = WK_PAGEDEP(wk);
4383 for (i = 0; i < DAHASHSZ; i++) {
4384 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
4387 flush_pagedep_deps(info->vp,
4389 &pagedep->pd_diraddhd[i]))) {
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 = WK_MKDIR(wk)->md_buf;
4407 if (getdirtybuf(&nbp, info->waitfor) == 0)
4410 if (info->waitfor & MNT_NOWAIT) {
4412 } else if ((error = bwrite(nbp)) != 0) {
4422 * This case should never happen if the vnode has
4423 * been properly sync'ed. However, if this function
4424 * is used at a place where the vnode has not yet
4425 * been sync'ed, this dependency can show up. So,
4426 * rather than panic, just flush it.
4428 * nbp can wind up == bp if a device node for the
4429 * same filesystem is being fsynced at the same time,
4430 * leading to a panic if we don't catch the case.
4432 nbp = WK_BMSAFEMAP(wk)->sm_buf;
4435 if (getdirtybuf(&nbp, info->waitfor) == 0)
4438 if (info->waitfor & MNT_NOWAIT) {
4440 } else if ((error = bwrite(nbp)) != 0) {
4450 panic("softdep_sync_metadata: Unknown type %s",
4451 TYPENAME(wk->wk_type));
4462 * Flush the dependencies associated with an inodedep.
4463 * Called with splbio blocked.
4466 flush_inodedep_deps(struct fs *fs, ino_t ino)
4468 struct inodedep *inodedep;
4469 struct allocdirect *adp;
4474 * This work is done in two passes. The first pass grabs most
4475 * of the buffers and begins asynchronously writing them. The
4476 * only way to wait for these asynchronous writes is to sleep
4477 * on the filesystem vnode which may stay busy for a long time
4478 * if the filesystem is active. So, instead, we make a second
4479 * pass over the dependencies blocking on each write. In the
4480 * usual case we will be blocking against a write that we
4481 * initiated, so when it is done the dependency will have been
4482 * resolved. Thus the second pass is expected to end quickly.
4483 * We give a brief window at the top of the loop to allow
4484 * any pending I/O to complete.
4486 for (waitfor = MNT_NOWAIT; ; ) {
4489 if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4491 TAILQ_FOREACH(adp, &inodedep->id_inoupdt, ad_next) {
4492 if (adp->ad_state & DEPCOMPLETE)
4495 if (getdirtybuf(&bp, waitfor) == 0) {
4496 if (waitfor & MNT_NOWAIT)
4501 if (waitfor & MNT_NOWAIT) {
4503 } else if ((error = bwrite(bp)) != 0) {
4512 TAILQ_FOREACH(adp, &inodedep->id_newinoupdt, ad_next) {
4513 if (adp->ad_state & DEPCOMPLETE)
4516 if (getdirtybuf(&bp, waitfor) == 0) {
4517 if (waitfor & MNT_NOWAIT)
4522 if (waitfor & MNT_NOWAIT) {
4524 } else if ((error = bwrite(bp)) != 0) {
4534 * If pass2, we are done, otherwise do pass 2.
4536 if (waitfor == MNT_WAIT)
4541 * Try freeing inodedep in case all dependencies have been removed.
4543 if (inodedep_lookup(fs, ino, 0, &inodedep) != 0)
4544 (void) free_inodedep(inodedep);
4549 * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
4550 * Called with splbio blocked.
4553 flush_pagedep_deps(struct vnode *pvp, struct mount *mp,
4554 struct diraddhd *diraddhdp)
4556 struct inodedep *inodedep;
4557 struct ufsmount *ump;
4560 int gotit, error = 0;
4565 while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
4567 * Flush ourselves if this directory entry
4568 * has a MKDIR_PARENT dependency.
4570 if (dap->da_state & MKDIR_PARENT) {
4572 if ((error = ffs_update(pvp, 1)) != 0)
4576 * If that cleared dependencies, go on to next.
4578 if (dap != LIST_FIRST(diraddhdp))
4580 if (dap->da_state & MKDIR_PARENT) {
4582 panic("flush_pagedep_deps: MKDIR_PARENT");
4586 * A newly allocated directory must have its "." and
4587 * ".." entries written out before its name can be
4588 * committed in its parent. We do not want or need
4589 * the full semantics of a synchronous VOP_FSYNC as
4590 * that may end up here again, once for each directory
4591 * level in the filesystem. Instead, we push the blocks
4592 * and wait for them to clear. We have to fsync twice
4593 * because the first call may choose to defer blocks
4594 * that still have dependencies, but deferral will
4595 * happen at most once.
4597 inum = dap->da_newinum;
4598 if (dap->da_state & MKDIR_BODY) {
4600 if ((error = VFS_VGET(mp, NULL, inum, &vp)) != 0)
4602 if ((error=VOP_FSYNC(vp, MNT_NOWAIT, 0)) ||
4603 (error=VOP_FSYNC(vp, MNT_NOWAIT, 0))) {
4607 drain_output(vp, 0);
4611 * If that cleared dependencies, go on to next.
4613 if (dap != LIST_FIRST(diraddhdp))
4615 if (dap->da_state & MKDIR_BODY) {
4617 panic("flush_pagedep_deps: MKDIR_BODY");
4621 * Flush the inode on which the directory entry depends.
4622 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
4623 * the only remaining dependency is that the updated inode
4624 * count must get pushed to disk. The inode has already
4625 * been pushed into its inode buffer (via VOP_UPDATE) at
4626 * the time of the reference count change. So we need only
4627 * locate that buffer, ensure that there will be no rollback
4628 * caused by a bitmap dependency, then write the inode buffer.
4630 if (inodedep_lookup(ump->um_fs, inum, 0, &inodedep) == 0) {
4632 panic("flush_pagedep_deps: lost inode");
4635 * If the inode still has bitmap dependencies,
4636 * push them to disk.
4638 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4639 gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
4641 if (gotit && (error = bwrite(inodedep->id_buf)) != 0)
4644 if (dap != LIST_FIRST(diraddhdp))
4648 * If the inode is still sitting in a buffer waiting
4649 * to be written, push it to disk.
4652 if ((error = bread(ump->um_devvp,
4653 fsbtodoff(ump->um_fs, ino_to_fsba(ump->um_fs, inum)),
4654 (int)ump->um_fs->fs_bsize, &bp)) != 0)
4656 if ((error = bwrite(bp)) != 0)
4660 * If we have failed to get rid of all the dependencies
4661 * then something is seriously wrong.
4663 if (dap == LIST_FIRST(diraddhdp)) {
4665 panic("flush_pagedep_deps: flush failed");
4674 * A large burst of file addition or deletion activity can drive the
4675 * memory load excessively high. First attempt to slow things down
4676 * using the techniques below. If that fails, this routine requests
4677 * the offending operations to fall back to running synchronously
4678 * until the memory load returns to a reasonable level.
4681 softdep_slowdown(struct vnode *vp)
4683 int max_softdeps_hard;
4685 max_softdeps_hard = max_softdeps * 11 / 10;
4686 if (num_dirrem < max_softdeps_hard / 2 &&
4687 num_inodedep < max_softdeps_hard)
4689 stat_sync_limit_hit += 1;
4694 * If memory utilization has gotten too high, deliberately slow things
4695 * down and speed up the I/O processing.
4698 request_cleanup(int resource, int islocked)
4700 struct thread *td = curthread; /* XXX */
4703 * We never hold up the filesystem syncer process.
4705 if (td == filesys_syncer)
4708 * First check to see if the work list has gotten backlogged.
4709 * If it has, co-opt this process to help clean up two entries.
4710 * Because this process may hold inodes locked, we cannot
4711 * handle any remove requests that might block on a locked
4712 * inode as that could lead to deadlock.
4714 if (num_on_worklist > max_softdeps / 10) {
4717 process_worklist_item(NULL, LK_NOWAIT);
4718 process_worklist_item(NULL, LK_NOWAIT);
4719 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;
4752 panic("request_cleanup: unknown type");
4755 * Hopefully the syncer daemon will catch up and awaken us.
4756 * We wait at most tickdelay before proceeding in any case.
4761 if (!callout_active(&handle))
4762 callout_reset(&handle, tickdelay > 2 ? tickdelay : 2,
4764 interlocked_sleep(&lk, (caddr_t)&proc_waiting, 0,
4773 * Awaken processes pausing in request_cleanup and clear proc_waiting
4774 * to indicate that there is no longer a timer running.
4777 pause_timer(void *arg)
4780 wakeup_one(&proc_waiting);
4781 if (proc_waiting > 0)
4782 callout_reset(&handle, tickdelay > 2 ? tickdelay : 2,
4785 callout_deactivate(&handle);
4789 * Flush out a directory with at least one removal dependency in an effort to
4790 * reduce the number of dirrem, freefile, and freeblks dependency structures.
4793 clear_remove(struct thread *td)
4795 struct pagedep_hashhead *pagedephd;
4796 struct pagedep *pagedep;
4797 static int next = 0;
4804 for (cnt = 0; cnt < pagedep_hash; cnt++) {
4805 pagedephd = &pagedep_hashtbl[next++];
4806 if (next >= pagedep_hash)
4808 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
4809 if (LIST_FIRST(&pagedep->pd_dirremhd) == NULL)
4811 mp = pagedep->pd_mnt;
4812 ino = pagedep->pd_ino;
4814 if ((error = VFS_VGET(mp, NULL, ino, &vp)) != 0) {
4815 softdep_error("clear_remove: vget", error);
4818 if ((error = VOP_FSYNC(vp, MNT_NOWAIT, 0)))
4819 softdep_error("clear_remove: fsync", error);
4820 drain_output(vp, 0);
4829 * Clear out a block of dirty inodes in an effort to reduce
4830 * the number of inodedep dependency structures.
4832 struct clear_inodedeps_info {
4838 clear_inodedeps_mountlist_callback(struct mount *mp, void *data)
4840 struct clear_inodedeps_info *info = data;
4842 if ((mp->mnt_flag & MNT_SOFTDEP) && info->fs == VFSTOUFS(mp)->um_fs) {
4850 clear_inodedeps(struct thread *td)
4852 struct clear_inodedeps_info info;
4853 struct inodedep_hashhead *inodedephd;
4854 struct inodedep *inodedep;
4855 static int next = 0;
4859 ino_t firstino, lastino, ino;
4863 * Pick a random inode dependency to be cleared.
4864 * We will then gather up all the inodes in its block
4865 * that have dependencies and flush them out.
4867 for (cnt = 0; cnt < inodedep_hash; cnt++) {
4868 inodedephd = &inodedep_hashtbl[next++];
4869 if (next >= inodedep_hash)
4871 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
4874 if (inodedep == NULL) {
4879 * Ugly code to find mount point given pointer to superblock.
4881 fs = inodedep->id_fs;
4884 mountlist_scan(clear_inodedeps_mountlist_callback,
4885 &info, MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
4887 * Find the last inode in the block with dependencies.
4889 firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
4890 for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
4891 if (inodedep_lookup(fs, lastino, 0, &inodedep) != 0)
4894 * Asynchronously push all but the last inode with dependencies.
4895 * Synchronously push the last inode with dependencies to ensure
4896 * that the inode block gets written to free up the inodedeps.
4898 for (ino = firstino; ino <= lastino; ino++) {
4899 if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4902 if ((error = VFS_VGET(info.mp, NULL, ino, &vp)) != 0) {
4903 softdep_error("clear_inodedeps: vget", error);
4906 if (ino == lastino) {
4907 if ((error = VOP_FSYNC(vp, MNT_WAIT, 0)))
4908 softdep_error("clear_inodedeps: fsync1", error);
4910 if ((error = VOP_FSYNC(vp, MNT_NOWAIT, 0)))
4911 softdep_error("clear_inodedeps: fsync2", error);
4912 drain_output(vp, 0);
4921 * Function to determine if the buffer has outstanding dependencies
4922 * that will cause a roll-back if the buffer is written. If wantcount
4923 * is set, return number of dependencies, otherwise just yes or no.
4925 * bioops callback - hold io_token
4928 softdep_count_dependencies(struct buf *bp, int wantcount)
4930 struct worklist *wk;
4931 struct inodedep *inodedep;
4932 struct indirdep *indirdep;
4933 struct allocindir *aip;
4934 struct pagedep *pagedep;
4943 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4944 switch (wk->wk_type) {
4947 inodedep = WK_INODEDEP(wk);
4948 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4949 /* bitmap allocation dependency */
4954 if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
4955 /* direct block pointer dependency */
4963 indirdep = WK_INDIRDEP(wk);
4965 LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
4966 /* indirect block pointer dependency */
4974 pagedep = WK_PAGEDEP(wk);
4975 for (i = 0; i < DAHASHSZ; i++) {
4977 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
4978 /* directory entry dependency */
4990 /* never a dependency on these blocks */
4995 panic("softdep_check_for_rollback: Unexpected type %s",
4996 TYPENAME(wk->wk_type));
5010 * Acquire exclusive access to a buffer. Requires softdep lock
5011 * to be held on entry. If waitfor is MNT_WAIT, may release/reacquire
5014 * Returns 1 if the buffer was locked, 0 otherwise.
5017 getdirtybuf(struct buf **bpp, int waitfor)
5027 /* Must acquire buffer lock with ffs_softdep lock held */
5028 KKASSERT(lock_held(&lk) > 0);
5029 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT);
5033 if (waitfor != MNT_WAIT)
5037 * Release ffs_softdep lock around sleep/wait for buffer lock.
5039 * We must acquire buffer lock with softdep lock held, so
5040 * we must retry locking the buffer after we wake.
5043 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL);
5047 else if (error == ENOLCK)
5050 panic("getdirtybuf: Inconsistent lock");
5053 /* Buffer wasn't dirty */
5054 if ((bp->b_flags & B_DELWRI) == 0) {
5063 * Wait for pending output on a vnode to complete.
5064 * Must be called with vnode locked.
5067 drain_output(struct vnode *vp, int islocked)
5072 while (bio_track_active(&vp->v_track_write)) {
5074 bio_track_wait(&vp->v_track_write, 0, 0);
5082 * Called whenever a buffer that is being invalidated or reallocated
5083 * contains dependencies. This should only happen if an I/O error has
5084 * occurred. The routine is called with the buffer locked.
5086 * bioops callback - hold io_token
5089 softdep_deallocate_dependencies(struct buf *bp)
5091 /* nothing to do, mp lock not needed */
5092 if ((bp->b_flags & B_ERROR) == 0)
5093 panic("softdep_deallocate_dependencies: dangling deps");
5094 softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntfromname, bp->b_error);
5095 panic("softdep_deallocate_dependencies: unrecovered I/O error");
5099 * Function to handle asynchronous write errors in the filesystem.
5102 softdep_error(char *func, int error)
5105 /* XXX should do something better! */
5106 kprintf("%s: got error %d while accessing filesystem\n", func, error);