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 *);
228 static int lock_held(struct lock *);
229 static int interlocked_sleep(struct lock *, void *, int,
232 static struct lock lk;
234 #define ACQUIRE_LOCK(lkp) acquire_lock(lkp)
235 #define FREE_LOCK(lkp) free_lock(lkp)
238 acquire_lock(struct lock *lkp)
240 lockmgr(lkp, LK_EXCLUSIVE);
244 free_lock(struct lock *lkp)
246 lockmgr(lkp, LK_RELEASE);
250 lock_held(struct lock *lkp)
252 return lockcountnb(lkp);
256 interlocked_sleep(struct lock *lkp, void *ident, int flags,
257 const char *wmesg, int timo)
261 KKASSERT(lock_held(lkp) > 0);
262 retval = lksleep(ident, lkp, flags, wmesg, timo);
267 * Place holder for real semaphores.
276 static void sema_init(struct sema *, char *, int, int);
277 static int sema_get(struct sema *, struct lock *);
278 static void sema_release(struct sema *);
280 #define NOHOLDER ((struct thread *) -1)
283 sema_init(struct sema *semap, char *name, int prio, int timo)
286 semap->holder = NOHOLDER;
294 sema_get(struct sema *semap, struct lock *interlock)
297 if (semap->value++ > 0) {
298 if (interlock != NULL) {
299 interlocked_sleep(interlock, (caddr_t)semap,
300 semap->prio, semap->name, semap->timo);
301 FREE_LOCK(interlock);
303 tsleep((caddr_t)semap, semap->prio, semap->name,
308 semap->holder = curthread;
309 if (interlock != NULL)
310 FREE_LOCK(interlock);
315 sema_release(struct sema *semap)
318 if (semap->value <= 0 || semap->holder != curthread) {
319 panic("sema_release: not held");
321 if (--semap->value > 0) {
325 semap->holder = NOHOLDER;
329 * Worklist queue management.
330 * These routines require that the lock be held.
332 static void worklist_insert(struct workhead *, struct worklist *);
333 static void worklist_remove(struct worklist *);
334 static void workitem_free(struct worklist *, int);
336 #define WORKLIST_INSERT_BP(bp, item) do { \
337 (bp)->b_ops = &softdep_bioops; \
338 worklist_insert(&(bp)->b_dep, item); \
341 #define WORKLIST_INSERT(head, item) worklist_insert(head, item)
342 #define WORKLIST_REMOVE(item) worklist_remove(item)
343 #define WORKITEM_FREE(item, type) workitem_free((struct worklist *)item, type)
346 worklist_insert(struct workhead *head, struct worklist *item)
349 KKASSERT(lock_held(&lk) > 0);
351 if (item->wk_state & ONWORKLIST) {
352 panic("worklist_insert: already on list");
354 item->wk_state |= ONWORKLIST;
355 LIST_INSERT_HEAD(head, item, wk_list);
359 worklist_remove(struct worklist *item)
362 KKASSERT(lock_held(&lk));
363 if ((item->wk_state & ONWORKLIST) == 0)
364 panic("worklist_remove: not on list");
366 item->wk_state &= ~ONWORKLIST;
367 LIST_REMOVE(item, wk_list);
371 workitem_free(struct worklist *item, int type)
374 if (item->wk_state & ONWORKLIST)
375 panic("workitem_free: still on list");
376 if (item->wk_type != type)
377 panic("workitem_free: type mismatch");
379 kfree(item, DtoM(type));
383 * Workitem queue management
385 static struct workhead softdep_workitem_pending;
386 static int num_on_worklist; /* number of worklist items to be processed */
387 static int softdep_worklist_busy; /* 1 => trying to do unmount */
388 static int softdep_worklist_req; /* serialized waiters */
389 static int max_softdeps; /* maximum number of structs before slowdown */
390 static int tickdelay = 2; /* number of ticks to pause during slowdown */
391 static int *stat_countp; /* statistic to count in proc_waiting timeout */
392 static int proc_waiting; /* tracks whether we have a timeout posted */
393 static struct callout handle; /* handle on posted proc_waiting timeout */
394 static struct thread *filesys_syncer; /* proc of filesystem syncer process */
395 static int req_clear_inodedeps; /* syncer process flush some inodedeps */
396 #define FLUSH_INODES 1
397 static int req_clear_remove; /* syncer process flush some freeblks */
398 #define FLUSH_REMOVE 2
402 static int stat_worklist_push; /* number of worklist cleanups */
403 static int stat_blk_limit_push; /* number of times block limit neared */
404 static int stat_ino_limit_push; /* number of times inode limit neared */
405 static int stat_blk_limit_hit; /* number of times block slowdown imposed */
406 static int stat_ino_limit_hit; /* number of times inode slowdown imposed */
407 static int stat_sync_limit_hit; /* number of synchronous slowdowns imposed */
408 static int stat_indir_blk_ptrs; /* bufs redirtied as indir ptrs not written */
409 static int stat_inode_bitmap; /* bufs redirtied as inode bitmap not written */
410 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
411 static int stat_dir_entry; /* bufs redirtied as dir entry cannot write */
414 #include <sys/sysctl.h>
415 SYSCTL_INT(_debug, OID_AUTO, max_softdeps, CTLFLAG_RW, &max_softdeps, 0,
416 "Maximum soft dependencies before slowdown occurs");
417 SYSCTL_INT(_debug, OID_AUTO, tickdelay, CTLFLAG_RW, &tickdelay, 0,
418 "Ticks to delay before allocating during slowdown");
419 SYSCTL_INT(_debug, OID_AUTO, worklist_push, CTLFLAG_RW, &stat_worklist_push, 0,
420 "Number of worklist cleanups");
421 SYSCTL_INT(_debug, OID_AUTO, blk_limit_push, CTLFLAG_RW, &stat_blk_limit_push, 0,
422 "Number of times block limit neared");
423 SYSCTL_INT(_debug, OID_AUTO, ino_limit_push, CTLFLAG_RW, &stat_ino_limit_push, 0,
424 "Number of times inode limit neared");
425 SYSCTL_INT(_debug, OID_AUTO, blk_limit_hit, CTLFLAG_RW, &stat_blk_limit_hit, 0,
426 "Number of times block slowdown imposed");
427 SYSCTL_INT(_debug, OID_AUTO, ino_limit_hit, CTLFLAG_RW, &stat_ino_limit_hit, 0,
428 "Number of times inode slowdown imposed ");
429 SYSCTL_INT(_debug, OID_AUTO, sync_limit_hit, CTLFLAG_RW, &stat_sync_limit_hit, 0,
430 "Number of synchronous slowdowns imposed");
431 SYSCTL_INT(_debug, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW, &stat_indir_blk_ptrs, 0,
432 "Bufs redirtied as indir ptrs not written");
433 SYSCTL_INT(_debug, OID_AUTO, inode_bitmap, CTLFLAG_RW, &stat_inode_bitmap, 0,
434 "Bufs redirtied as inode bitmap not written");
435 SYSCTL_INT(_debug, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW, &stat_direct_blk_ptrs, 0,
436 "Bufs redirtied as direct ptrs not written");
437 SYSCTL_INT(_debug, OID_AUTO, dir_entry, CTLFLAG_RW, &stat_dir_entry, 0,
438 "Bufs redirtied as dir entry cannot write");
442 * Add an item to the end of the work queue.
443 * This routine requires that the lock be held.
444 * This is the only routine that adds items to the list.
445 * The following routine is the only one that removes items
446 * and does so in order from first to last.
449 add_to_worklist(struct worklist *wk)
451 static struct worklist *worklist_tail;
453 if (wk->wk_state & ONWORKLIST) {
454 panic("add_to_worklist: already on list");
456 wk->wk_state |= ONWORKLIST;
457 if (LIST_FIRST(&softdep_workitem_pending) == NULL)
458 LIST_INSERT_HEAD(&softdep_workitem_pending, wk, wk_list);
460 LIST_INSERT_AFTER(worklist_tail, wk, wk_list);
462 num_on_worklist += 1;
466 * Process that runs once per second to handle items in the background queue.
468 * Note that we ensure that everything is done in the order in which they
469 * appear in the queue. The code below depends on this property to ensure
470 * that blocks of a file are freed before the inode itself is freed. This
471 * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
472 * until all the old ones have been purged from the dependency lists.
474 * bioops callback - hold io_token
477 softdep_process_worklist(struct mount *matchmnt)
479 thread_t td = curthread;
480 int matchcnt, loopcount;
486 * Record the process identifier of our caller so that we can give
487 * this process preferential treatment in request_cleanup below.
493 * There is no danger of having multiple processes run this
494 * code, but we have to single-thread it when softdep_flushfiles()
495 * is in operation to get an accurate count of the number of items
496 * related to its mount point that are in the list.
498 if (matchmnt == NULL) {
499 if (softdep_worklist_busy < 0) {
503 softdep_worklist_busy += 1;
507 * If requested, try removing inode or removal dependencies.
509 if (req_clear_inodedeps) {
511 req_clear_inodedeps -= 1;
512 wakeup_one(&proc_waiting);
514 if (req_clear_remove) {
516 req_clear_remove -= 1;
517 wakeup_one(&proc_waiting);
520 starttime = time_second;
521 while (num_on_worklist > 0) {
522 matchcnt += process_worklist_item(matchmnt, 0);
525 * If a umount operation wants to run the worklist
528 if (softdep_worklist_req && matchmnt == NULL) {
534 * If requested, try removing inode or removal dependencies.
536 if (req_clear_inodedeps) {
538 req_clear_inodedeps -= 1;
539 wakeup_one(&proc_waiting);
541 if (req_clear_remove) {
543 req_clear_remove -= 1;
544 wakeup_one(&proc_waiting);
547 * We do not generally want to stop for buffer space, but if
548 * we are really being a buffer hog, we will stop and wait.
550 if (loopcount++ % 128 == 0)
553 * Never allow processing to run for more than one
554 * second. Otherwise the other syncer tasks may get
555 * excessively backlogged.
557 if (starttime != time_second && matchmnt == NULL) {
562 if (matchmnt == NULL) {
563 --softdep_worklist_busy;
564 if (softdep_worklist_req && softdep_worklist_busy == 0)
565 wakeup(&softdep_worklist_req);
573 * Process one item on the worklist.
576 process_worklist_item(struct mount *matchmnt, int flags)
579 struct dirrem *dirrem;
585 if (matchmnt != NULL)
586 matchfs = VFSTOUFS(matchmnt)->um_fs;
589 * Normally we just process each item on the worklist in order.
590 * However, if we are in a situation where we cannot lock any
591 * inodes, we have to skip over any dirrem requests whose
592 * vnodes are resident and locked.
594 LIST_FOREACH(wk, &softdep_workitem_pending, wk_list) {
595 if ((flags & LK_NOWAIT) == 0 || wk->wk_type != D_DIRREM)
597 dirrem = WK_DIRREM(wk);
598 vp = ufs_ihashlookup(VFSTOUFS(dirrem->dm_mnt)->um_dev,
600 if (vp == NULL || !vn_islocked(vp))
608 num_on_worklist -= 1;
610 switch (wk->wk_type) {
613 /* removal of a directory entry */
614 if (WK_DIRREM(wk)->dm_mnt == matchmnt)
616 handle_workitem_remove(WK_DIRREM(wk));
620 /* releasing blocks and/or fragments from a file */
621 if (WK_FREEBLKS(wk)->fb_fs == matchfs)
623 handle_workitem_freeblocks(WK_FREEBLKS(wk));
627 /* releasing a fragment when replaced as a file grows */
628 if (WK_FREEFRAG(wk)->ff_fs == matchfs)
630 handle_workitem_freefrag(WK_FREEFRAG(wk));
634 /* releasing an inode when its link count drops to 0 */
635 if (WK_FREEFILE(wk)->fx_fs == matchfs)
637 handle_workitem_freefile(WK_FREEFILE(wk));
641 panic("%s_process_worklist: Unknown type %s",
642 "softdep", TYPENAME(wk->wk_type));
649 * Move dependencies from one buffer to another.
651 * bioops callback - hold io_token
654 softdep_move_dependencies(struct buf *oldbp, struct buf *newbp)
656 struct worklist *wk, *wktail;
659 if (LIST_FIRST(&newbp->b_dep) != NULL)
660 panic("softdep_move_dependencies: need merge code");
663 while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
664 LIST_REMOVE(wk, wk_list);
666 LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
668 LIST_INSERT_AFTER(wktail, wk, wk_list);
670 newbp->b_ops = &softdep_bioops;
677 * Purge the work list of all items associated with a particular mount point.
680 softdep_flushfiles(struct mount *oldmnt, int flags)
686 * Await our turn to clear out the queue, then serialize access.
689 while (softdep_worklist_busy != 0) {
690 softdep_worklist_req += 1;
691 lksleep(&softdep_worklist_req, &lk, 0, "softflush", 0);
692 softdep_worklist_req -= 1;
694 softdep_worklist_busy = -1;
697 if ((error = ffs_flushfiles(oldmnt, flags)) != 0) {
698 softdep_worklist_busy = 0;
699 if (softdep_worklist_req)
700 wakeup(&softdep_worklist_req);
704 * Alternately flush the block device associated with the mount
705 * point and process any dependencies that the flushing
706 * creates. In theory, this loop can happen at most twice,
707 * but we give it a few extra just to be sure.
709 devvp = VFSTOUFS(oldmnt)->um_devvp;
710 for (loopcnt = 10; loopcnt > 0; ) {
711 if (softdep_process_worklist(oldmnt) == 0) {
714 * Do another flush in case any vnodes were brought in
715 * as part of the cleanup operations.
717 if ((error = ffs_flushfiles(oldmnt, flags)) != 0)
720 * If we still found nothing to do, we are really done.
722 if (softdep_process_worklist(oldmnt) == 0)
725 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
726 error = VOP_FSYNC(devvp, MNT_WAIT, 0);
732 softdep_worklist_busy = 0;
733 if (softdep_worklist_req)
734 wakeup(&softdep_worklist_req);
738 * If we are unmounting then it is an error to fail. If we
739 * are simply trying to downgrade to read-only, then filesystem
740 * activity can keep us busy forever, so we just fail with EBUSY.
743 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
744 panic("softdep_flushfiles: looping");
753 * There are three types of structures that can be looked up:
754 * 1) pagedep structures identified by mount point, inode number,
756 * 2) inodedep structures identified by mount point and inode number.
757 * 3) newblk structures identified by mount point and
758 * physical block number.
760 * The "pagedep" and "inodedep" dependency structures are hashed
761 * separately from the file blocks and inodes to which they correspond.
762 * This separation helps when the in-memory copy of an inode or
763 * file block must be replaced. It also obviates the need to access
764 * an inode or file page when simply updating (or de-allocating)
765 * dependency structures. Lookup of newblk structures is needed to
766 * find newly allocated blocks when trying to associate them with
767 * their allocdirect or allocindir structure.
769 * The lookup routines optionally create and hash a new instance when
770 * an existing entry is not found.
772 #define DEPALLOC 0x0001 /* allocate structure if lookup fails */
773 #define NODELAY 0x0002 /* cannot do background work */
776 * Structures and routines associated with pagedep caching.
778 LIST_HEAD(pagedep_hashhead, pagedep) *pagedep_hashtbl;
779 u_long pagedep_hash; /* size of hash table - 1 */
780 #define PAGEDEP_HASH(mp, inum, lbn) \
781 (&pagedep_hashtbl[((((register_t)(mp)) >> 13) + (inum) + (lbn)) & \
783 static struct sema pagedep_in_progress;
786 * Helper routine for pagedep_lookup()
790 pagedep_find(struct pagedep_hashhead *pagedephd, ino_t ino, ufs_lbn_t lbn,
793 struct pagedep *pagedep;
795 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
796 if (ino == pagedep->pd_ino &&
797 lbn == pagedep->pd_lbn &&
798 mp == pagedep->pd_mnt) {
806 * Look up a pagedep. Return 1 if found, 0 if not found.
807 * If not found, allocate if DEPALLOC flag is passed.
808 * Found or allocated entry is returned in pagedeppp.
809 * This routine must be called with splbio interrupts blocked.
812 pagedep_lookup(struct inode *ip, ufs_lbn_t lbn, int flags,
813 struct pagedep **pagedeppp)
815 struct pagedep *pagedep;
816 struct pagedep_hashhead *pagedephd;
820 KKASSERT(lock_held(&lk) > 0);
822 mp = ITOV(ip)->v_mount;
823 pagedephd = PAGEDEP_HASH(mp, ip->i_number, lbn);
825 *pagedeppp = pagedep_find(pagedephd, ip->i_number, lbn, mp);
828 if ((flags & DEPALLOC) == 0)
830 if (sema_get(&pagedep_in_progress, &lk) == 0) {
834 pagedep = kmalloc(sizeof(struct pagedep), M_PAGEDEP,
835 M_SOFTDEP_FLAGS | M_ZERO);
837 if (pagedep_find(pagedephd, ip->i_number, lbn, mp)) {
838 kprintf("pagedep_lookup: blocking race avoided\n");
840 sema_release(&pagedep_in_progress);
841 kfree(pagedep, M_PAGEDEP);
845 pagedep->pd_list.wk_type = D_PAGEDEP;
846 pagedep->pd_mnt = mp;
847 pagedep->pd_ino = ip->i_number;
848 pagedep->pd_lbn = lbn;
849 LIST_INIT(&pagedep->pd_dirremhd);
850 LIST_INIT(&pagedep->pd_pendinghd);
851 for (i = 0; i < DAHASHSZ; i++)
852 LIST_INIT(&pagedep->pd_diraddhd[i]);
854 LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
855 sema_release(&pagedep_in_progress);
856 *pagedeppp = pagedep;
861 * Structures and routines associated with inodedep caching.
863 LIST_HEAD(inodedep_hashhead, inodedep) *inodedep_hashtbl;
864 static u_long inodedep_hash; /* size of hash table - 1 */
865 static long num_inodedep; /* number of inodedep allocated */
866 #define INODEDEP_HASH(fs, inum) \
867 (&inodedep_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & inodedep_hash])
868 static struct sema inodedep_in_progress;
871 * Helper routine for inodedep_lookup()
875 inodedep_find(struct inodedep_hashhead *inodedephd, struct fs *fs, ino_t inum)
877 struct inodedep *inodedep;
879 LIST_FOREACH(inodedep, inodedephd, id_hash) {
880 if (inum == inodedep->id_ino && fs == inodedep->id_fs)
887 * Look up a inodedep. Return 1 if found, 0 if not found.
888 * If not found, allocate if DEPALLOC flag is passed.
889 * Found or allocated entry is returned in inodedeppp.
890 * This routine must be called with splbio interrupts blocked.
893 inodedep_lookup(struct fs *fs, ino_t inum, int flags,
894 struct inodedep **inodedeppp)
896 struct inodedep *inodedep;
897 struct inodedep_hashhead *inodedephd;
900 KKASSERT(lock_held(&lk) > 0);
903 inodedephd = INODEDEP_HASH(fs, inum);
905 *inodedeppp = inodedep_find(inodedephd, fs, inum);
908 if ((flags & DEPALLOC) == 0)
911 * If we are over our limit, try to improve the situation.
913 if (num_inodedep > max_softdeps && firsttry &&
914 speedup_syncer() == 0 && (flags & NODELAY) == 0 &&
915 request_cleanup(FLUSH_INODES, 1)) {
919 if (sema_get(&inodedep_in_progress, &lk) == 0) {
923 inodedep = kmalloc(sizeof(struct inodedep), M_INODEDEP,
924 M_SOFTDEP_FLAGS | M_ZERO);
925 if (inodedep_find(inodedephd, fs, inum)) {
926 kprintf("inodedep_lookup: blocking race avoided\n");
928 sema_release(&inodedep_in_progress);
929 kfree(inodedep, M_INODEDEP);
932 inodedep->id_list.wk_type = D_INODEDEP;
933 inodedep->id_fs = fs;
934 inodedep->id_ino = inum;
935 inodedep->id_state = ALLCOMPLETE;
936 inodedep->id_nlinkdelta = 0;
937 inodedep->id_savedino = NULL;
938 inodedep->id_savedsize = -1;
939 inodedep->id_buf = NULL;
940 LIST_INIT(&inodedep->id_pendinghd);
941 LIST_INIT(&inodedep->id_inowait);
942 LIST_INIT(&inodedep->id_bufwait);
943 TAILQ_INIT(&inodedep->id_inoupdt);
944 TAILQ_INIT(&inodedep->id_newinoupdt);
947 LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
948 sema_release(&inodedep_in_progress);
949 *inodedeppp = inodedep;
954 * Structures and routines associated with newblk caching.
956 LIST_HEAD(newblk_hashhead, newblk) *newblk_hashtbl;
957 u_long newblk_hash; /* size of hash table - 1 */
958 #define NEWBLK_HASH(fs, inum) \
959 (&newblk_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & newblk_hash])
960 static struct sema newblk_in_progress;
963 * Helper routine for newblk_lookup()
967 newblk_find(struct newblk_hashhead *newblkhd, struct fs *fs,
968 ufs_daddr_t newblkno)
970 struct newblk *newblk;
972 LIST_FOREACH(newblk, newblkhd, nb_hash) {
973 if (newblkno == newblk->nb_newblkno && fs == newblk->nb_fs)
980 * Look up a newblk. Return 1 if found, 0 if not found.
981 * If not found, allocate if DEPALLOC flag is passed.
982 * Found or allocated entry is returned in newblkpp.
985 newblk_lookup(struct fs *fs, ufs_daddr_t newblkno, int flags,
986 struct newblk **newblkpp)
988 struct newblk *newblk;
989 struct newblk_hashhead *newblkhd;
991 newblkhd = NEWBLK_HASH(fs, newblkno);
993 *newblkpp = newblk_find(newblkhd, fs, newblkno);
996 if ((flags & DEPALLOC) == 0)
998 if (sema_get(&newblk_in_progress, 0) == 0)
1000 newblk = kmalloc(sizeof(struct newblk), M_NEWBLK,
1001 M_SOFTDEP_FLAGS | M_ZERO);
1003 if (newblk_find(newblkhd, fs, newblkno)) {
1004 kprintf("newblk_lookup: blocking race avoided\n");
1005 sema_release(&pagedep_in_progress);
1006 kfree(newblk, M_NEWBLK);
1009 newblk->nb_state = 0;
1011 newblk->nb_newblkno = newblkno;
1012 LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
1013 sema_release(&newblk_in_progress);
1019 * Executed during filesystem system initialization before
1020 * mounting any filesystems.
1023 softdep_initialize(void)
1025 callout_init(&handle);
1027 LIST_INIT(&mkdirlisthd);
1028 LIST_INIT(&softdep_workitem_pending);
1029 max_softdeps = min(desiredvnodes * 8,
1030 M_INODEDEP->ks_limit / (2 * sizeof(struct inodedep)));
1031 pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
1033 lockinit(&lk, "ffs_softdep", 0, LK_CANRECURSE);
1034 sema_init(&pagedep_in_progress, "pagedep", 0, 0);
1035 inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP, &inodedep_hash);
1036 sema_init(&inodedep_in_progress, "inodedep", 0, 0);
1037 newblk_hashtbl = hashinit(64, M_NEWBLK, &newblk_hash);
1038 sema_init(&newblk_in_progress, "newblk", 0, 0);
1039 add_bio_ops(&softdep_bioops);
1043 * Called at mount time to notify the dependency code that a
1044 * filesystem wishes to use it.
1047 softdep_mount(struct vnode *devvp, struct mount *mp, struct fs *fs)
1049 struct csum cstotal;
1054 mp->mnt_flag &= ~MNT_ASYNC;
1055 mp->mnt_flag |= MNT_SOFTDEP;
1056 mp->mnt_bioops = &softdep_bioops;
1058 * When doing soft updates, the counters in the
1059 * superblock may have gotten out of sync, so we have
1060 * to scan the cylinder groups and recalculate them.
1062 if (fs->fs_clean != 0)
1064 bzero(&cstotal, sizeof cstotal);
1065 for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
1066 if ((error = bread(devvp, fsbtodoff(fs, cgtod(fs, cyl)),
1067 fs->fs_cgsize, &bp)) != 0) {
1071 cgp = (struct cg *)bp->b_data;
1072 cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
1073 cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
1074 cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
1075 cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
1076 fs->fs_cs(fs, cyl) = cgp->cg_cs;
1080 if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
1081 kprintf("ffs_mountfs: superblock updated for soft updates\n");
1083 bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
1088 * Protecting the freemaps (or bitmaps).
1090 * To eliminate the need to execute fsck before mounting a filesystem
1091 * after a power failure, one must (conservatively) guarantee that the
1092 * on-disk copy of the bitmaps never indicate that a live inode or block is
1093 * free. So, when a block or inode is allocated, the bitmap should be
1094 * updated (on disk) before any new pointers. When a block or inode is
1095 * freed, the bitmap should not be updated until all pointers have been
1096 * reset. The latter dependency is handled by the delayed de-allocation
1097 * approach described below for block and inode de-allocation. The former
1098 * dependency is handled by calling the following procedure when a block or
1099 * inode is allocated. When an inode is allocated an "inodedep" is created
1100 * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
1101 * Each "inodedep" is also inserted into the hash indexing structure so
1102 * that any additional link additions can be made dependent on the inode
1105 * The ufs filesystem maintains a number of free block counts (e.g., per
1106 * cylinder group, per cylinder and per <cylinder, rotational position> pair)
1107 * in addition to the bitmaps. These counts are used to improve efficiency
1108 * during allocation and therefore must be consistent with the bitmaps.
1109 * There is no convenient way to guarantee post-crash consistency of these
1110 * counts with simple update ordering, for two main reasons: (1) The counts
1111 * and bitmaps for a single cylinder group block are not in the same disk
1112 * sector. If a disk write is interrupted (e.g., by power failure), one may
1113 * be written and the other not. (2) Some of the counts are located in the
1114 * superblock rather than the cylinder group block. So, we focus our soft
1115 * updates implementation on protecting the bitmaps. When mounting a
1116 * filesystem, we recompute the auxiliary counts from the bitmaps.
1120 * Called just after updating the cylinder group block to allocate an inode.
1123 * bp: buffer for cylgroup block with inode map
1124 * ip: inode related to allocation
1125 * newinum: new inode number being allocated
1128 softdep_setup_inomapdep(struct buf *bp, struct inode *ip, ino_t newinum)
1130 struct inodedep *inodedep;
1131 struct bmsafemap *bmsafemap;
1134 * Create a dependency for the newly allocated inode.
1135 * Panic if it already exists as something is seriously wrong.
1136 * Otherwise add it to the dependency list for the buffer holding
1137 * the cylinder group map from which it was allocated.
1140 if ((inodedep_lookup(ip->i_fs, newinum, DEPALLOC|NODELAY, &inodedep))) {
1142 panic("softdep_setup_inomapdep: found inode");
1144 inodedep->id_buf = bp;
1145 inodedep->id_state &= ~DEPCOMPLETE;
1146 bmsafemap = bmsafemap_lookup(bp);
1147 LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
1152 * Called just after updating the cylinder group block to
1153 * allocate block or fragment.
1156 * bp: buffer for cylgroup block with block map
1157 * fs: filesystem doing allocation
1158 * newblkno: number of newly allocated block
1161 softdep_setup_blkmapdep(struct buf *bp, struct fs *fs,
1162 ufs_daddr_t newblkno)
1164 struct newblk *newblk;
1165 struct bmsafemap *bmsafemap;
1168 * Create a dependency for the newly allocated block.
1169 * Add it to the dependency list for the buffer holding
1170 * the cylinder group map from which it was allocated.
1172 if (newblk_lookup(fs, newblkno, DEPALLOC, &newblk) != 0)
1173 panic("softdep_setup_blkmapdep: found block");
1175 newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(bp);
1176 LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
1181 * Find the bmsafemap associated with a cylinder group buffer.
1182 * If none exists, create one. The buffer must be locked when
1183 * this routine is called and this routine must be called with
1184 * splbio interrupts blocked.
1186 static struct bmsafemap *
1187 bmsafemap_lookup(struct buf *bp)
1189 struct bmsafemap *bmsafemap;
1190 struct worklist *wk;
1192 KKASSERT(lock_held(&lk) > 0);
1194 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
1195 if (wk->wk_type == D_BMSAFEMAP)
1196 return (WK_BMSAFEMAP(wk));
1199 bmsafemap = kmalloc(sizeof(struct bmsafemap), M_BMSAFEMAP,
1201 bmsafemap->sm_list.wk_type = D_BMSAFEMAP;
1202 bmsafemap->sm_list.wk_state = 0;
1203 bmsafemap->sm_buf = bp;
1204 LIST_INIT(&bmsafemap->sm_allocdirecthd);
1205 LIST_INIT(&bmsafemap->sm_allocindirhd);
1206 LIST_INIT(&bmsafemap->sm_inodedephd);
1207 LIST_INIT(&bmsafemap->sm_newblkhd);
1209 WORKLIST_INSERT_BP(bp, &bmsafemap->sm_list);
1214 * Direct block allocation dependencies.
1216 * When a new block is allocated, the corresponding disk locations must be
1217 * initialized (with zeros or new data) before the on-disk inode points to
1218 * them. Also, the freemap from which the block was allocated must be
1219 * updated (on disk) before the inode's pointer. These two dependencies are
1220 * independent of each other and are needed for all file blocks and indirect
1221 * blocks that are pointed to directly by the inode. Just before the
1222 * "in-core" version of the inode is updated with a newly allocated block
1223 * number, a procedure (below) is called to setup allocation dependency
1224 * structures. These structures are removed when the corresponding
1225 * dependencies are satisfied or when the block allocation becomes obsolete
1226 * (i.e., the file is deleted, the block is de-allocated, or the block is a
1227 * fragment that gets upgraded). All of these cases are handled in
1228 * procedures described later.
1230 * When a file extension causes a fragment to be upgraded, either to a larger
1231 * fragment or to a full block, the on-disk location may change (if the
1232 * previous fragment could not simply be extended). In this case, the old
1233 * fragment must be de-allocated, but not until after the inode's pointer has
1234 * been updated. In most cases, this is handled by later procedures, which
1235 * will construct a "freefrag" structure to be added to the workitem queue
1236 * when the inode update is complete (or obsolete). The main exception to
1237 * this is when an allocation occurs while a pending allocation dependency
1238 * (for the same block pointer) remains. This case is handled in the main
1239 * allocation dependency setup procedure by immediately freeing the
1240 * unreferenced fragments.
1243 * ip: inode to which block is being added
1244 * lbn: block pointer within inode
1245 * newblkno: disk block number being added
1246 * oldblkno: previous block number, 0 unless frag
1247 * newsize: size of new block
1248 * oldsize: size of new block
1249 * bp: bp for allocated block
1252 softdep_setup_allocdirect(struct inode *ip, ufs_lbn_t lbn, ufs_daddr_t newblkno,
1253 ufs_daddr_t oldblkno, long newsize, long oldsize,
1256 struct allocdirect *adp, *oldadp;
1257 struct allocdirectlst *adphead;
1258 struct bmsafemap *bmsafemap;
1259 struct inodedep *inodedep;
1260 struct pagedep *pagedep;
1261 struct newblk *newblk;
1263 adp = kmalloc(sizeof(struct allocdirect), M_ALLOCDIRECT,
1264 M_SOFTDEP_FLAGS | M_ZERO);
1265 adp->ad_list.wk_type = D_ALLOCDIRECT;
1267 adp->ad_newblkno = newblkno;
1268 adp->ad_oldblkno = oldblkno;
1269 adp->ad_newsize = newsize;
1270 adp->ad_oldsize = oldsize;
1271 adp->ad_state = ATTACHED;
1272 if (newblkno == oldblkno)
1273 adp->ad_freefrag = NULL;
1275 adp->ad_freefrag = newfreefrag(ip, oldblkno, oldsize);
1277 if (newblk_lookup(ip->i_fs, newblkno, 0, &newblk) == 0)
1278 panic("softdep_setup_allocdirect: lost block");
1281 inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC | NODELAY, &inodedep);
1282 adp->ad_inodedep = inodedep;
1284 if (newblk->nb_state == DEPCOMPLETE) {
1285 adp->ad_state |= DEPCOMPLETE;
1288 bmsafemap = newblk->nb_bmsafemap;
1289 adp->ad_buf = bmsafemap->sm_buf;
1290 LIST_REMOVE(newblk, nb_deps);
1291 LIST_INSERT_HEAD(&bmsafemap->sm_allocdirecthd, adp, ad_deps);
1293 LIST_REMOVE(newblk, nb_hash);
1294 kfree(newblk, M_NEWBLK);
1296 WORKLIST_INSERT_BP(bp, &adp->ad_list);
1297 if (lbn >= NDADDR) {
1298 /* allocating an indirect block */
1299 if (oldblkno != 0) {
1301 panic("softdep_setup_allocdirect: non-zero indir");
1305 * Allocating a direct block.
1307 * If we are allocating a directory block, then we must
1308 * allocate an associated pagedep to track additions and
1311 if ((ip->i_mode & IFMT) == IFDIR &&
1312 pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0) {
1313 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
1317 * The list of allocdirects must be kept in sorted and ascending
1318 * order so that the rollback routines can quickly determine the
1319 * first uncommitted block (the size of the file stored on disk
1320 * ends at the end of the lowest committed fragment, or if there
1321 * are no fragments, at the end of the highest committed block).
1322 * Since files generally grow, the typical case is that the new
1323 * block is to be added at the end of the list. We speed this
1324 * special case by checking against the last allocdirect in the
1325 * list before laboriously traversing the list looking for the
1328 adphead = &inodedep->id_newinoupdt;
1329 oldadp = TAILQ_LAST(adphead, allocdirectlst);
1330 if (oldadp == NULL || oldadp->ad_lbn <= lbn) {
1331 /* insert at end of list */
1332 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
1333 if (oldadp != NULL && oldadp->ad_lbn == lbn)
1334 allocdirect_merge(adphead, adp, oldadp);
1338 TAILQ_FOREACH(oldadp, adphead, ad_next) {
1339 if (oldadp->ad_lbn >= lbn)
1342 if (oldadp == NULL) {
1344 panic("softdep_setup_allocdirect: lost entry");
1346 /* insert in middle of list */
1347 TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
1348 if (oldadp->ad_lbn == lbn)
1349 allocdirect_merge(adphead, adp, oldadp);
1354 * Replace an old allocdirect dependency with a newer one.
1355 * This routine must be called with splbio interrupts blocked.
1358 * adphead: head of list holding allocdirects
1359 * newadp: allocdirect being added
1360 * oldadp: existing allocdirect being checked
1363 allocdirect_merge(struct allocdirectlst *adphead,
1364 struct allocdirect *newadp,
1365 struct allocdirect *oldadp)
1367 struct freefrag *freefrag;
1369 KKASSERT(lock_held(&lk) > 0);
1371 if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
1372 newadp->ad_oldsize != oldadp->ad_newsize ||
1373 newadp->ad_lbn >= NDADDR) {
1375 panic("allocdirect_check: old %d != new %d || lbn %ld >= %d",
1376 newadp->ad_oldblkno, oldadp->ad_newblkno, newadp->ad_lbn,
1379 newadp->ad_oldblkno = oldadp->ad_oldblkno;
1380 newadp->ad_oldsize = oldadp->ad_oldsize;
1382 * If the old dependency had a fragment to free or had never
1383 * previously had a block allocated, then the new dependency
1384 * can immediately post its freefrag and adopt the old freefrag.
1385 * This action is done by swapping the freefrag dependencies.
1386 * The new dependency gains the old one's freefrag, and the
1387 * old one gets the new one and then immediately puts it on
1388 * the worklist when it is freed by free_allocdirect. It is
1389 * not possible to do this swap when the old dependency had a
1390 * non-zero size but no previous fragment to free. This condition
1391 * arises when the new block is an extension of the old block.
1392 * Here, the first part of the fragment allocated to the new
1393 * dependency is part of the block currently claimed on disk by
1394 * the old dependency, so cannot legitimately be freed until the
1395 * conditions for the new dependency are fulfilled.
1397 if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
1398 freefrag = newadp->ad_freefrag;
1399 newadp->ad_freefrag = oldadp->ad_freefrag;
1400 oldadp->ad_freefrag = freefrag;
1402 free_allocdirect(adphead, oldadp, 0);
1406 * Allocate a new freefrag structure if needed.
1408 static struct freefrag *
1409 newfreefrag(struct inode *ip, ufs_daddr_t blkno, long size)
1411 struct freefrag *freefrag;
1417 if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
1418 panic("newfreefrag: frag size");
1419 freefrag = kmalloc(sizeof(struct freefrag), M_FREEFRAG,
1421 freefrag->ff_list.wk_type = D_FREEFRAG;
1422 freefrag->ff_state = ip->i_uid & ~ONWORKLIST; /* XXX - used below */
1423 freefrag->ff_inum = ip->i_number;
1424 freefrag->ff_fs = fs;
1425 freefrag->ff_devvp = ip->i_devvp;
1426 freefrag->ff_blkno = blkno;
1427 freefrag->ff_fragsize = size;
1432 * This workitem de-allocates fragments that were replaced during
1433 * file block allocation.
1436 handle_workitem_freefrag(struct freefrag *freefrag)
1440 tip.i_fs = freefrag->ff_fs;
1441 tip.i_devvp = freefrag->ff_devvp;
1442 tip.i_dev = freefrag->ff_devvp->v_rdev;
1443 tip.i_number = freefrag->ff_inum;
1444 tip.i_uid = freefrag->ff_state & ~ONWORKLIST; /* XXX - set above */
1445 ffs_blkfree(&tip, freefrag->ff_blkno, freefrag->ff_fragsize);
1446 kfree(freefrag, M_FREEFRAG);
1450 * Indirect block allocation dependencies.
1452 * The same dependencies that exist for a direct block also exist when
1453 * a new block is allocated and pointed to by an entry in a block of
1454 * indirect pointers. The undo/redo states described above are also
1455 * used here. Because an indirect block contains many pointers that
1456 * may have dependencies, a second copy of the entire in-memory indirect
1457 * block is kept. The buffer cache copy is always completely up-to-date.
1458 * The second copy, which is used only as a source for disk writes,
1459 * contains only the safe pointers (i.e., those that have no remaining
1460 * update dependencies). The second copy is freed when all pointers
1461 * are safe. The cache is not allowed to replace indirect blocks with
1462 * pending update dependencies. If a buffer containing an indirect
1463 * block with dependencies is written, these routines will mark it
1464 * dirty again. It can only be successfully written once all the
1465 * dependencies are removed. The ffs_fsync routine in conjunction with
1466 * softdep_sync_metadata work together to get all the dependencies
1467 * removed so that a file can be successfully written to disk. Three
1468 * procedures are used when setting up indirect block pointer
1469 * dependencies. The division is necessary because of the organization
1470 * of the "balloc" routine and because of the distinction between file
1471 * pages and file metadata blocks.
1475 * Allocate a new allocindir structure.
1478 * ip: inode for file being extended
1479 * ptrno: offset of pointer in indirect block
1480 * newblkno: disk block number being added
1481 * oldblkno: previous block number, 0 if none
1483 static struct allocindir *
1484 newallocindir(struct inode *ip, int ptrno, ufs_daddr_t newblkno,
1485 ufs_daddr_t oldblkno)
1487 struct allocindir *aip;
1489 aip = kmalloc(sizeof(struct allocindir), M_ALLOCINDIR,
1490 M_SOFTDEP_FLAGS | M_ZERO);
1491 aip->ai_list.wk_type = D_ALLOCINDIR;
1492 aip->ai_state = ATTACHED;
1493 aip->ai_offset = ptrno;
1494 aip->ai_newblkno = newblkno;
1495 aip->ai_oldblkno = oldblkno;
1496 aip->ai_freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize);
1501 * Called just before setting an indirect block pointer
1502 * to a newly allocated file page.
1505 * ip: inode for file being extended
1506 * lbn: allocated block number within file
1507 * bp: buffer with indirect blk referencing page
1508 * ptrno: offset of pointer in indirect block
1509 * newblkno: disk block number being added
1510 * oldblkno: previous block number, 0 if none
1511 * nbp: buffer holding allocated page
1514 softdep_setup_allocindir_page(struct inode *ip, ufs_lbn_t lbn,
1515 struct buf *bp, int ptrno,
1516 ufs_daddr_t newblkno, ufs_daddr_t oldblkno,
1519 struct allocindir *aip;
1520 struct pagedep *pagedep;
1522 aip = newallocindir(ip, ptrno, newblkno, oldblkno);
1525 * If we are allocating a directory page, then we must
1526 * allocate an associated pagedep to track additions and
1529 if ((ip->i_mode & IFMT) == IFDIR &&
1530 pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0)
1531 WORKLIST_INSERT_BP(nbp, &pagedep->pd_list);
1532 WORKLIST_INSERT_BP(nbp, &aip->ai_list);
1534 setup_allocindir_phase2(bp, ip, aip);
1538 * Called just before setting an indirect block pointer to a
1539 * newly allocated indirect block.
1541 * nbp: newly allocated indirect block
1542 * ip: inode for file being extended
1543 * bp: indirect block referencing allocated block
1544 * ptrno: offset of pointer in indirect block
1545 * newblkno: disk block number being added
1548 softdep_setup_allocindir_meta(struct buf *nbp, struct inode *ip,
1549 struct buf *bp, int ptrno,
1550 ufs_daddr_t newblkno)
1552 struct allocindir *aip;
1554 aip = newallocindir(ip, ptrno, newblkno, 0);
1556 WORKLIST_INSERT_BP(nbp, &aip->ai_list);
1558 setup_allocindir_phase2(bp, ip, aip);
1562 * Called to finish the allocation of the "aip" allocated
1563 * by one of the two routines above.
1566 * bp: in-memory copy of the indirect block
1567 * ip: inode for file being extended
1568 * aip: allocindir allocated by the above routines
1571 setup_allocindir_phase2(struct buf *bp, struct inode *ip,
1572 struct allocindir *aip)
1574 struct worklist *wk;
1575 struct indirdep *indirdep, *newindirdep;
1576 struct bmsafemap *bmsafemap;
1577 struct allocindir *oldaip;
1578 struct freefrag *freefrag;
1579 struct newblk *newblk;
1581 if (bp->b_loffset >= 0)
1582 panic("setup_allocindir_phase2: not indir blk");
1583 for (indirdep = NULL, newindirdep = NULL; ; ) {
1585 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
1586 if (wk->wk_type != D_INDIRDEP)
1588 indirdep = WK_INDIRDEP(wk);
1591 if (indirdep == NULL && newindirdep) {
1592 indirdep = newindirdep;
1593 WORKLIST_INSERT_BP(bp, &indirdep->ir_list);
1598 if (newblk_lookup(ip->i_fs, aip->ai_newblkno, 0,
1600 panic("setup_allocindir: lost block");
1602 if (newblk->nb_state == DEPCOMPLETE) {
1603 aip->ai_state |= DEPCOMPLETE;
1606 bmsafemap = newblk->nb_bmsafemap;
1607 aip->ai_buf = bmsafemap->sm_buf;
1608 LIST_REMOVE(newblk, nb_deps);
1609 LIST_INSERT_HEAD(&bmsafemap->sm_allocindirhd,
1612 LIST_REMOVE(newblk, nb_hash);
1613 kfree(newblk, M_NEWBLK);
1614 aip->ai_indirdep = indirdep;
1616 * Check to see if there is an existing dependency
1617 * for this block. If there is, merge the old
1618 * dependency into the new one.
1620 if (aip->ai_oldblkno == 0)
1624 LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next)
1625 if (oldaip->ai_offset == aip->ai_offset)
1627 if (oldaip != NULL) {
1628 if (oldaip->ai_newblkno != aip->ai_oldblkno) {
1630 panic("setup_allocindir_phase2: blkno");
1632 aip->ai_oldblkno = oldaip->ai_oldblkno;
1633 freefrag = oldaip->ai_freefrag;
1634 oldaip->ai_freefrag = aip->ai_freefrag;
1635 aip->ai_freefrag = freefrag;
1636 free_allocindir(oldaip, NULL);
1638 LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
1639 ((ufs_daddr_t *)indirdep->ir_savebp->b_data)
1640 [aip->ai_offset] = aip->ai_oldblkno;
1645 * Avoid any possibility of data corruption by
1646 * ensuring that our old version is thrown away.
1648 newindirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
1649 brelse(newindirdep->ir_savebp);
1650 WORKITEM_FREE((caddr_t)newindirdep, D_INDIRDEP);
1654 newindirdep = kmalloc(sizeof(struct indirdep), M_INDIRDEP,
1656 newindirdep->ir_list.wk_type = D_INDIRDEP;
1657 newindirdep->ir_state = ATTACHED;
1658 LIST_INIT(&newindirdep->ir_deplisthd);
1659 LIST_INIT(&newindirdep->ir_donehd);
1660 if (bp->b_bio2.bio_offset == NOOFFSET) {
1661 VOP_BMAP(bp->b_vp, bp->b_bio1.bio_offset,
1662 &bp->b_bio2.bio_offset, NULL, NULL,
1665 KKASSERT(bp->b_bio2.bio_offset != NOOFFSET);
1666 newindirdep->ir_savebp = getblk(ip->i_devvp,
1667 bp->b_bio2.bio_offset,
1668 bp->b_bcount, 0, 0);
1669 BUF_KERNPROC(newindirdep->ir_savebp);
1670 bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
1675 * Block de-allocation dependencies.
1677 * When blocks are de-allocated, the on-disk pointers must be nullified before
1678 * the blocks are made available for use by other files. (The true
1679 * requirement is that old pointers must be nullified before new on-disk
1680 * pointers are set. We chose this slightly more stringent requirement to
1681 * reduce complexity.) Our implementation handles this dependency by updating
1682 * the inode (or indirect block) appropriately but delaying the actual block
1683 * de-allocation (i.e., freemap and free space count manipulation) until
1684 * after the updated versions reach stable storage. After the disk is
1685 * updated, the blocks can be safely de-allocated whenever it is convenient.
1686 * This implementation handles only the common case of reducing a file's
1687 * length to zero. Other cases are handled by the conventional synchronous
1690 * The ffs implementation with which we worked double-checks
1691 * the state of the block pointers and file size as it reduces
1692 * a file's length. Some of this code is replicated here in our
1693 * soft updates implementation. The freeblks->fb_chkcnt field is
1694 * used to transfer a part of this information to the procedure
1695 * that eventually de-allocates the blocks.
1697 * This routine should be called from the routine that shortens
1698 * a file's length, before the inode's size or block pointers
1699 * are modified. It will save the block pointer information for
1700 * later release and zero the inode so that the calling routine
1703 struct softdep_setup_freeblocks_info {
1708 static int softdep_setup_freeblocks_bp(struct buf *bp, void *data);
1712 * ip: The inode whose length is to be reduced
1713 * length: The new length for the file
1716 softdep_setup_freeblocks(struct inode *ip, off_t length)
1718 struct softdep_setup_freeblocks_info info;
1719 struct freeblks *freeblks;
1720 struct inodedep *inodedep;
1721 struct allocdirect *adp;
1725 int i, error, delay;
1730 panic("softde_setup_freeblocks: non-zero length");
1731 freeblks = kmalloc(sizeof(struct freeblks), M_FREEBLKS,
1732 M_SOFTDEP_FLAGS | M_ZERO);
1733 freeblks->fb_list.wk_type = D_FREEBLKS;
1734 freeblks->fb_state = ATTACHED;
1735 freeblks->fb_uid = ip->i_uid;
1736 freeblks->fb_previousinum = ip->i_number;
1737 freeblks->fb_devvp = ip->i_devvp;
1738 freeblks->fb_fs = fs;
1739 freeblks->fb_oldsize = ip->i_size;
1740 freeblks->fb_newsize = length;
1741 freeblks->fb_chkcnt = ip->i_blocks;
1742 for (i = 0; i < NDADDR; i++) {
1743 freeblks->fb_dblks[i] = ip->i_db[i];
1746 for (i = 0; i < NIADDR; i++) {
1747 freeblks->fb_iblks[i] = ip->i_ib[i];
1753 * Push the zero'ed inode to to its disk buffer so that we are free
1754 * to delete its dependencies below. Once the dependencies are gone
1755 * the buffer can be safely released.
1757 if ((error = bread(ip->i_devvp,
1758 fsbtodoff(fs, ino_to_fsba(fs, ip->i_number)),
1759 (int)fs->fs_bsize, &bp)) != 0)
1760 softdep_error("softdep_setup_freeblocks", error);
1761 *((struct ufs1_dinode *)bp->b_data + ino_to_fsbo(fs, ip->i_number)) =
1764 * Find and eliminate any inode dependencies.
1767 (void) inodedep_lookup(fs, ip->i_number, DEPALLOC, &inodedep);
1768 if ((inodedep->id_state & IOSTARTED) != 0) {
1770 panic("softdep_setup_freeblocks: inode busy");
1773 * Add the freeblks structure to the list of operations that
1774 * must await the zero'ed inode being written to disk. If we
1775 * still have a bitmap dependency (delay == 0), then the inode
1776 * has never been written to disk, so we can process the
1777 * freeblks below once we have deleted the dependencies.
1779 delay = (inodedep->id_state & DEPCOMPLETE);
1781 WORKLIST_INSERT(&inodedep->id_bufwait, &freeblks->fb_list);
1783 * Because the file length has been truncated to zero, any
1784 * pending block allocation dependency structures associated
1785 * with this inode are obsolete and can simply be de-allocated.
1786 * We must first merge the two dependency lists to get rid of
1787 * any duplicate freefrag structures, then purge the merged list.
1789 merge_inode_lists(inodedep);
1790 while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
1791 free_allocdirect(&inodedep->id_inoupdt, adp, 1);
1795 * We must wait for any I/O in progress to finish so that
1796 * all potential buffers on the dirty list will be visible.
1797 * Once they are all there, walk the list and get rid of
1802 drain_output(vp, 1);
1806 lwkt_gettoken(&vp->v_token);
1808 count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
1809 softdep_setup_freeblocks_bp, &info);
1810 } while (count != 0);
1811 lwkt_reltoken(&vp->v_token);
1813 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) != 0)
1814 (void)free_inodedep(inodedep);
1817 freeblks->fb_state |= DEPCOMPLETE;
1819 * If the inode with zeroed block pointers is now on disk
1820 * we can start freeing blocks. Add freeblks to the worklist
1821 * instead of calling handle_workitem_freeblocks directly as
1822 * it is more likely that additional IO is needed to complete
1823 * the request here than in the !delay case.
1825 if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
1826 add_to_worklist(&freeblks->fb_list);
1831 * If the inode has never been written to disk (delay == 0),
1832 * then we can process the freeblks now that we have deleted
1836 handle_workitem_freeblocks(freeblks);
1840 softdep_setup_freeblocks_bp(struct buf *bp, void *data)
1842 struct softdep_setup_freeblocks_info *info = data;
1843 struct inodedep *inodedep;
1845 if (getdirtybuf(&bp, MNT_WAIT) == 0) {
1846 kprintf("softdep_setup_freeblocks_bp(1): caught bp %p going away\n", bp);
1849 if (bp->b_vp != ITOV(info->ip) || (bp->b_flags & B_DELWRI) == 0) {
1850 kprintf("softdep_setup_freeblocks_bp(2): caught bp %p going away\n", bp);
1854 (void) inodedep_lookup(info->fs, info->ip->i_number, 0, &inodedep);
1855 deallocate_dependencies(bp, inodedep);
1856 bp->b_flags |= B_INVAL | B_NOCACHE;
1864 * Reclaim any dependency structures from a buffer that is about to
1865 * be reallocated to a new vnode. The buffer must be locked, thus,
1866 * no I/O completion operations can occur while we are manipulating
1867 * its associated dependencies. The mutex is held so that other I/O's
1868 * associated with related dependencies do not occur.
1871 deallocate_dependencies(struct buf *bp, struct inodedep *inodedep)
1873 struct worklist *wk;
1874 struct indirdep *indirdep;
1875 struct allocindir *aip;
1876 struct pagedep *pagedep;
1877 struct dirrem *dirrem;
1881 while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
1882 switch (wk->wk_type) {
1885 indirdep = WK_INDIRDEP(wk);
1887 * None of the indirect pointers will ever be visible,
1888 * so they can simply be tossed. GOINGAWAY ensures
1889 * that allocated pointers will be saved in the buffer
1890 * cache until they are freed. Note that they will
1891 * only be able to be found by their physical address
1892 * since the inode mapping the logical address will
1893 * be gone. The save buffer used for the safe copy
1894 * was allocated in setup_allocindir_phase2 using
1895 * the physical address so it could be used for this
1896 * purpose. Hence we swap the safe copy with the real
1897 * copy, allowing the safe copy to be freed and holding
1898 * on to the real copy for later use in indir_trunc.
1900 * NOTE: ir_savebp is relative to the block device
1901 * so b_bio1 contains the device block number.
1903 if (indirdep->ir_state & GOINGAWAY) {
1905 panic("deallocate_dependencies: already gone");
1907 indirdep->ir_state |= GOINGAWAY;
1908 while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
1909 free_allocindir(aip, inodedep);
1910 if (bp->b_bio1.bio_offset >= 0 ||
1911 bp->b_bio2.bio_offset != indirdep->ir_savebp->b_bio1.bio_offset) {
1913 panic("deallocate_dependencies: not indir");
1915 bcopy(bp->b_data, indirdep->ir_savebp->b_data,
1917 WORKLIST_REMOVE(wk);
1918 WORKLIST_INSERT_BP(indirdep->ir_savebp, wk);
1922 pagedep = WK_PAGEDEP(wk);
1924 * None of the directory additions will ever be
1925 * visible, so they can simply be tossed.
1927 for (i = 0; i < DAHASHSZ; i++)
1929 LIST_FIRST(&pagedep->pd_diraddhd[i])))
1931 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
1934 * Copy any directory remove dependencies to the list
1935 * to be processed after the zero'ed inode is written.
1936 * If the inode has already been written, then they
1937 * can be dumped directly onto the work list.
1939 LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
1940 LIST_REMOVE(dirrem, dm_next);
1941 dirrem->dm_dirinum = pagedep->pd_ino;
1942 if (inodedep == NULL ||
1943 (inodedep->id_state & ALLCOMPLETE) ==
1945 add_to_worklist(&dirrem->dm_list);
1947 WORKLIST_INSERT(&inodedep->id_bufwait,
1950 WORKLIST_REMOVE(&pagedep->pd_list);
1951 LIST_REMOVE(pagedep, pd_hash);
1952 WORKITEM_FREE(pagedep, D_PAGEDEP);
1956 free_allocindir(WK_ALLOCINDIR(wk), inodedep);
1962 panic("deallocate_dependencies: Unexpected type %s",
1963 TYPENAME(wk->wk_type));
1968 panic("deallocate_dependencies: Unknown type %s",
1969 TYPENAME(wk->wk_type));
1976 * Free an allocdirect. Generate a new freefrag work request if appropriate.
1977 * This routine must be called with splbio interrupts blocked.
1980 free_allocdirect(struct allocdirectlst *adphead,
1981 struct allocdirect *adp, int delay)
1983 KKASSERT(lock_held(&lk) > 0);
1985 if ((adp->ad_state & DEPCOMPLETE) == 0)
1986 LIST_REMOVE(adp, ad_deps);
1987 TAILQ_REMOVE(adphead, adp, ad_next);
1988 if ((adp->ad_state & COMPLETE) == 0)
1989 WORKLIST_REMOVE(&adp->ad_list);
1990 if (adp->ad_freefrag != NULL) {
1992 WORKLIST_INSERT(&adp->ad_inodedep->id_bufwait,
1993 &adp->ad_freefrag->ff_list);
1995 add_to_worklist(&adp->ad_freefrag->ff_list);
1997 WORKITEM_FREE(adp, D_ALLOCDIRECT);
2001 * Prepare an inode to be freed. The actual free operation is not
2002 * done until the zero'ed inode has been written to disk.
2005 softdep_freefile(struct vnode *pvp, ino_t ino, int mode)
2007 struct inode *ip = VTOI(pvp);
2008 struct inodedep *inodedep;
2009 struct freefile *freefile;
2012 * This sets up the inode de-allocation dependency.
2014 freefile = kmalloc(sizeof(struct freefile), M_FREEFILE,
2016 freefile->fx_list.wk_type = D_FREEFILE;
2017 freefile->fx_list.wk_state = 0;
2018 freefile->fx_mode = mode;
2019 freefile->fx_oldinum = ino;
2020 freefile->fx_devvp = ip->i_devvp;
2021 freefile->fx_fs = ip->i_fs;
2024 * If the inodedep does not exist, then the zero'ed inode has
2025 * been written to disk. If the allocated inode has never been
2026 * written to disk, then the on-disk inode is zero'ed. In either
2027 * case we can free the file immediately.
2030 if (inodedep_lookup(ip->i_fs, ino, 0, &inodedep) == 0 ||
2031 check_inode_unwritten(inodedep)) {
2033 handle_workitem_freefile(freefile);
2036 WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
2041 * Check to see if an inode has never been written to disk. If
2042 * so free the inodedep and return success, otherwise return failure.
2043 * This routine must be called with splbio interrupts blocked.
2045 * If we still have a bitmap dependency, then the inode has never
2046 * been written to disk. Drop the dependency as it is no longer
2047 * necessary since the inode is being deallocated. We set the
2048 * ALLCOMPLETE flags since the bitmap now properly shows that the
2049 * inode is not allocated. Even if the inode is actively being
2050 * written, it has been rolled back to its zero'ed state, so we
2051 * are ensured that a zero inode is what is on the disk. For short
2052 * lived files, this change will usually result in removing all the
2053 * dependencies from the inode so that it can be freed immediately.
2056 check_inode_unwritten(struct inodedep *inodedep)
2059 if ((inodedep->id_state & DEPCOMPLETE) != 0 ||
2060 LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2061 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2062 LIST_FIRST(&inodedep->id_inowait) != NULL ||
2063 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2064 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2065 inodedep->id_nlinkdelta != 0)
2069 * Another process might be in initiate_write_inodeblock
2070 * trying to allocate memory without holding "Softdep Lock".
2072 if ((inodedep->id_state & IOSTARTED) != 0 &&
2073 inodedep->id_savedino == NULL)
2076 inodedep->id_state |= ALLCOMPLETE;
2077 LIST_REMOVE(inodedep, id_deps);
2078 inodedep->id_buf = NULL;
2079 if (inodedep->id_state & ONWORKLIST)
2080 WORKLIST_REMOVE(&inodedep->id_list);
2081 if (inodedep->id_savedino != NULL) {
2082 kfree(inodedep->id_savedino, M_INODEDEP);
2083 inodedep->id_savedino = NULL;
2085 if (free_inodedep(inodedep) == 0) {
2087 panic("check_inode_unwritten: busy inode");
2093 * Try to free an inodedep structure. Return 1 if it could be freed.
2096 free_inodedep(struct inodedep *inodedep)
2099 if ((inodedep->id_state & ONWORKLIST) != 0 ||
2100 (inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
2101 LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2102 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2103 LIST_FIRST(&inodedep->id_inowait) != NULL ||
2104 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2105 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2106 inodedep->id_nlinkdelta != 0 || inodedep->id_savedino != NULL)
2108 LIST_REMOVE(inodedep, id_hash);
2109 WORKITEM_FREE(inodedep, D_INODEDEP);
2115 * This workitem routine performs the block de-allocation.
2116 * The workitem is added to the pending list after the updated
2117 * inode block has been written to disk. As mentioned above,
2118 * checks regarding the number of blocks de-allocated (compared
2119 * to the number of blocks allocated for the file) are also
2120 * performed in this function.
2123 handle_workitem_freeblocks(struct freeblks *freeblks)
2128 int i, level, bsize;
2129 long nblocks, blocksreleased = 0;
2130 int error, allerror = 0;
2131 ufs_lbn_t baselbns[NIADDR], tmpval;
2133 tip.i_number = freeblks->fb_previousinum;
2134 tip.i_devvp = freeblks->fb_devvp;
2135 tip.i_dev = freeblks->fb_devvp->v_rdev;
2136 tip.i_fs = freeblks->fb_fs;
2137 tip.i_size = freeblks->fb_oldsize;
2138 tip.i_uid = freeblks->fb_uid;
2139 fs = freeblks->fb_fs;
2141 baselbns[0] = NDADDR;
2142 for (i = 1; i < NIADDR; i++) {
2143 tmpval *= NINDIR(fs);
2144 baselbns[i] = baselbns[i - 1] + tmpval;
2146 nblocks = btodb(fs->fs_bsize);
2149 * Indirect blocks first.
2151 for (level = (NIADDR - 1); level >= 0; level--) {
2152 if ((bn = freeblks->fb_iblks[level]) == 0)
2154 if ((error = indir_trunc(&tip, fsbtodoff(fs, bn), level,
2155 baselbns[level], &blocksreleased)) == 0)
2157 ffs_blkfree(&tip, bn, fs->fs_bsize);
2158 blocksreleased += nblocks;
2161 * All direct blocks or frags.
2163 for (i = (NDADDR - 1); i >= 0; i--) {
2164 if ((bn = freeblks->fb_dblks[i]) == 0)
2166 bsize = blksize(fs, &tip, i);
2167 ffs_blkfree(&tip, bn, bsize);
2168 blocksreleased += btodb(bsize);
2172 if (freeblks->fb_chkcnt != blocksreleased)
2173 kprintf("handle_workitem_freeblocks: block count\n");
2175 softdep_error("handle_workitem_freeblks", allerror);
2176 #endif /* DIAGNOSTIC */
2177 WORKITEM_FREE(freeblks, D_FREEBLKS);
2181 * Release blocks associated with the inode ip and stored in the indirect
2182 * block at doffset. If level is greater than SINGLE, the block is an
2183 * indirect block and recursive calls to indirtrunc must be used to
2184 * cleanse other indirect blocks.
2187 indir_trunc(struct inode *ip, off_t doffset, int level, ufs_lbn_t lbn,
2194 struct worklist *wk;
2195 struct indirdep *indirdep;
2196 int i, lbnadd, nblocks;
2197 int error, allerror = 0;
2201 for (i = level; i > 0; i--)
2202 lbnadd *= NINDIR(fs);
2204 * Get buffer of block pointers to be freed. This routine is not
2205 * called until the zero'ed inode has been written, so it is safe
2206 * to free blocks as they are encountered. Because the inode has
2207 * been zero'ed, calls to bmap on these blocks will fail. So, we
2208 * have to use the on-disk address and the block device for the
2209 * filesystem to look them up. If the file was deleted before its
2210 * indirect blocks were all written to disk, the routine that set
2211 * us up (deallocate_dependencies) will have arranged to leave
2212 * a complete copy of the indirect block in memory for our use.
2213 * Otherwise we have to read the blocks in from the disk.
2216 if ((bp = findblk(ip->i_devvp, doffset, FINDBLK_TEST)) != NULL &&
2217 (wk = LIST_FIRST(&bp->b_dep)) != NULL) {
2219 * bp must be ir_savebp, which is held locked for our use.
2221 if (wk->wk_type != D_INDIRDEP ||
2222 (indirdep = WK_INDIRDEP(wk))->ir_savebp != bp ||
2223 (indirdep->ir_state & GOINGAWAY) == 0) {
2225 panic("indir_trunc: lost indirdep");
2227 WORKLIST_REMOVE(wk);
2228 WORKITEM_FREE(indirdep, D_INDIRDEP);
2229 if (LIST_FIRST(&bp->b_dep) != NULL) {
2231 panic("indir_trunc: dangling dep");
2236 error = bread(ip->i_devvp, doffset, (int)fs->fs_bsize, &bp);
2241 * Recursively free indirect blocks.
2243 bap = (ufs_daddr_t *)bp->b_data;
2244 nblocks = btodb(fs->fs_bsize);
2245 for (i = NINDIR(fs) - 1; i >= 0; i--) {
2246 if ((nb = bap[i]) == 0)
2249 if ((error = indir_trunc(ip, fsbtodoff(fs, nb),
2250 level - 1, lbn + (i * lbnadd), countp)) != 0)
2253 ffs_blkfree(ip, nb, fs->fs_bsize);
2256 bp->b_flags |= B_INVAL | B_NOCACHE;
2262 * Free an allocindir.
2263 * This routine must be called with splbio interrupts blocked.
2266 free_allocindir(struct allocindir *aip, struct inodedep *inodedep)
2268 struct freefrag *freefrag;
2270 KKASSERT(lock_held(&lk) > 0);
2272 if ((aip->ai_state & DEPCOMPLETE) == 0)
2273 LIST_REMOVE(aip, ai_deps);
2274 if (aip->ai_state & ONWORKLIST)
2275 WORKLIST_REMOVE(&aip->ai_list);
2276 LIST_REMOVE(aip, ai_next);
2277 if ((freefrag = aip->ai_freefrag) != NULL) {
2278 if (inodedep == NULL)
2279 add_to_worklist(&freefrag->ff_list);
2281 WORKLIST_INSERT(&inodedep->id_bufwait,
2282 &freefrag->ff_list);
2284 WORKITEM_FREE(aip, D_ALLOCINDIR);
2288 * Directory entry addition dependencies.
2290 * When adding a new directory entry, the inode (with its incremented link
2291 * count) must be written to disk before the directory entry's pointer to it.
2292 * Also, if the inode is newly allocated, the corresponding freemap must be
2293 * updated (on disk) before the directory entry's pointer. These requirements
2294 * are met via undo/redo on the directory entry's pointer, which consists
2295 * simply of the inode number.
2297 * As directory entries are added and deleted, the free space within a
2298 * directory block can become fragmented. The ufs filesystem will compact
2299 * a fragmented directory block to make space for a new entry. When this
2300 * occurs, the offsets of previously added entries change. Any "diradd"
2301 * dependency structures corresponding to these entries must be updated with
2306 * This routine is called after the in-memory inode's link
2307 * count has been incremented, but before the directory entry's
2308 * pointer to the inode has been set.
2311 * bp: buffer containing directory block
2312 * dp: inode for directory
2313 * diroffset: offset of new entry in directory
2314 * newinum: inode referenced by new directory entry
2315 * newdirbp: non-NULL => contents of new mkdir
2318 softdep_setup_directory_add(struct buf *bp, struct inode *dp, off_t diroffset,
2319 ino_t newinum, struct buf *newdirbp)
2321 int offset; /* offset of new entry within directory block */
2322 ufs_lbn_t lbn; /* block in directory containing new entry */
2325 struct pagedep *pagedep;
2326 struct inodedep *inodedep;
2327 struct mkdir *mkdir1, *mkdir2;
2330 * Whiteouts have no dependencies.
2332 if (newinum == WINO) {
2333 if (newdirbp != NULL)
2339 lbn = lblkno(fs, diroffset);
2340 offset = blkoff(fs, diroffset);
2341 dap = kmalloc(sizeof(struct diradd), M_DIRADD,
2342 M_SOFTDEP_FLAGS | M_ZERO);
2343 dap->da_list.wk_type = D_DIRADD;
2344 dap->da_offset = offset;
2345 dap->da_newinum = newinum;
2346 dap->da_state = ATTACHED;
2347 if (newdirbp == NULL) {
2348 dap->da_state |= DEPCOMPLETE;
2351 dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
2352 mkdir1 = kmalloc(sizeof(struct mkdir), M_MKDIR,
2354 mkdir1->md_list.wk_type = D_MKDIR;
2355 mkdir1->md_state = MKDIR_BODY;
2356 mkdir1->md_diradd = dap;
2357 mkdir2 = kmalloc(sizeof(struct mkdir), M_MKDIR,
2359 mkdir2->md_list.wk_type = D_MKDIR;
2360 mkdir2->md_state = MKDIR_PARENT;
2361 mkdir2->md_diradd = dap;
2363 * Dependency on "." and ".." being written to disk.
2365 mkdir1->md_buf = newdirbp;
2367 LIST_INSERT_HEAD(&mkdirlisthd, mkdir1, md_mkdirs);
2368 WORKLIST_INSERT_BP(newdirbp, &mkdir1->md_list);
2372 * Dependency on link count increase for parent directory
2375 if (inodedep_lookup(dp->i_fs, dp->i_number, 0, &inodedep) == 0
2376 || (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2377 dap->da_state &= ~MKDIR_PARENT;
2378 WORKITEM_FREE(mkdir2, D_MKDIR);
2380 LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
2381 WORKLIST_INSERT(&inodedep->id_bufwait,&mkdir2->md_list);
2385 * Link into parent directory pagedep to await its being written.
2387 if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2388 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
2389 dap->da_pagedep = pagedep;
2390 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
2393 * Link into its inodedep. Put it on the id_bufwait list if the inode
2394 * is not yet written. If it is written, do the post-inode write
2395 * processing to put it on the id_pendinghd list.
2397 (void) inodedep_lookup(fs, newinum, DEPALLOC, &inodedep);
2398 if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
2399 diradd_inode_written(dap, inodedep);
2401 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2406 * This procedure is called to change the offset of a directory
2407 * entry when compacting a directory block which must be owned
2408 * exclusively by the caller. Note that the actual entry movement
2409 * must be done in this procedure to ensure that no I/O completions
2410 * occur while the move is in progress.
2413 * dp: inode for directory
2414 * base: address of dp->i_offset
2415 * oldloc: address of old directory location
2416 * newloc: address of new directory location
2417 * entrysize: size of directory entry
2420 softdep_change_directoryentry_offset(struct inode *dp, caddr_t base,
2421 caddr_t oldloc, caddr_t newloc,
2424 int offset, oldoffset, newoffset;
2425 struct pagedep *pagedep;
2430 lbn = lblkno(dp->i_fs, dp->i_offset);
2431 offset = blkoff(dp->i_fs, dp->i_offset);
2432 if (pagedep_lookup(dp, lbn, 0, &pagedep) == 0)
2434 oldoffset = offset + (oldloc - base);
2435 newoffset = offset + (newloc - base);
2437 LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(oldoffset)], da_pdlist) {
2438 if (dap->da_offset != oldoffset)
2440 dap->da_offset = newoffset;
2441 if (DIRADDHASH(newoffset) == DIRADDHASH(oldoffset))
2443 LIST_REMOVE(dap, da_pdlist);
2444 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(newoffset)],
2450 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist) {
2451 if (dap->da_offset == oldoffset) {
2452 dap->da_offset = newoffset;
2458 bcopy(oldloc, newloc, entrysize);
2463 * Free a diradd dependency structure. This routine must be called
2464 * with splbio interrupts blocked.
2467 free_diradd(struct diradd *dap)
2469 struct dirrem *dirrem;
2470 struct pagedep *pagedep;
2471 struct inodedep *inodedep;
2472 struct mkdir *mkdir, *nextmd;
2474 KKASSERT(lock_held(&lk) > 0);
2476 WORKLIST_REMOVE(&dap->da_list);
2477 LIST_REMOVE(dap, da_pdlist);
2478 if ((dap->da_state & DIRCHG) == 0) {
2479 pagedep = dap->da_pagedep;
2481 dirrem = dap->da_previous;
2482 pagedep = dirrem->dm_pagedep;
2483 dirrem->dm_dirinum = pagedep->pd_ino;
2484 add_to_worklist(&dirrem->dm_list);
2486 if (inodedep_lookup(VFSTOUFS(pagedep->pd_mnt)->um_fs, dap->da_newinum,
2488 (void) free_inodedep(inodedep);
2489 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
2490 for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
2491 nextmd = LIST_NEXT(mkdir, md_mkdirs);
2492 if (mkdir->md_diradd != dap)
2494 dap->da_state &= ~mkdir->md_state;
2495 WORKLIST_REMOVE(&mkdir->md_list);
2496 LIST_REMOVE(mkdir, md_mkdirs);
2497 WORKITEM_FREE(mkdir, D_MKDIR);
2499 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
2501 panic("free_diradd: unfound ref");
2504 WORKITEM_FREE(dap, D_DIRADD);
2508 * Directory entry removal dependencies.
2510 * When removing a directory entry, the entry's inode pointer must be
2511 * zero'ed on disk before the corresponding inode's link count is decremented
2512 * (possibly freeing the inode for re-use). This dependency is handled by
2513 * updating the directory entry but delaying the inode count reduction until
2514 * after the directory block has been written to disk. After this point, the
2515 * inode count can be decremented whenever it is convenient.
2519 * This routine should be called immediately after removing
2520 * a directory entry. The inode's link count should not be
2521 * decremented by the calling procedure -- the soft updates
2522 * code will do this task when it is safe.
2525 * bp: buffer containing directory block
2526 * dp: inode for the directory being modified
2527 * ip: inode for directory entry being removed
2528 * isrmdir: indicates if doing RMDIR
2531 softdep_setup_remove(struct buf *bp, struct inode *dp, struct inode *ip,
2534 struct dirrem *dirrem, *prevdirrem;
2537 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.
2539 dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
2542 * If the COMPLETE flag is clear, then there were no active
2543 * entries and we want to roll back to a zeroed entry until
2544 * the new inode is committed to disk. If the COMPLETE flag is
2545 * set then we have deleted an entry that never made it to
2546 * disk. If the entry we deleted resulted from a name change,
2547 * then the old name still resides on disk. We cannot delete
2548 * its inode (returned to us in prevdirrem) until the zeroed
2549 * directory entry gets to disk. The new inode has never been
2550 * referenced on the disk, so can be deleted immediately.
2552 if ((dirrem->dm_state & COMPLETE) == 0) {
2553 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
2557 if (prevdirrem != NULL)
2558 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
2559 prevdirrem, dm_next);
2560 dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
2562 handle_workitem_remove(dirrem);
2567 * Allocate a new dirrem if appropriate and return it along with
2568 * its associated pagedep. Called without a lock, returns with lock.
2570 static long num_dirrem; /* number of dirrem allocated */
2574 * bp: buffer containing directory block
2575 * dp: inode for the directory being modified
2576 * ip: inode for directory entry being removed
2577 * isrmdir: indicates if doing RMDIR
2578 * prevdirremp: previously referenced inode, if any
2580 static struct dirrem *
2581 newdirrem(struct buf *bp, struct inode *dp, struct inode *ip,
2582 int isrmdir, struct dirrem **prevdirremp)
2587 struct dirrem *dirrem;
2588 struct pagedep *pagedep;
2591 * Whiteouts have no deletion dependencies.
2594 panic("newdirrem: whiteout");
2596 * If we are over our limit, try to improve the situation.
2597 * Limiting the number of dirrem structures will also limit
2598 * the number of freefile and freeblks structures.
2600 if (num_dirrem > max_softdeps / 2 && speedup_syncer() == 0)
2601 (void) request_cleanup(FLUSH_REMOVE, 0);
2603 dirrem = kmalloc(sizeof(struct dirrem), M_DIRREM,
2604 M_SOFTDEP_FLAGS | M_ZERO);
2605 dirrem->dm_list.wk_type = D_DIRREM;
2606 dirrem->dm_state = isrmdir ? RMDIR : 0;
2607 dirrem->dm_mnt = ITOV(ip)->v_mount;
2608 dirrem->dm_oldinum = ip->i_number;
2609 *prevdirremp = NULL;
2612 lbn = lblkno(dp->i_fs, dp->i_offset);
2613 offset = blkoff(dp->i_fs, dp->i_offset);
2614 if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2615 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
2616 dirrem->dm_pagedep = pagedep;
2618 * Check for a diradd dependency for the same directory entry.
2619 * If present, then both dependencies become obsolete and can
2620 * be de-allocated. Check for an entry on both the pd_dirraddhd
2621 * list and the pd_pendinghd list.
2624 LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
2625 if (dap->da_offset == offset)
2629 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
2630 if (dap->da_offset == offset)
2636 * Must be ATTACHED at this point.
2638 if ((dap->da_state & ATTACHED) == 0) {
2640 panic("newdirrem: not ATTACHED");
2642 if (dap->da_newinum != ip->i_number) {
2644 panic("newdirrem: inum %"PRId64" should be %"PRId64,
2645 ip->i_number, dap->da_newinum);
2648 * If we are deleting a changed name that never made it to disk,
2649 * then return the dirrem describing the previous inode (which
2650 * represents the inode currently referenced from this entry on disk).
2652 if ((dap->da_state & DIRCHG) != 0) {
2653 *prevdirremp = dap->da_previous;
2654 dap->da_state &= ~DIRCHG;
2655 dap->da_pagedep = pagedep;
2658 * We are deleting an entry that never made it to disk.
2659 * Mark it COMPLETE so we can delete its inode immediately.
2661 dirrem->dm_state |= COMPLETE;
2667 * Directory entry change dependencies.
2669 * Changing an existing directory entry requires that an add operation
2670 * be completed first followed by a deletion. The semantics for the addition
2671 * are identical to the description of adding a new entry above except
2672 * that the rollback is to the old inode number rather than zero. Once
2673 * the addition dependency is completed, the removal is done as described
2674 * in the removal routine above.
2678 * This routine should be called immediately after changing
2679 * a directory entry. The inode's link count should not be
2680 * decremented by the calling procedure -- the soft updates
2681 * code will perform this task when it is safe.
2684 * bp: buffer containing directory block
2685 * dp: inode for the directory being modified
2686 * ip: inode for directory entry being removed
2687 * newinum: new inode number for changed entry
2688 * isrmdir: indicates if doing RMDIR
2691 softdep_setup_directory_change(struct buf *bp, struct inode *dp,
2692 struct inode *ip, ino_t newinum,
2696 struct diradd *dap = NULL;
2697 struct dirrem *dirrem, *prevdirrem;
2698 struct pagedep *pagedep;
2699 struct inodedep *inodedep;
2701 offset = blkoff(dp->i_fs, dp->i_offset);
2704 * Whiteouts do not need diradd dependencies.
2706 if (newinum != WINO) {
2707 dap = kmalloc(sizeof(struct diradd), M_DIRADD,
2708 M_SOFTDEP_FLAGS | M_ZERO);
2709 dap->da_list.wk_type = D_DIRADD;
2710 dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
2711 dap->da_offset = offset;
2712 dap->da_newinum = newinum;
2716 * Allocate a new dirrem and ACQUIRE_LOCK.
2718 dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
2719 pagedep = dirrem->dm_pagedep;
2721 * The possible values for isrmdir:
2722 * 0 - non-directory file rename
2723 * 1 - directory rename within same directory
2724 * inum - directory rename to new directory of given inode number
2725 * When renaming to a new directory, we are both deleting and
2726 * creating a new directory entry, so the link count on the new
2727 * directory should not change. Thus we do not need the followup
2728 * dirrem which is usually done in handle_workitem_remove. We set
2729 * the DIRCHG flag to tell handle_workitem_remove to skip the
2733 dirrem->dm_state |= DIRCHG;
2736 * Whiteouts have no additional dependencies,
2737 * so just put the dirrem on the correct list.
2739 if (newinum == WINO) {
2740 if ((dirrem->dm_state & COMPLETE) == 0) {
2741 LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
2744 dirrem->dm_dirinum = pagedep->pd_ino;
2745 add_to_worklist(&dirrem->dm_list);
2752 * If the COMPLETE flag is clear, then there were no active
2753 * entries and we want to roll back to the previous inode until
2754 * the new inode is committed to disk. If the COMPLETE flag is
2755 * set, then we have deleted an entry that never made it to disk.
2756 * If the entry we deleted resulted from a name change, then the old
2757 * inode reference still resides on disk. Any rollback that we do
2758 * needs to be to that old inode (returned to us in prevdirrem). If
2759 * the entry we deleted resulted from a create, then there is
2760 * no entry on the disk, so we want to roll back to zero rather
2761 * than the uncommitted inode. In either of the COMPLETE cases we
2762 * want to immediately free the unwritten and unreferenced inode.
2764 if ((dirrem->dm_state & COMPLETE) == 0) {
2765 dap->da_previous = dirrem;
2767 if (prevdirrem != NULL) {
2768 dap->da_previous = prevdirrem;
2770 dap->da_state &= ~DIRCHG;
2771 dap->da_pagedep = pagedep;
2773 dirrem->dm_dirinum = pagedep->pd_ino;
2774 add_to_worklist(&dirrem->dm_list);
2777 * Link into its inodedep. Put it on the id_bufwait list if the inode
2778 * is not yet written. If it is written, do the post-inode write
2779 * processing to put it on the id_pendinghd list.
2781 if (inodedep_lookup(dp->i_fs, newinum, DEPALLOC, &inodedep) == 0 ||
2782 (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2783 dap->da_state |= COMPLETE;
2784 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
2785 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
2787 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
2789 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2795 * Called whenever the link count on an inode is changed.
2796 * It creates an inode dependency so that the new reference(s)
2797 * to the inode cannot be committed to disk until the updated
2798 * inode has been written.
2801 * ip: the inode with the increased link count
2804 softdep_change_linkcnt(struct inode *ip)
2806 struct inodedep *inodedep;
2809 (void) inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC, &inodedep);
2810 if (ip->i_nlink < ip->i_effnlink) {
2812 panic("softdep_change_linkcnt: bad delta");
2814 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2819 * This workitem decrements the inode's link count.
2820 * If the link count reaches zero, the file is removed.
2823 handle_workitem_remove(struct dirrem *dirrem)
2825 struct inodedep *inodedep;
2831 error = VFS_VGET(dirrem->dm_mnt, NULL, dirrem->dm_oldinum, &vp);
2833 softdep_error("handle_workitem_remove: vget", error);
2838 if ((inodedep_lookup(ip->i_fs, dirrem->dm_oldinum, 0, &inodedep)) == 0){
2840 panic("handle_workitem_remove: lost inodedep");
2843 * Normal file deletion.
2845 if ((dirrem->dm_state & RMDIR) == 0) {
2847 ip->i_flag |= IN_CHANGE;
2848 if (ip->i_nlink < ip->i_effnlink) {
2850 panic("handle_workitem_remove: bad file delta");
2852 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2856 WORKITEM_FREE(dirrem, D_DIRREM);
2860 * Directory deletion. Decrement reference count for both the
2861 * just deleted parent directory entry and the reference for ".".
2862 * Next truncate the directory to length zero. When the
2863 * truncation completes, arrange to have the reference count on
2864 * the parent decremented to account for the loss of "..".
2867 ip->i_flag |= IN_CHANGE;
2868 if (ip->i_nlink < ip->i_effnlink) {
2870 panic("handle_workitem_remove: bad dir delta");
2872 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2874 if ((error = ffs_truncate(vp, (off_t)0, 0, proc0.p_ucred)) != 0)
2875 softdep_error("handle_workitem_remove: truncate", error);
2877 * Rename a directory to a new parent. Since, we are both deleting
2878 * and creating a new directory entry, the link count on the new
2879 * directory should not change. Thus we skip the followup dirrem.
2881 if (dirrem->dm_state & DIRCHG) {
2884 WORKITEM_FREE(dirrem, D_DIRREM);
2888 * If the inodedep does not exist, then the zero'ed inode has
2889 * been written to disk. If the allocated inode has never been
2890 * written to disk, then the on-disk inode is zero'ed. In either
2891 * case we can remove the file immediately.
2894 dirrem->dm_state = 0;
2895 oldinum = dirrem->dm_oldinum;
2896 dirrem->dm_oldinum = dirrem->dm_dirinum;
2897 if (inodedep_lookup(ip->i_fs, oldinum, 0, &inodedep) == 0 ||
2898 check_inode_unwritten(inodedep)) {
2901 handle_workitem_remove(dirrem);
2904 WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
2906 ip->i_flag |= IN_CHANGE;
2912 * Inode de-allocation dependencies.
2914 * When an inode's link count is reduced to zero, it can be de-allocated. We
2915 * found it convenient to postpone de-allocation until after the inode is
2916 * written to disk with its new link count (zero). At this point, all of the
2917 * on-disk inode's block pointers are nullified and, with careful dependency
2918 * list ordering, all dependencies related to the inode will be satisfied and
2919 * the corresponding dependency structures de-allocated. So, if/when the
2920 * inode is reused, there will be no mixing of old dependencies with new
2921 * ones. This artificial dependency is set up by the block de-allocation
2922 * procedure above (softdep_setup_freeblocks) and completed by the
2923 * following procedure.
2926 handle_workitem_freefile(struct freefile *freefile)
2930 struct inodedep *idp;
2935 error = inodedep_lookup(freefile->fx_fs, freefile->fx_oldinum, 0, &idp);
2938 panic("handle_workitem_freefile: inodedep survived");
2940 tip.i_devvp = freefile->fx_devvp;
2941 tip.i_dev = freefile->fx_devvp->v_rdev;
2942 tip.i_fs = freefile->fx_fs;
2944 if ((error = ffs_freefile(&vp, freefile->fx_oldinum, freefile->fx_mode)) != 0)
2945 softdep_error("handle_workitem_freefile", error);
2946 WORKITEM_FREE(freefile, D_FREEFILE);
2950 * Helper function which unlinks marker element from work list and returns
2951 * the next element on the list.
2953 static __inline struct worklist *
2954 markernext(struct worklist *marker)
2956 struct worklist *next;
2958 next = LIST_NEXT(marker, wk_list);
2959 LIST_REMOVE(marker, wk_list);
2964 * checkread, checkwrite
2966 * bioops callback - hold io_token
2969 softdep_checkread(struct buf *bp)
2971 /* nothing to do, mp lock not needed */
2976 * bioops callback - hold io_token
2979 softdep_checkwrite(struct buf *bp)
2981 /* nothing to do, mp lock not needed */
2988 * The dependency structures constructed above are most actively used when file
2989 * system blocks are written to disk. No constraints are placed on when a
2990 * block can be written, but unsatisfied update dependencies are made safe by
2991 * modifying (or replacing) the source memory for the duration of the disk
2992 * write. When the disk write completes, the memory block is again brought
2995 * In-core inode structure reclamation.
2997 * Because there are a finite number of "in-core" inode structures, they are
2998 * reused regularly. By transferring all inode-related dependencies to the
2999 * in-memory inode block and indexing them separately (via "inodedep"s), we
3000 * can allow "in-core" inode structures to be reused at any time and avoid
3001 * any increase in contention.
3003 * Called just before entering the device driver to initiate a new disk I/O.
3004 * The buffer must be locked, thus, no I/O completion operations can occur
3005 * while we are manipulating its associated dependencies.
3007 * bioops callback - hold io_token
3010 * bp: structure describing disk write to occur
3013 softdep_disk_io_initiation(struct buf *bp)
3015 struct worklist *wk;
3016 struct worklist marker;
3017 struct indirdep *indirdep;
3020 * We only care about write operations. There should never
3021 * be dependencies for reads.
3023 if (bp->b_cmd == BUF_CMD_READ)
3024 panic("softdep_disk_io_initiation: read");
3028 marker.wk_type = D_LAST + 1; /* Not a normal workitem */
3031 * Do any necessary pre-I/O processing.
3033 for (wk = LIST_FIRST(&bp->b_dep); wk; wk = markernext(&marker)) {
3034 LIST_INSERT_AFTER(wk, &marker, wk_list);
3036 switch (wk->wk_type) {
3038 initiate_write_filepage(WK_PAGEDEP(wk), bp);
3042 initiate_write_inodeblock(WK_INODEDEP(wk), bp);
3046 indirdep = WK_INDIRDEP(wk);
3047 if (indirdep->ir_state & GOINGAWAY)
3048 panic("disk_io_initiation: indirdep gone");
3050 * If there are no remaining dependencies, this
3051 * will be writing the real pointers, so the
3052 * dependency can be freed.
3054 if (LIST_FIRST(&indirdep->ir_deplisthd) == NULL) {
3055 indirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
3056 brelse(indirdep->ir_savebp);
3057 /* inline expand WORKLIST_REMOVE(wk); */
3058 wk->wk_state &= ~ONWORKLIST;
3059 LIST_REMOVE(wk, wk_list);
3060 WORKITEM_FREE(indirdep, D_INDIRDEP);
3064 * Replace up-to-date version with safe version.
3066 indirdep->ir_saveddata = kmalloc(bp->b_bcount,
3070 indirdep->ir_state &= ~ATTACHED;
3071 indirdep->ir_state |= UNDONE;
3072 bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
3073 bcopy(indirdep->ir_savebp->b_data, bp->b_data,
3085 panic("handle_disk_io_initiation: Unexpected type %s",
3086 TYPENAME(wk->wk_type));
3095 * Called from within the procedure above to deal with unsatisfied
3096 * allocation dependencies in a directory. The buffer must be locked,
3097 * thus, no I/O completion operations can occur while we are
3098 * manipulating its associated dependencies.
3101 initiate_write_filepage(struct pagedep *pagedep, struct buf *bp)
3107 if (pagedep->pd_state & IOSTARTED) {
3109 * This can only happen if there is a driver that does not
3110 * understand chaining. Here biodone will reissue the call
3111 * to strategy for the incomplete buffers.
3113 kprintf("initiate_write_filepage: already started\n");
3116 pagedep->pd_state |= IOSTARTED;
3118 for (i = 0; i < DAHASHSZ; i++) {
3119 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
3120 ep = (struct direct *)
3121 ((char *)bp->b_data + dap->da_offset);
3122 if (ep->d_ino != dap->da_newinum) {
3124 panic("%s: dir inum %d != new %"PRId64,
3125 "initiate_write_filepage",
3126 ep->d_ino, dap->da_newinum);
3128 if (dap->da_state & DIRCHG)
3129 ep->d_ino = dap->da_previous->dm_oldinum;
3132 dap->da_state &= ~ATTACHED;
3133 dap->da_state |= UNDONE;
3140 * Called from within the procedure above to deal with unsatisfied
3141 * allocation dependencies in an inodeblock. The buffer must be
3142 * locked, thus, no I/O completion operations can occur while we
3143 * are manipulating its associated dependencies.
3146 * bp: The inode block
3149 initiate_write_inodeblock(struct inodedep *inodedep, struct buf *bp)
3151 struct allocdirect *adp, *lastadp;
3152 struct ufs1_dinode *dp;
3153 struct ufs1_dinode *sip;
3155 ufs_lbn_t prevlbn = 0;
3158 if (inodedep->id_state & IOSTARTED)
3159 panic("initiate_write_inodeblock: already started");
3160 inodedep->id_state |= IOSTARTED;
3161 fs = inodedep->id_fs;
3162 dp = (struct ufs1_dinode *)bp->b_data +
3163 ino_to_fsbo(fs, inodedep->id_ino);
3165 * If the bitmap is not yet written, then the allocated
3166 * inode cannot be written to disk.
3168 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
3169 if (inodedep->id_savedino != NULL)
3170 panic("initiate_write_inodeblock: already doing I/O");
3171 sip = kmalloc(sizeof(struct ufs1_dinode), M_INODEDEP,
3173 inodedep->id_savedino = sip;
3174 *inodedep->id_savedino = *dp;
3175 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
3176 dp->di_gen = inodedep->id_savedino->di_gen;
3180 * If no dependencies, then there is nothing to roll back.
3182 inodedep->id_savedsize = dp->di_size;
3183 if (TAILQ_FIRST(&inodedep->id_inoupdt) == NULL)
3186 * Set the dependencies to busy.
3189 for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3190 adp = TAILQ_NEXT(adp, ad_next)) {
3192 if (deplist != 0 && prevlbn >= adp->ad_lbn) {
3194 panic("softdep_write_inodeblock: lbn order");
3196 prevlbn = adp->ad_lbn;
3197 if (adp->ad_lbn < NDADDR &&
3198 dp->di_db[adp->ad_lbn] != adp->ad_newblkno) {
3200 panic("%s: direct pointer #%ld mismatch %d != %d",
3201 "softdep_write_inodeblock", adp->ad_lbn,
3202 dp->di_db[adp->ad_lbn], adp->ad_newblkno);
3204 if (adp->ad_lbn >= NDADDR &&
3205 dp->di_ib[adp->ad_lbn - NDADDR] != adp->ad_newblkno) {
3207 panic("%s: indirect pointer #%ld mismatch %d != %d",
3208 "softdep_write_inodeblock", adp->ad_lbn - NDADDR,
3209 dp->di_ib[adp->ad_lbn - NDADDR], adp->ad_newblkno);
3211 deplist |= 1 << adp->ad_lbn;
3212 if ((adp->ad_state & ATTACHED) == 0) {
3214 panic("softdep_write_inodeblock: Unknown state 0x%x",
3217 #endif /* DIAGNOSTIC */
3218 adp->ad_state &= ~ATTACHED;
3219 adp->ad_state |= UNDONE;
3222 * The on-disk inode cannot claim to be any larger than the last
3223 * fragment that has been written. Otherwise, the on-disk inode
3224 * might have fragments that were not the last block in the file
3225 * which would corrupt the filesystem.
3227 for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3228 lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
3229 if (adp->ad_lbn >= NDADDR)
3231 dp->di_db[adp->ad_lbn] = adp->ad_oldblkno;
3232 /* keep going until hitting a rollback to a frag */
3233 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
3235 dp->di_size = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
3236 for (i = adp->ad_lbn + 1; i < NDADDR; i++) {
3238 if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0) {
3240 panic("softdep_write_inodeblock: lost dep1");
3242 #endif /* DIAGNOSTIC */
3245 for (i = 0; i < NIADDR; i++) {
3247 if (dp->di_ib[i] != 0 &&
3248 (deplist & ((1 << NDADDR) << i)) == 0) {
3250 panic("softdep_write_inodeblock: lost dep2");
3252 #endif /* DIAGNOSTIC */
3259 * If we have zero'ed out the last allocated block of the file,
3260 * roll back the size to the last currently allocated block.
3261 * We know that this last allocated block is a full-sized as
3262 * we already checked for fragments in the loop above.
3264 if (lastadp != NULL &&
3265 dp->di_size <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
3266 for (i = lastadp->ad_lbn; i >= 0; i--)
3267 if (dp->di_db[i] != 0)
3269 dp->di_size = (i + 1) * fs->fs_bsize;
3272 * The only dependencies are for indirect blocks.
3274 * The file size for indirect block additions is not guaranteed.
3275 * Such a guarantee would be non-trivial to achieve. The conventional
3276 * synchronous write implementation also does not make this guarantee.
3277 * Fsck should catch and fix discrepancies. Arguably, the file size
3278 * can be over-estimated without destroying integrity when the file
3279 * moves into the indirect blocks (i.e., is large). If we want to
3280 * postpone fsck, we are stuck with this argument.
3282 for (; adp; adp = TAILQ_NEXT(adp, ad_next))
3283 dp->di_ib[adp->ad_lbn - NDADDR] = 0;
3288 * This routine is called during the completion interrupt
3289 * service routine for a disk write (from the procedure called
3290 * by the device driver to inform the filesystem caches of
3291 * a request completion). It should be called early in this
3292 * procedure, before the block is made available to other
3293 * processes or other routines are called.
3295 * bioops callback - hold io_token
3298 * bp: describes the completed disk write
3301 softdep_disk_write_complete(struct buf *bp)
3303 struct worklist *wk;
3304 struct workhead reattach;
3305 struct newblk *newblk;
3306 struct allocindir *aip;
3307 struct allocdirect *adp;
3308 struct indirdep *indirdep;
3309 struct inodedep *inodedep;
3310 struct bmsafemap *bmsafemap;
3314 LIST_INIT(&reattach);
3315 while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
3316 WORKLIST_REMOVE(wk);
3317 switch (wk->wk_type) {
3320 if (handle_written_filepage(WK_PAGEDEP(wk), bp))
3321 WORKLIST_INSERT(&reattach, wk);
3325 if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
3326 WORKLIST_INSERT(&reattach, wk);
3330 bmsafemap = WK_BMSAFEMAP(wk);
3331 while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkhd))) {
3332 newblk->nb_state |= DEPCOMPLETE;
3333 newblk->nb_bmsafemap = NULL;
3334 LIST_REMOVE(newblk, nb_deps);
3337 LIST_FIRST(&bmsafemap->sm_allocdirecthd))) {
3338 adp->ad_state |= DEPCOMPLETE;
3340 LIST_REMOVE(adp, ad_deps);
3341 handle_allocdirect_partdone(adp);
3344 LIST_FIRST(&bmsafemap->sm_allocindirhd))) {
3345 aip->ai_state |= DEPCOMPLETE;
3347 LIST_REMOVE(aip, ai_deps);
3348 handle_allocindir_partdone(aip);
3351 LIST_FIRST(&bmsafemap->sm_inodedephd)) != NULL) {
3352 inodedep->id_state |= DEPCOMPLETE;
3353 LIST_REMOVE(inodedep, id_deps);
3354 inodedep->id_buf = NULL;
3356 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
3360 handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
3364 adp = WK_ALLOCDIRECT(wk);
3365 adp->ad_state |= COMPLETE;
3366 handle_allocdirect_partdone(adp);
3370 aip = WK_ALLOCINDIR(wk);
3371 aip->ai_state |= COMPLETE;
3372 handle_allocindir_partdone(aip);
3376 indirdep = WK_INDIRDEP(wk);
3377 if (indirdep->ir_state & GOINGAWAY) {
3378 panic("disk_write_complete: indirdep gone");
3380 bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
3381 kfree(indirdep->ir_saveddata, M_INDIRDEP);
3382 indirdep->ir_saveddata = 0;
3383 indirdep->ir_state &= ~UNDONE;
3384 indirdep->ir_state |= ATTACHED;
3385 while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
3386 handle_allocindir_partdone(aip);
3387 if (aip == LIST_FIRST(&indirdep->ir_donehd)) {
3388 panic("disk_write_complete: not gone");
3391 WORKLIST_INSERT(&reattach, wk);
3392 if ((bp->b_flags & B_DELWRI) == 0)
3393 stat_indir_blk_ptrs++;
3398 panic("handle_disk_write_complete: Unknown type %s",
3399 TYPENAME(wk->wk_type));
3404 * Reattach any requests that must be redone.
3406 while ((wk = LIST_FIRST(&reattach)) != NULL) {
3407 WORKLIST_REMOVE(wk);
3408 WORKLIST_INSERT_BP(bp, wk);
3415 * Called from within softdep_disk_write_complete above. Note that
3416 * this routine is always called from interrupt level with further
3417 * splbio interrupts blocked.
3420 * adp: the completed allocdirect
3423 handle_allocdirect_partdone(struct allocdirect *adp)
3425 struct allocdirect *listadp;
3426 struct inodedep *inodedep;
3429 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3431 if (adp->ad_buf != NULL)
3432 panic("handle_allocdirect_partdone: dangling dep");
3435 * The on-disk inode cannot claim to be any larger than the last
3436 * fragment that has been written. Otherwise, the on-disk inode
3437 * might have fragments that were not the last block in the file
3438 * which would corrupt the filesystem. Thus, we cannot free any
3439 * allocdirects after one whose ad_oldblkno claims a fragment as
3440 * these blocks must be rolled back to zero before writing the inode.
3441 * We check the currently active set of allocdirects in id_inoupdt.
3443 inodedep = adp->ad_inodedep;
3444 bsize = inodedep->id_fs->fs_bsize;
3445 TAILQ_FOREACH(listadp, &inodedep->id_inoupdt, ad_next) {
3446 /* found our block */
3449 /* continue if ad_oldlbn is not a fragment */
3450 if (listadp->ad_oldsize == 0 ||
3451 listadp->ad_oldsize == bsize)
3453 /* hit a fragment */
3457 * If we have reached the end of the current list without
3458 * finding the just finished dependency, then it must be
3459 * on the future dependency list. Future dependencies cannot
3460 * be freed until they are moved to the current list.
3462 if (listadp == NULL) {
3464 TAILQ_FOREACH(listadp, &inodedep->id_newinoupdt, ad_next)
3465 /* found our block */
3468 if (listadp == NULL)
3469 panic("handle_allocdirect_partdone: lost dep");
3474 * If we have found the just finished dependency, then free
3475 * it along with anything that follows it that is complete.
3477 for (; adp; adp = listadp) {
3478 listadp = TAILQ_NEXT(adp, ad_next);
3479 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3481 free_allocdirect(&inodedep->id_inoupdt, adp, 1);
3486 * Called from within softdep_disk_write_complete above. Note that
3487 * this routine is always called from interrupt level with further
3488 * splbio interrupts blocked.
3491 * aip: the completed allocindir
3494 handle_allocindir_partdone(struct allocindir *aip)
3496 struct indirdep *indirdep;
3498 if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
3500 if (aip->ai_buf != NULL)
3501 panic("handle_allocindir_partdone: dangling dependency");
3503 indirdep = aip->ai_indirdep;
3504 if (indirdep->ir_state & UNDONE) {
3505 LIST_REMOVE(aip, ai_next);
3506 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
3509 ((ufs_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
3511 LIST_REMOVE(aip, ai_next);
3512 if (aip->ai_freefrag != NULL)
3513 add_to_worklist(&aip->ai_freefrag->ff_list);
3514 WORKITEM_FREE(aip, D_ALLOCINDIR);
3518 * Called from within softdep_disk_write_complete above to restore
3519 * in-memory inode block contents to their most up-to-date state. Note
3520 * that this routine is always called from interrupt level with further
3521 * splbio interrupts blocked.
3524 * bp: buffer containing the inode block
3527 handle_written_inodeblock(struct inodedep *inodedep, struct buf *bp)
3529 struct worklist *wk, *filefree;
3530 struct allocdirect *adp, *nextadp;
3531 struct ufs1_dinode *dp;
3534 if ((inodedep->id_state & IOSTARTED) == 0)
3535 panic("handle_written_inodeblock: not started");
3537 inodedep->id_state &= ~IOSTARTED;
3538 dp = (struct ufs1_dinode *)bp->b_data +
3539 ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
3541 * If we had to rollback the inode allocation because of
3542 * bitmaps being incomplete, then simply restore it.
3543 * Keep the block dirty so that it will not be reclaimed until
3544 * all associated dependencies have been cleared and the
3545 * corresponding updates written to disk.
3547 if (inodedep->id_savedino != NULL) {
3548 *dp = *inodedep->id_savedino;
3549 kfree(inodedep->id_savedino, M_INODEDEP);
3550 inodedep->id_savedino = NULL;
3551 if ((bp->b_flags & B_DELWRI) == 0)
3552 stat_inode_bitmap++;
3556 inodedep->id_state |= COMPLETE;
3558 * Roll forward anything that had to be rolled back before
3559 * the inode could be updated.
3562 for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
3563 nextadp = TAILQ_NEXT(adp, ad_next);
3564 if (adp->ad_state & ATTACHED)
3565 panic("handle_written_inodeblock: new entry");
3567 if (adp->ad_lbn < NDADDR) {
3568 if (dp->di_db[adp->ad_lbn] != adp->ad_oldblkno) {
3569 panic("%s: %s #%ld mismatch %d != %d",
3570 "handle_written_inodeblock",
3571 "direct pointer", adp->ad_lbn,
3572 dp->di_db[adp->ad_lbn], adp->ad_oldblkno);
3574 dp->di_db[adp->ad_lbn] = adp->ad_newblkno;
3576 if (dp->di_ib[adp->ad_lbn - NDADDR] != 0) {
3577 panic("%s: %s #%ld allocated as %d",
3578 "handle_written_inodeblock",
3579 "indirect pointer", adp->ad_lbn - NDADDR,
3580 dp->di_ib[adp->ad_lbn - NDADDR]);
3582 dp->di_ib[adp->ad_lbn - NDADDR] = adp->ad_newblkno;
3584 adp->ad_state &= ~UNDONE;
3585 adp->ad_state |= ATTACHED;
3588 if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
3589 stat_direct_blk_ptrs++;
3591 * Reset the file size to its most up-to-date value.
3593 if (inodedep->id_savedsize == -1) {
3594 panic("handle_written_inodeblock: bad size");
3596 if (dp->di_size != inodedep->id_savedsize) {
3597 dp->di_size = inodedep->id_savedsize;
3600 inodedep->id_savedsize = -1;
3602 * If there were any rollbacks in the inode block, then it must be
3603 * marked dirty so that its will eventually get written back in
3609 * Process any allocdirects that completed during the update.
3611 if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
3612 handle_allocdirect_partdone(adp);
3614 * Process deallocations that were held pending until the
3615 * inode had been written to disk. Freeing of the inode
3616 * is delayed until after all blocks have been freed to
3617 * avoid creation of new <vfsid, inum, lbn> triples
3618 * before the old ones have been deleted.
3621 while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
3622 WORKLIST_REMOVE(wk);
3623 switch (wk->wk_type) {
3627 * We defer adding filefree to the worklist until
3628 * all other additions have been made to ensure
3629 * that it will be done after all the old blocks
3632 if (filefree != NULL) {
3633 panic("handle_written_inodeblock: filefree");
3639 handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
3643 diradd_inode_written(WK_DIRADD(wk), inodedep);
3647 wk->wk_state |= COMPLETE;
3648 if ((wk->wk_state & ALLCOMPLETE) != ALLCOMPLETE)
3650 /* -- fall through -- */
3653 add_to_worklist(wk);
3657 panic("handle_written_inodeblock: Unknown type %s",
3658 TYPENAME(wk->wk_type));
3662 if (filefree != NULL) {
3663 if (free_inodedep(inodedep) == 0) {
3664 panic("handle_written_inodeblock: live inodedep");
3666 add_to_worklist(filefree);
3671 * If no outstanding dependencies, free it.
3673 if (free_inodedep(inodedep) || TAILQ_FIRST(&inodedep->id_inoupdt) == 0)
3675 return (hadchanges);
3679 * Process a diradd entry after its dependent inode has been written.
3680 * This routine must be called with splbio interrupts blocked.
3683 diradd_inode_written(struct diradd *dap, struct inodedep *inodedep)
3685 struct pagedep *pagedep;
3687 dap->da_state |= COMPLETE;
3688 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3689 if (dap->da_state & DIRCHG)
3690 pagedep = dap->da_previous->dm_pagedep;
3692 pagedep = dap->da_pagedep;
3693 LIST_REMOVE(dap, da_pdlist);
3694 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3696 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
3700 * Handle the completion of a mkdir dependency.
3703 handle_written_mkdir(struct mkdir *mkdir, int type)
3706 struct pagedep *pagedep;
3708 if (mkdir->md_state != type) {
3709 panic("handle_written_mkdir: bad type");
3711 dap = mkdir->md_diradd;
3712 dap->da_state &= ~type;
3713 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
3714 dap->da_state |= DEPCOMPLETE;
3715 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3716 if (dap->da_state & DIRCHG)
3717 pagedep = dap->da_previous->dm_pagedep;
3719 pagedep = dap->da_pagedep;
3720 LIST_REMOVE(dap, da_pdlist);
3721 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3723 LIST_REMOVE(mkdir, md_mkdirs);
3724 WORKITEM_FREE(mkdir, D_MKDIR);
3728 * Called from within softdep_disk_write_complete above.
3729 * A write operation was just completed. Removed inodes can
3730 * now be freed and associated block pointers may be committed.
3731 * Note that this routine is always called from interrupt level
3732 * with further splbio interrupts blocked.
3735 * bp: buffer containing the written page
3738 handle_written_filepage(struct pagedep *pagedep, struct buf *bp)
3740 struct dirrem *dirrem;
3741 struct diradd *dap, *nextdap;
3745 if ((pagedep->pd_state & IOSTARTED) == 0) {
3746 panic("handle_written_filepage: not started");
3748 pagedep->pd_state &= ~IOSTARTED;
3750 * Process any directory removals that have been committed.
3752 while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
3753 LIST_REMOVE(dirrem, dm_next);
3754 dirrem->dm_dirinum = pagedep->pd_ino;
3755 add_to_worklist(&dirrem->dm_list);
3758 * Free any directory additions that have been committed.
3760 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
3763 * Uncommitted directory entries must be restored.
3765 for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
3766 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
3768 nextdap = LIST_NEXT(dap, da_pdlist);
3769 if (dap->da_state & ATTACHED) {
3770 panic("handle_written_filepage: attached");
3772 ep = (struct direct *)
3773 ((char *)bp->b_data + dap->da_offset);
3774 ep->d_ino = dap->da_newinum;
3775 dap->da_state &= ~UNDONE;
3776 dap->da_state |= ATTACHED;
3779 * If the inode referenced by the directory has
3780 * been written out, then the dependency can be
3781 * moved to the pending list.
3783 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3784 LIST_REMOVE(dap, da_pdlist);
3785 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
3791 * If there were any rollbacks in the directory, then it must be
3792 * marked dirty so that its will eventually get written back in
3796 if ((bp->b_flags & B_DELWRI) == 0)
3801 * If no dependencies remain, the pagedep will be freed.
3802 * Otherwise it will remain to update the page before it
3803 * is written back to disk.
3805 if (LIST_FIRST(&pagedep->pd_pendinghd) == 0) {
3806 for (i = 0; i < DAHASHSZ; i++)
3807 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) != NULL)
3809 if (i == DAHASHSZ) {
3810 LIST_REMOVE(pagedep, pd_hash);
3811 WORKITEM_FREE(pagedep, D_PAGEDEP);
3819 * Writing back in-core inode structures.
3821 * The filesystem only accesses an inode's contents when it occupies an
3822 * "in-core" inode structure. These "in-core" structures are separate from
3823 * the page frames used to cache inode blocks. Only the latter are
3824 * transferred to/from the disk. So, when the updated contents of the
3825 * "in-core" inode structure are copied to the corresponding in-memory inode
3826 * block, the dependencies are also transferred. The following procedure is
3827 * called when copying a dirty "in-core" inode to a cached inode block.
3831 * Called when an inode is loaded from disk. If the effective link count
3832 * differed from the actual link count when it was last flushed, then we
3833 * need to ensure that the correct effective link count is put back.
3836 * ip: the "in_core" copy of the inode
3839 softdep_load_inodeblock(struct inode *ip)
3841 struct inodedep *inodedep;
3844 * Check for alternate nlink count.
3846 ip->i_effnlink = ip->i_nlink;
3848 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3852 ip->i_effnlink -= inodedep->id_nlinkdelta;
3857 * This routine is called just before the "in-core" inode
3858 * information is to be copied to the in-memory inode block.
3859 * Recall that an inode block contains several inodes. If
3860 * the force flag is set, then the dependencies will be
3861 * cleared so that the update can always be made. Note that
3862 * the buffer is locked when this routine is called, so we
3863 * will never be in the middle of writing the inode block
3867 * ip: the "in_core" copy of the inode
3868 * bp: the buffer containing the inode block
3869 * waitfor: nonzero => update must be allowed
3872 softdep_update_inodeblock(struct inode *ip, struct buf *bp,
3875 struct inodedep *inodedep;
3876 struct worklist *wk;
3880 * If the effective link count is not equal to the actual link
3881 * count, then we must track the difference in an inodedep while
3882 * the inode is (potentially) tossed out of the cache. Otherwise,
3883 * if there is no existing inodedep, then there are no dependencies
3887 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3889 if (ip->i_effnlink != ip->i_nlink)
3890 panic("softdep_update_inodeblock: bad link count");
3893 if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink) {
3895 panic("softdep_update_inodeblock: bad delta");
3898 * Changes have been initiated. Anything depending on these
3899 * changes cannot occur until this inode has been written.
3901 inodedep->id_state &= ~COMPLETE;
3902 if ((inodedep->id_state & ONWORKLIST) == 0)
3903 WORKLIST_INSERT_BP(bp, &inodedep->id_list);
3905 * Any new dependencies associated with the incore inode must
3906 * now be moved to the list associated with the buffer holding
3907 * the in-memory copy of the inode. Once merged process any
3908 * allocdirects that are completed by the merger.
3910 merge_inode_lists(inodedep);
3911 if (TAILQ_FIRST(&inodedep->id_inoupdt) != NULL)
3912 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt));
3914 * Now that the inode has been pushed into the buffer, the
3915 * operations dependent on the inode being written to disk
3916 * can be moved to the id_bufwait so that they will be
3917 * processed when the buffer I/O completes.
3919 while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
3920 WORKLIST_REMOVE(wk);
3921 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
3924 * Newly allocated inodes cannot be written until the bitmap
3925 * that allocates them have been written (indicated by
3926 * DEPCOMPLETE being set in id_state). If we are doing a
3927 * forced sync (e.g., an fsync on a file), we force the bitmap
3928 * to be written so that the update can be done.
3935 if ((inodedep->id_state & DEPCOMPLETE) != 0) {
3939 gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
3941 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) != 0)
3947 if ((error = bwrite(inodedep->id_buf)) != 0)
3948 softdep_error("softdep_update_inodeblock: bwrite", error);
3952 * Merge the new inode dependency list (id_newinoupdt) into the old
3953 * inode dependency list (id_inoupdt). This routine must be called
3954 * with splbio interrupts blocked.
3957 merge_inode_lists(struct inodedep *inodedep)
3959 struct allocdirect *listadp, *newadp;
3961 newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3962 for (listadp = TAILQ_FIRST(&inodedep->id_inoupdt); listadp && newadp;) {
3963 if (listadp->ad_lbn < newadp->ad_lbn) {
3964 listadp = TAILQ_NEXT(listadp, ad_next);
3967 TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3968 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
3969 if (listadp->ad_lbn == newadp->ad_lbn) {
3970 allocdirect_merge(&inodedep->id_inoupdt, newadp,
3974 newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3976 while ((newadp = TAILQ_FIRST(&inodedep->id_newinoupdt)) != NULL) {
3977 TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3978 TAILQ_INSERT_TAIL(&inodedep->id_inoupdt, newadp, ad_next);
3983 * If we are doing an fsync, then we must ensure that any directory
3984 * entries for the inode have been written after the inode gets to disk.
3986 * bioops callback - hold io_token
3989 * vp: the "in_core" copy of the inode
3992 softdep_fsync(struct vnode *vp)
3994 struct inodedep *inodedep;
3995 struct pagedep *pagedep;
3996 struct worklist *wk;
4003 int error, flushparent;
4008 * Move check from original kernel code, possibly not needed any
4009 * more with the per-mount bioops.
4011 if ((vp->v_mount->mnt_flag & MNT_SOFTDEP) == 0)
4018 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0) {
4023 if (LIST_FIRST(&inodedep->id_inowait) != NULL ||
4024 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
4025 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
4026 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL) {
4028 panic("softdep_fsync: pending ops");
4030 for (error = 0, flushparent = 0; ; ) {
4031 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
4033 if (wk->wk_type != D_DIRADD) {
4035 panic("softdep_fsync: Unexpected type %s",
4036 TYPENAME(wk->wk_type));
4038 dap = WK_DIRADD(wk);
4040 * Flush our parent if this directory entry
4041 * has a MKDIR_PARENT dependency.
4043 if (dap->da_state & DIRCHG)
4044 pagedep = dap->da_previous->dm_pagedep;
4046 pagedep = dap->da_pagedep;
4047 mnt = pagedep->pd_mnt;
4048 parentino = pagedep->pd_ino;
4049 lbn = pagedep->pd_lbn;
4050 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE) {
4052 panic("softdep_fsync: dirty");
4054 flushparent = dap->da_state & MKDIR_PARENT;
4056 * If we are being fsync'ed as part of vgone'ing this vnode,
4057 * then we will not be able to release and recover the
4058 * vnode below, so we just have to give up on writing its
4059 * directory entry out. It will eventually be written, just
4060 * not now, but then the user was not asking to have it
4061 * written, so we are not breaking any promises.
4063 if (vp->v_flag & VRECLAIMED)
4066 * We prevent deadlock by always fetching inodes from the
4067 * root, moving down the directory tree. Thus, when fetching
4068 * our parent directory, we must unlock ourselves before
4069 * requesting the lock on our parent. See the comment in
4070 * ufs_lookup for details on possible races.
4074 error = VFS_VGET(mnt, NULL, parentino, &pvp);
4075 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4081 if ((error = ffs_update(pvp, 1)) != 0) {
4088 * Flush directory page containing the inode's name.
4090 error = bread(pvp, lblktodoff(fs, lbn), blksize(fs, VTOI(pvp), lbn), &bp);
4099 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0)
4108 * Flush all the dirty bitmaps associated with the block device
4109 * before flushing the rest of the dirty blocks so as to reduce
4110 * the number of dependencies that will have to be rolled back.
4112 static int softdep_fsync_mountdev_bp(struct buf *bp, void *data);
4115 softdep_fsync_mountdev(struct vnode *vp)
4117 if (!vn_isdisk(vp, NULL))
4118 panic("softdep_fsync_mountdev: vnode not a disk");
4120 lwkt_gettoken(&vp->v_token);
4121 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
4122 softdep_fsync_mountdev_bp, vp);
4123 lwkt_reltoken(&vp->v_token);
4124 drain_output(vp, 1);
4129 softdep_fsync_mountdev_bp(struct buf *bp, void *data)
4131 struct worklist *wk;
4132 struct vnode *vp = data;
4135 * If it is already scheduled, skip to the next buffer.
4137 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT))
4139 if (bp->b_vp != vp || (bp->b_flags & B_DELWRI) == 0) {
4141 kprintf("softdep_fsync_mountdev_bp: warning, buffer %p ripped out from under vnode %p\n", bp, vp);
4145 * We are only interested in bitmaps with outstanding
4148 if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
4149 wk->wk_type != D_BMSAFEMAP) {
4161 * This routine is called when we are trying to synchronously flush a
4162 * file. This routine must eliminate any filesystem metadata dependencies
4163 * so that the syncing routine can succeed by pushing the dirty blocks
4164 * associated with the file. If any I/O errors occur, they are returned.
4166 struct softdep_sync_metadata_info {
4171 static int softdep_sync_metadata_bp(struct buf *bp, void *data);
4174 softdep_sync_metadata(struct vnode *vp, struct thread *td)
4176 struct softdep_sync_metadata_info info;
4180 * Check whether this vnode is involved in a filesystem
4181 * that is doing soft dependency processing.
4183 if (!vn_isdisk(vp, NULL)) {
4184 if (!DOINGSOFTDEP(vp))
4187 if (vp->v_rdev->si_mountpoint == NULL ||
4188 (vp->v_rdev->si_mountpoint->mnt_flag & MNT_SOFTDEP) == 0)
4191 * Ensure that any direct block dependencies have been cleared.
4194 if ((error = flush_inodedep_deps(VTOI(vp)->i_fs, VTOI(vp)->i_number))) {
4199 * For most files, the only metadata dependencies are the
4200 * cylinder group maps that allocate their inode or blocks.
4201 * The block allocation dependencies can be found by traversing
4202 * the dependency lists for any buffers that remain on their
4203 * dirty buffer list. The inode allocation dependency will
4204 * be resolved when the inode is updated with MNT_WAIT.
4205 * This work is done in two passes. The first pass grabs most
4206 * of the buffers and begins asynchronously writing them. The
4207 * only way to wait for these asynchronous writes is to sleep
4208 * on the filesystem vnode which may stay busy for a long time
4209 * if the filesystem is active. So, instead, we make a second
4210 * pass over the dependencies blocking on each write. In the
4211 * usual case we will be blocking against a write that we
4212 * initiated, so when it is done the dependency will have been
4213 * resolved. Thus the second pass is expected to end quickly.
4215 waitfor = MNT_NOWAIT;
4218 * We must wait for any I/O in progress to finish so that
4219 * all potential buffers on the dirty list will be visible.
4221 drain_output(vp, 1);
4224 info.waitfor = waitfor;
4225 lwkt_gettoken(&vp->v_token);
4226 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
4227 softdep_sync_metadata_bp, &info);
4228 lwkt_reltoken(&vp->v_token);
4231 return(-error); /* error code */
4235 * The brief unlock is to allow any pent up dependency
4236 * processing to be done. Then proceed with the second pass.
4238 if (waitfor & MNT_NOWAIT) {
4246 * If we have managed to get rid of all the dirty buffers,
4247 * then we are done. For certain directories and block
4248 * devices, we may need to do further work.
4250 * We must wait for any I/O in progress to finish so that
4251 * all potential buffers on the dirty list will be visible.
4253 drain_output(vp, 1);
4254 if (RB_EMPTY(&vp->v_rbdirty_tree)) {
4261 * If we are trying to sync a block device, some of its buffers may
4262 * contain metadata that cannot be written until the contents of some
4263 * partially written files have been written to disk. The only easy
4264 * way to accomplish this is to sync the entire filesystem (luckily
4265 * this happens rarely).
4267 if (vn_isdisk(vp, NULL) &&
4269 vp->v_rdev->si_mountpoint && !vn_islocked(vp) &&
4270 (error = VFS_SYNC(vp->v_rdev->si_mountpoint, MNT_WAIT)) != 0)
4276 softdep_sync_metadata_bp(struct buf *bp, void *data)
4278 struct softdep_sync_metadata_info *info = data;
4279 struct pagedep *pagedep;
4280 struct allocdirect *adp;
4281 struct allocindir *aip;
4282 struct worklist *wk;
4287 if (getdirtybuf(&bp, MNT_WAIT) == 0) {
4288 kprintf("softdep_sync_metadata_bp(1): caught buf %p going away\n", bp);
4291 if (bp->b_vp != info->vp || (bp->b_flags & B_DELWRI) == 0) {
4292 kprintf("softdep_sync_metadata_bp(2): caught buf %p going away vp %p\n", bp, info->vp);
4298 * As we hold the buffer locked, none of its dependencies
4301 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4302 switch (wk->wk_type) {
4305 adp = WK_ALLOCDIRECT(wk);
4306 if (adp->ad_state & DEPCOMPLETE)
4309 if (getdirtybuf(&nbp, info->waitfor) == 0)
4312 if (info->waitfor & MNT_NOWAIT) {
4314 } else if ((error = bwrite(nbp)) != 0) {
4323 aip = WK_ALLOCINDIR(wk);
4324 if (aip->ai_state & DEPCOMPLETE)
4327 if (getdirtybuf(&nbp, info->waitfor) == 0)
4330 if (info->waitfor & MNT_NOWAIT) {
4332 } else if ((error = bwrite(nbp)) != 0) {
4343 LIST_FOREACH(aip, &WK_INDIRDEP(wk)->ir_deplisthd, ai_next) {
4344 if (aip->ai_state & DEPCOMPLETE)
4347 if (getdirtybuf(&nbp, MNT_WAIT) == 0)
4350 if ((error = bwrite(nbp)) != 0) {
4361 if ((error = flush_inodedep_deps(WK_INODEDEP(wk)->id_fs,
4362 WK_INODEDEP(wk)->id_ino)) != 0) {
4372 * We are trying to sync a directory that may
4373 * have dependencies on both its own metadata
4374 * and/or dependencies on the inodes of any
4375 * recently allocated files. We walk its diradd
4376 * lists pushing out the associated inode.
4378 pagedep = WK_PAGEDEP(wk);
4379 for (i = 0; i < DAHASHSZ; i++) {
4380 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
4383 flush_pagedep_deps(info->vp,
4385 &pagedep->pd_diraddhd[i]))) {
4396 * This case should never happen if the vnode has
4397 * been properly sync'ed. However, if this function
4398 * is used at a place where the vnode has not yet
4399 * been sync'ed, this dependency can show up. So,
4400 * rather than panic, just flush it.
4402 nbp = WK_MKDIR(wk)->md_buf;
4403 if (getdirtybuf(&nbp, info->waitfor) == 0)
4406 if (info->waitfor & MNT_NOWAIT) {
4408 } else if ((error = bwrite(nbp)) != 0) {
4418 * This case should never happen if the vnode has
4419 * been properly sync'ed. However, if this function
4420 * is used at a place where the vnode has not yet
4421 * been sync'ed, this dependency can show up. So,
4422 * rather than panic, just flush it.
4424 * nbp can wind up == bp if a device node for the
4425 * same filesystem is being fsynced at the same time,
4426 * leading to a panic if we don't catch the case.
4428 nbp = WK_BMSAFEMAP(wk)->sm_buf;
4431 if (getdirtybuf(&nbp, info->waitfor) == 0)
4434 if (info->waitfor & MNT_NOWAIT) {
4436 } else if ((error = bwrite(nbp)) != 0) {
4446 panic("softdep_sync_metadata: Unknown type %s",
4447 TYPENAME(wk->wk_type));
4458 * Flush the dependencies associated with an inodedep.
4459 * Called with splbio blocked.
4462 flush_inodedep_deps(struct fs *fs, ino_t ino)
4464 struct inodedep *inodedep;
4465 struct allocdirect *adp;
4470 * This work is done in two passes. The first pass grabs most
4471 * of the buffers and begins asynchronously writing them. The
4472 * only way to wait for these asynchronous writes is to sleep
4473 * on the filesystem vnode which may stay busy for a long time
4474 * if the filesystem is active. So, instead, we make a second
4475 * pass over the dependencies blocking on each write. In the
4476 * usual case we will be blocking against a write that we
4477 * initiated, so when it is done the dependency will have been
4478 * resolved. Thus the second pass is expected to end quickly.
4479 * We give a brief window at the top of the loop to allow
4480 * any pending I/O to complete.
4482 for (waitfor = MNT_NOWAIT; ; ) {
4485 if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4487 TAILQ_FOREACH(adp, &inodedep->id_inoupdt, ad_next) {
4488 if (adp->ad_state & DEPCOMPLETE)
4491 if (getdirtybuf(&bp, waitfor) == 0) {
4492 if (waitfor & MNT_NOWAIT)
4497 if (waitfor & MNT_NOWAIT) {
4499 } else if ((error = bwrite(bp)) != 0) {
4508 TAILQ_FOREACH(adp, &inodedep->id_newinoupdt, ad_next) {
4509 if (adp->ad_state & DEPCOMPLETE)
4512 if (getdirtybuf(&bp, waitfor) == 0) {
4513 if (waitfor & MNT_NOWAIT)
4518 if (waitfor & MNT_NOWAIT) {
4520 } else if ((error = bwrite(bp)) != 0) {
4530 * If pass2, we are done, otherwise do pass 2.
4532 if (waitfor == MNT_WAIT)
4537 * Try freeing inodedep in case all dependencies have been removed.
4539 if (inodedep_lookup(fs, ino, 0, &inodedep) != 0)
4540 (void) free_inodedep(inodedep);
4545 * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
4546 * Called with splbio blocked.
4549 flush_pagedep_deps(struct vnode *pvp, struct mount *mp,
4550 struct diraddhd *diraddhdp)
4552 struct inodedep *inodedep;
4553 struct ufsmount *ump;
4556 int gotit, error = 0;
4561 while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
4563 * Flush ourselves if this directory entry
4564 * has a MKDIR_PARENT dependency.
4566 if (dap->da_state & MKDIR_PARENT) {
4568 if ((error = ffs_update(pvp, 1)) != 0)
4572 * If that cleared dependencies, go on to next.
4574 if (dap != LIST_FIRST(diraddhdp))
4576 if (dap->da_state & MKDIR_PARENT) {
4578 panic("flush_pagedep_deps: MKDIR_PARENT");
4582 * A newly allocated directory must have its "." and
4583 * ".." entries written out before its name can be
4584 * committed in its parent. We do not want or need
4585 * the full semantics of a synchronous VOP_FSYNC as
4586 * that may end up here again, once for each directory
4587 * level in the filesystem. Instead, we push the blocks
4588 * and wait for them to clear. We have to fsync twice
4589 * because the first call may choose to defer blocks
4590 * that still have dependencies, but deferral will
4591 * happen at most once.
4593 inum = dap->da_newinum;
4594 if (dap->da_state & MKDIR_BODY) {
4596 if ((error = VFS_VGET(mp, NULL, inum, &vp)) != 0)
4598 if ((error=VOP_FSYNC(vp, MNT_NOWAIT, 0)) ||
4599 (error=VOP_FSYNC(vp, MNT_NOWAIT, 0))) {
4603 drain_output(vp, 0);
4607 * If that cleared dependencies, go on to next.
4609 if (dap != LIST_FIRST(diraddhdp))
4611 if (dap->da_state & MKDIR_BODY) {
4613 panic("flush_pagedep_deps: MKDIR_BODY");
4617 * Flush the inode on which the directory entry depends.
4618 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
4619 * the only remaining dependency is that the updated inode
4620 * count must get pushed to disk. The inode has already
4621 * been pushed into its inode buffer (via VOP_UPDATE) at
4622 * the time of the reference count change. So we need only
4623 * locate that buffer, ensure that there will be no rollback
4624 * caused by a bitmap dependency, then write the inode buffer.
4626 if (inodedep_lookup(ump->um_fs, inum, 0, &inodedep) == 0) {
4628 panic("flush_pagedep_deps: lost inode");
4631 * If the inode still has bitmap dependencies,
4632 * push them to disk.
4634 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4635 gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
4637 if (gotit && (error = bwrite(inodedep->id_buf)) != 0)
4640 if (dap != LIST_FIRST(diraddhdp))
4644 * If the inode is still sitting in a buffer waiting
4645 * to be written, push it to disk.
4648 if ((error = bread(ump->um_devvp,
4649 fsbtodoff(ump->um_fs, ino_to_fsba(ump->um_fs, inum)),
4650 (int)ump->um_fs->fs_bsize, &bp)) != 0)
4652 if ((error = bwrite(bp)) != 0)
4656 * If we have failed to get rid of all the dependencies
4657 * then something is seriously wrong.
4659 if (dap == LIST_FIRST(diraddhdp)) {
4661 panic("flush_pagedep_deps: flush failed");
4670 * A large burst of file addition or deletion activity can drive the
4671 * memory load excessively high. First attempt to slow things down
4672 * using the techniques below. If that fails, this routine requests
4673 * the offending operations to fall back to running synchronously
4674 * until the memory load returns to a reasonable level.
4677 softdep_slowdown(struct vnode *vp)
4679 int max_softdeps_hard;
4681 max_softdeps_hard = max_softdeps * 11 / 10;
4682 if (num_dirrem < max_softdeps_hard / 2 &&
4683 num_inodedep < max_softdeps_hard)
4685 stat_sync_limit_hit += 1;
4690 * If memory utilization has gotten too high, deliberately slow things
4691 * down and speed up the I/O processing.
4694 request_cleanup(int resource, int islocked)
4696 struct thread *td = curthread; /* XXX */
4699 * We never hold up the filesystem syncer process.
4701 if (td == filesys_syncer)
4704 * First check to see if the work list has gotten backlogged.
4705 * If it has, co-opt this process to help clean up two entries.
4706 * Because this process may hold inodes locked, we cannot
4707 * handle any remove requests that might block on a locked
4708 * inode as that could lead to deadlock.
4710 if (num_on_worklist > max_softdeps / 10) {
4713 process_worklist_item(NULL, LK_NOWAIT);
4714 process_worklist_item(NULL, LK_NOWAIT);
4715 stat_worklist_push += 2;
4722 * If we are resource constrained on inode dependencies, try
4723 * flushing some dirty inodes. Otherwise, we are constrained
4724 * by file deletions, so try accelerating flushes of directories
4725 * with removal dependencies. We would like to do the cleanup
4726 * here, but we probably hold an inode locked at this point and
4727 * that might deadlock against one that we try to clean. So,
4728 * the best that we can do is request the syncer daemon to do
4729 * the cleanup for us.
4734 stat_ino_limit_push += 1;
4735 req_clear_inodedeps += 1;
4736 stat_countp = &stat_ino_limit_hit;
4740 stat_blk_limit_push += 1;
4741 req_clear_remove += 1;
4742 stat_countp = &stat_blk_limit_hit;
4748 panic("request_cleanup: unknown type");
4751 * Hopefully the syncer daemon will catch up and awaken us.
4752 * We wait at most tickdelay before proceeding in any case.
4757 if (!callout_active(&handle))
4758 callout_reset(&handle, tickdelay > 2 ? tickdelay : 2,
4760 interlocked_sleep(&lk, (caddr_t)&proc_waiting, 0,
4769 * Awaken processes pausing in request_cleanup and clear proc_waiting
4770 * to indicate that there is no longer a timer running.
4773 pause_timer(void *arg)
4776 wakeup_one(&proc_waiting);
4777 if (proc_waiting > 0)
4778 callout_reset(&handle, tickdelay > 2 ? tickdelay : 2,
4781 callout_deactivate(&handle);
4785 * Flush out a directory with at least one removal dependency in an effort to
4786 * reduce the number of dirrem, freefile, and freeblks dependency structures.
4789 clear_remove(struct thread *td)
4791 struct pagedep_hashhead *pagedephd;
4792 struct pagedep *pagedep;
4793 static int next = 0;
4800 for (cnt = 0; cnt < pagedep_hash; cnt++) {
4801 pagedephd = &pagedep_hashtbl[next++];
4802 if (next >= pagedep_hash)
4804 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
4805 if (LIST_FIRST(&pagedep->pd_dirremhd) == NULL)
4807 mp = pagedep->pd_mnt;
4808 ino = pagedep->pd_ino;
4810 if ((error = VFS_VGET(mp, NULL, ino, &vp)) != 0) {
4811 softdep_error("clear_remove: vget", error);
4814 if ((error = VOP_FSYNC(vp, MNT_NOWAIT, 0)))
4815 softdep_error("clear_remove: fsync", error);
4816 drain_output(vp, 0);
4825 * Clear out a block of dirty inodes in an effort to reduce
4826 * the number of inodedep dependency structures.
4828 struct clear_inodedeps_info {
4834 clear_inodedeps_mountlist_callback(struct mount *mp, void *data)
4836 struct clear_inodedeps_info *info = data;
4838 if ((mp->mnt_flag & MNT_SOFTDEP) && info->fs == VFSTOUFS(mp)->um_fs) {
4846 clear_inodedeps(struct thread *td)
4848 struct clear_inodedeps_info info;
4849 struct inodedep_hashhead *inodedephd;
4850 struct inodedep *inodedep;
4851 static int next = 0;
4855 ino_t firstino, lastino, ino;
4859 * Pick a random inode dependency to be cleared.
4860 * We will then gather up all the inodes in its block
4861 * that have dependencies and flush them out.
4863 for (cnt = 0; cnt < inodedep_hash; cnt++) {
4864 inodedephd = &inodedep_hashtbl[next++];
4865 if (next >= inodedep_hash)
4867 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
4870 if (inodedep == NULL) {
4875 * Ugly code to find mount point given pointer to superblock.
4877 fs = inodedep->id_fs;
4880 mountlist_scan(clear_inodedeps_mountlist_callback,
4881 &info, MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
4883 * Find the last inode in the block with dependencies.
4885 firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
4886 for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
4887 if (inodedep_lookup(fs, lastino, 0, &inodedep) != 0)
4890 * Asynchronously push all but the last inode with dependencies.
4891 * Synchronously push the last inode with dependencies to ensure
4892 * that the inode block gets written to free up the inodedeps.
4894 for (ino = firstino; ino <= lastino; ino++) {
4895 if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4898 if ((error = VFS_VGET(info.mp, NULL, ino, &vp)) != 0) {
4899 softdep_error("clear_inodedeps: vget", error);
4902 if (ino == lastino) {
4903 if ((error = VOP_FSYNC(vp, MNT_WAIT, 0)))
4904 softdep_error("clear_inodedeps: fsync1", error);
4906 if ((error = VOP_FSYNC(vp, MNT_NOWAIT, 0)))
4907 softdep_error("clear_inodedeps: fsync2", error);
4908 drain_output(vp, 0);
4917 * Function to determine if the buffer has outstanding dependencies
4918 * that will cause a roll-back if the buffer is written. If wantcount
4919 * is set, return number of dependencies, otherwise just yes or no.
4921 * bioops callback - hold io_token
4924 softdep_count_dependencies(struct buf *bp, int wantcount)
4926 struct worklist *wk;
4927 struct inodedep *inodedep;
4928 struct indirdep *indirdep;
4929 struct allocindir *aip;
4930 struct pagedep *pagedep;
4939 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4940 switch (wk->wk_type) {
4943 inodedep = WK_INODEDEP(wk);
4944 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4945 /* bitmap allocation dependency */
4950 if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
4951 /* direct block pointer dependency */
4959 indirdep = WK_INDIRDEP(wk);
4961 LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
4962 /* indirect block pointer dependency */
4970 pagedep = WK_PAGEDEP(wk);
4971 for (i = 0; i < DAHASHSZ; i++) {
4973 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
4974 /* directory entry dependency */
4986 /* never a dependency on these blocks */
4991 panic("softdep_check_for_rollback: Unexpected type %s",
4992 TYPENAME(wk->wk_type));
5006 * Acquire exclusive access to a buffer. Requires softdep lock
5007 * to be held on entry. If waitfor is MNT_WAIT, may release/reacquire
5010 * Returns 1 if the buffer was locked, 0 otherwise.
5013 getdirtybuf(struct buf **bpp, int waitfor)
5023 /* Must acquire buffer lock with ffs_softdep lock held */
5024 KKASSERT(lock_held(&lk) > 0);
5025 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT);
5029 if (waitfor != MNT_WAIT)
5033 * Release ffs_softdep lock around sleep/wait for buffer lock.
5035 * We must acquire buffer lock with softdep lock held, so
5036 * we must retry locking the buffer after we wake.
5039 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL);
5043 else if (error == ENOLCK)
5046 panic("getdirtybuf: Inconsistent lock");
5049 /* Buffer wasn't dirty */
5050 if ((bp->b_flags & B_DELWRI) == 0) {
5059 * Wait for pending output on a vnode to complete.
5060 * Must be called with vnode locked.
5063 drain_output(struct vnode *vp, int islocked)
5068 while (bio_track_active(&vp->v_track_write)) {
5070 bio_track_wait(&vp->v_track_write, 0, 0);
5078 * Called whenever a buffer that is being invalidated or reallocated
5079 * contains dependencies. This should only happen if an I/O error has
5080 * occurred. The routine is called with the buffer locked.
5082 * bioops callback - hold io_token
5085 softdep_deallocate_dependencies(struct buf *bp)
5087 /* nothing to do, mp lock not needed */
5088 if ((bp->b_flags & B_ERROR) == 0)
5089 panic("softdep_deallocate_dependencies: dangling deps");
5090 softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntfromname, bp->b_error);
5091 panic("softdep_deallocate_dependencies: unrecovered I/O error");
5095 * Function to handle asynchronous write errors in the filesystem.
5098 softdep_error(char *func, int error)
5101 /* XXX should do something better! */
5102 kprintf("%s: got error %d while accessing filesystem\n", func, error);