2 * Copyright 1998, 2000 Marshall Kirk McKusick. All Rights Reserved.
4 * The soft updates code is derived from the appendix of a University
5 * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
6 * "Soft Updates: A Solution to the Metadata Update Problem in File
7 * Systems", CSE-TR-254-95, August 1995).
9 * Further information about soft updates can be obtained from:
11 * Marshall Kirk McKusick http://www.mckusick.com/softdep/
12 * 1614 Oxford Street mckusick@mckusick.com
13 * Berkeley, CA 94709-1608 +1-510-843-9542
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
26 * THIS SOFTWARE IS PROVIDED BY MARSHALL KIRK MCKUSICK ``AS IS'' AND ANY
27 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
28 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
29 * DISCLAIMED. IN NO EVENT SHALL MARSHALL KIRK MCKUSICK BE LIABLE FOR
30 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * from: @(#)ffs_softdep.c 9.59 (McKusick) 6/21/00
39 * $FreeBSD: src/sys/ufs/ffs/ffs_softdep.c,v 1.57.2.11 2002/02/05 18:46:53 dillon Exp $
43 * For now we want the safety net that the DIAGNOSTIC and DEBUG flags provide.
52 #include <sys/param.h>
53 #include <sys/kernel.h>
54 #include <sys/systm.h>
56 #include <sys/malloc.h>
57 #include <sys/mount.h>
59 #include <sys/syslog.h>
60 #include <sys/vnode.h>
62 #include <machine/inttypes.h>
69 #include "ffs_extern.h"
70 #include "ufs_extern.h"
73 #include <sys/thread2.h>
77 * These definitions need to be adapted to the system to which
78 * this file is being ported.
81 * malloc types defined for the softdep system.
83 MALLOC_DEFINE(M_PAGEDEP, "pagedep","File page dependencies");
84 MALLOC_DEFINE(M_INODEDEP, "inodedep","Inode dependencies");
85 MALLOC_DEFINE(M_NEWBLK, "newblk","New block allocation");
86 MALLOC_DEFINE(M_BMSAFEMAP, "bmsafemap","Block or frag allocated from cyl group map");
87 MALLOC_DEFINE(M_ALLOCDIRECT, "allocdirect","Block or frag dependency for an inode");
88 MALLOC_DEFINE(M_INDIRDEP, "indirdep","Indirect block dependencies");
89 MALLOC_DEFINE(M_ALLOCINDIR, "allocindir","Block dependency for an indirect block");
90 MALLOC_DEFINE(M_FREEFRAG, "freefrag","Previously used frag for an inode");
91 MALLOC_DEFINE(M_FREEBLKS, "freeblks","Blocks freed from an inode");
92 MALLOC_DEFINE(M_FREEFILE, "freefile","Inode deallocated");
93 MALLOC_DEFINE(M_DIRADD, "diradd","New directory entry");
94 MALLOC_DEFINE(M_MKDIR, "mkdir","New directory");
95 MALLOC_DEFINE(M_DIRREM, "dirrem","Directory entry deleted");
97 #define M_SOFTDEP_FLAGS (M_WAITOK | M_USE_RESERVE)
102 #define D_BMSAFEMAP 3
103 #define D_ALLOCDIRECT 4
105 #define D_ALLOCINDIR 6
112 #define D_LAST D_DIRREM
115 * translate from workitem type to memory type
116 * MUST match the defines above, such that memtype[D_XXX] == M_XXX
118 static struct malloc_type *memtype[] = {
134 #define DtoM(type) (memtype[type])
137 * Names of malloc types.
139 #define TYPENAME(type) \
140 ((unsigned)(type) < D_LAST ? memtype[type]->ks_shortdesc : "???")
142 * End system adaptaion definitions.
146 * Internal function prototypes.
148 static void softdep_error(char *, int);
149 static void drain_output(struct vnode *, int);
150 static int getdirtybuf(struct buf **, int);
151 static void clear_remove(struct thread *);
152 static void clear_inodedeps(struct thread *);
153 static int flush_pagedep_deps(struct vnode *, struct mount *,
155 static int flush_inodedep_deps(struct fs *, ino_t);
156 static int handle_written_filepage(struct pagedep *, struct buf *);
157 static void diradd_inode_written(struct diradd *, struct inodedep *);
158 static int handle_written_inodeblock(struct inodedep *, struct buf *);
159 static void handle_allocdirect_partdone(struct allocdirect *);
160 static void handle_allocindir_partdone(struct allocindir *);
161 static void initiate_write_filepage(struct pagedep *, struct buf *);
162 static void handle_written_mkdir(struct mkdir *, int);
163 static void initiate_write_inodeblock(struct inodedep *, struct buf *);
164 static void handle_workitem_freefile(struct freefile *);
165 static void handle_workitem_remove(struct dirrem *);
166 static struct dirrem *newdirrem(struct buf *, struct inode *,
167 struct inode *, int, struct dirrem **);
168 static void free_diradd(struct diradd *);
169 static void free_allocindir(struct allocindir *, struct inodedep *);
170 static int indir_trunc (struct inode *, off_t, int, ufs_lbn_t, long *);
171 static void deallocate_dependencies(struct buf *, struct inodedep *);
172 static void free_allocdirect(struct allocdirectlst *,
173 struct allocdirect *, int);
174 static int check_inode_unwritten(struct inodedep *);
175 static int free_inodedep(struct inodedep *);
176 static void handle_workitem_freeblocks(struct freeblks *);
177 static void merge_inode_lists(struct inodedep *);
178 static void setup_allocindir_phase2(struct buf *, struct inode *,
179 struct allocindir *);
180 static struct allocindir *newallocindir(struct inode *, int, ufs_daddr_t,
182 static void handle_workitem_freefrag(struct freefrag *);
183 static struct freefrag *newfreefrag(struct inode *, ufs_daddr_t, long);
184 static void allocdirect_merge(struct allocdirectlst *,
185 struct allocdirect *, struct allocdirect *);
186 static struct bmsafemap *bmsafemap_lookup(struct buf *);
187 static int newblk_lookup(struct fs *, ufs_daddr_t, int,
189 static int inodedep_lookup(struct fs *, ino_t, int, struct inodedep **);
190 static int pagedep_lookup(struct inode *, ufs_lbn_t, int,
192 static int request_cleanup(int, int);
193 static int process_worklist_item(struct mount *, int);
194 static void add_to_worklist(struct worklist *);
197 * Exported softdep operations.
199 static void softdep_disk_io_initiation(struct buf *);
200 static void softdep_disk_write_complete(struct buf *);
201 static void softdep_deallocate_dependencies(struct buf *);
202 static int softdep_fsync(struct vnode *);
203 static int softdep_process_worklist(struct mount *);
204 static void softdep_move_dependencies(struct buf *, struct buf *);
205 static int softdep_count_dependencies(struct buf *bp, int);
206 static int softdep_checkread(struct buf *bp);
207 static int softdep_checkwrite(struct buf *bp);
209 static struct bio_ops softdep_bioops = {
210 .io_start = softdep_disk_io_initiation,
211 .io_complete = softdep_disk_write_complete,
212 .io_deallocate = softdep_deallocate_dependencies,
213 .io_fsync = softdep_fsync,
214 .io_sync = softdep_process_worklist,
215 .io_movedeps = softdep_move_dependencies,
216 .io_countdeps = softdep_count_dependencies,
217 .io_checkread = softdep_checkread,
218 .io_checkwrite = softdep_checkwrite
222 * Locking primitives.
224 static void acquire_lock(struct lock *);
225 static void free_lock(struct lock *);
227 static int lock_held(struct lock *);
230 static struct lock lk;
232 #define ACQUIRE_LOCK(lkp) acquire_lock(lkp)
233 #define FREE_LOCK(lkp) free_lock(lkp)
236 acquire_lock(struct lock *lkp)
238 lockmgr(lkp, LK_EXCLUSIVE);
242 free_lock(struct lock *lkp)
244 lockmgr(lkp, LK_RELEASE);
249 lock_held(struct lock *lkp)
251 return lockcountnb(lkp);
256 * Place holder for real semaphores.
264 static void sema_init(struct sema *, char *, int);
265 static int sema_get(struct sema *, struct lock *);
266 static void sema_release(struct sema *);
268 #define NOHOLDER ((struct thread *) -1)
271 sema_init(struct sema *semap, char *name, int timo)
273 semap->holder = NOHOLDER;
280 sema_get(struct sema *semap, struct lock *interlock)
282 if (semap->value++ > 0) {
284 lksleep(semap, interlock, 0, semap->name, semap->timo);
286 tsleep(semap, 0, semap->name, semap->timo);
289 semap->holder = curthread;
294 sema_release(struct sema *semap)
296 if (semap->value <= 0 || semap->holder != curthread) {
297 panic("sema_release: not held");
299 if (--semap->value > 0) {
303 semap->holder = NOHOLDER;
307 * Worklist queue management.
308 * These routines require that the lock be held.
310 static void worklist_insert(struct workhead *, struct worklist *);
311 static void worklist_remove(struct worklist *);
312 static void workitem_free(struct worklist *, int);
314 #define WORKLIST_INSERT_BP(bp, item) do { \
315 (bp)->b_ops = &softdep_bioops; \
316 worklist_insert(&(bp)->b_dep, item); \
319 #define WORKLIST_INSERT(head, item) worklist_insert(head, item)
320 #define WORKLIST_REMOVE(item) worklist_remove(item)
321 #define WORKITEM_FREE(item, type) workitem_free((struct worklist *)item, type)
324 worklist_insert(struct workhead *head, struct worklist *item)
326 KKASSERT(lock_held(&lk) > 0);
328 if (item->wk_state & ONWORKLIST) {
329 panic("worklist_insert: already on list");
331 item->wk_state |= ONWORKLIST;
332 LIST_INSERT_HEAD(head, item, wk_list);
336 worklist_remove(struct worklist *item)
339 KKASSERT(lock_held(&lk));
340 if ((item->wk_state & ONWORKLIST) == 0)
341 panic("worklist_remove: not on list");
343 item->wk_state &= ~ONWORKLIST;
344 LIST_REMOVE(item, wk_list);
348 workitem_free(struct worklist *item, int type)
351 if (item->wk_state & ONWORKLIST)
352 panic("workitem_free: still on list");
353 if (item->wk_type != type)
354 panic("workitem_free: type mismatch");
356 kfree(item, DtoM(type));
360 * Workitem queue management
362 static struct workhead softdep_workitem_pending;
363 static int num_on_worklist; /* number of worklist items to be processed */
364 static int softdep_worklist_busy; /* 1 => trying to do unmount */
365 static int softdep_worklist_req; /* serialized waiters */
366 static int max_softdeps; /* maximum number of structs before slowdown */
367 static int tickdelay = 2; /* number of ticks to pause during slowdown */
368 static int *stat_countp; /* statistic to count in proc_waiting timeout */
369 static int proc_waiting; /* tracks whether we have a timeout posted */
370 static struct thread *filesys_syncer; /* proc of filesystem syncer process */
371 static int req_clear_inodedeps; /* syncer process flush some inodedeps */
372 #define FLUSH_INODES 1
373 static int req_clear_remove; /* syncer process flush some freeblks */
374 #define FLUSH_REMOVE 2
378 static int stat_worklist_push; /* number of worklist cleanups */
379 static int stat_blk_limit_push; /* number of times block limit neared */
380 static int stat_ino_limit_push; /* number of times inode limit neared */
381 static int stat_blk_limit_hit; /* number of times block slowdown imposed */
382 static int stat_ino_limit_hit; /* number of times inode slowdown imposed */
383 static int stat_sync_limit_hit; /* number of synchronous slowdowns imposed */
384 static int stat_indir_blk_ptrs; /* bufs redirtied as indir ptrs not written */
385 static int stat_inode_bitmap; /* bufs redirtied as inode bitmap not written */
386 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
387 static int stat_dir_entry; /* bufs redirtied as dir entry cannot write */
390 #include <sys/sysctl.h>
391 SYSCTL_INT(_debug, OID_AUTO, max_softdeps, CTLFLAG_RW, &max_softdeps, 0,
392 "Maximum soft dependencies before slowdown occurs");
393 SYSCTL_INT(_debug, OID_AUTO, tickdelay, CTLFLAG_RW, &tickdelay, 0,
394 "Ticks to delay before allocating during slowdown");
395 SYSCTL_INT(_debug, OID_AUTO, worklist_push, CTLFLAG_RW, &stat_worklist_push, 0,
396 "Number of worklist cleanups");
397 SYSCTL_INT(_debug, OID_AUTO, blk_limit_push, CTLFLAG_RW, &stat_blk_limit_push, 0,
398 "Number of times block limit neared");
399 SYSCTL_INT(_debug, OID_AUTO, ino_limit_push, CTLFLAG_RW, &stat_ino_limit_push, 0,
400 "Number of times inode limit neared");
401 SYSCTL_INT(_debug, OID_AUTO, blk_limit_hit, CTLFLAG_RW, &stat_blk_limit_hit, 0,
402 "Number of times block slowdown imposed");
403 SYSCTL_INT(_debug, OID_AUTO, ino_limit_hit, CTLFLAG_RW, &stat_ino_limit_hit, 0,
404 "Number of times inode slowdown imposed ");
405 SYSCTL_INT(_debug, OID_AUTO, sync_limit_hit, CTLFLAG_RW, &stat_sync_limit_hit, 0,
406 "Number of synchronous slowdowns imposed");
407 SYSCTL_INT(_debug, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW, &stat_indir_blk_ptrs, 0,
408 "Bufs redirtied as indir ptrs not written");
409 SYSCTL_INT(_debug, OID_AUTO, inode_bitmap, CTLFLAG_RW, &stat_inode_bitmap, 0,
410 "Bufs redirtied as inode bitmap not written");
411 SYSCTL_INT(_debug, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW, &stat_direct_blk_ptrs, 0,
412 "Bufs redirtied as direct ptrs not written");
413 SYSCTL_INT(_debug, OID_AUTO, dir_entry, CTLFLAG_RW, &stat_dir_entry, 0,
414 "Bufs redirtied as dir entry cannot write");
418 * Add an item to the end of the work queue.
419 * This routine requires that the lock be held.
420 * This is the only routine that adds items to the list.
421 * The following routine is the only one that removes items
422 * and does so in order from first to last.
425 add_to_worklist(struct worklist *wk)
427 static struct worklist *worklist_tail;
429 if (wk->wk_state & ONWORKLIST) {
430 panic("add_to_worklist: already on list");
432 wk->wk_state |= ONWORKLIST;
433 if (LIST_FIRST(&softdep_workitem_pending) == NULL)
434 LIST_INSERT_HEAD(&softdep_workitem_pending, wk, wk_list);
436 LIST_INSERT_AFTER(worklist_tail, wk, wk_list);
438 num_on_worklist += 1;
442 * Process that runs once per second to handle items in the background queue.
444 * Note that we ensure that everything is done in the order in which they
445 * appear in the queue. The code below depends on this property to ensure
446 * that blocks of a file are freed before the inode itself is freed. This
447 * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
448 * until all the old ones have been purged from the dependency lists.
450 * bioops callback - hold io_token
453 softdep_process_worklist(struct mount *matchmnt)
455 thread_t td = curthread;
456 int matchcnt, loopcount;
462 * Record the process identifier of our caller so that we can give
463 * this process preferential treatment in request_cleanup below.
469 * There is no danger of having multiple processes run this
470 * code, but we have to single-thread it when softdep_flushfiles()
471 * is in operation to get an accurate count of the number of items
472 * related to its mount point that are in the list.
474 if (matchmnt == NULL) {
475 if (softdep_worklist_busy < 0) {
479 softdep_worklist_busy += 1;
483 * If requested, try removing inode or removal dependencies.
485 if (req_clear_inodedeps) {
487 req_clear_inodedeps -= 1;
488 wakeup_one(&proc_waiting);
490 if (req_clear_remove) {
492 req_clear_remove -= 1;
493 wakeup_one(&proc_waiting);
496 starttime = time_second;
497 while (num_on_worklist > 0) {
498 matchcnt += process_worklist_item(matchmnt, 0);
501 * If a umount operation wants to run the worklist
504 if (softdep_worklist_req && matchmnt == NULL) {
510 * If requested, try removing inode or removal dependencies.
512 if (req_clear_inodedeps) {
514 req_clear_inodedeps -= 1;
515 wakeup_one(&proc_waiting);
517 if (req_clear_remove) {
519 req_clear_remove -= 1;
520 wakeup_one(&proc_waiting);
523 * We do not generally want to stop for buffer space, but if
524 * we are really being a buffer hog, we will stop and wait.
526 if (loopcount++ % 128 == 0) {
533 * Never allow processing to run for more than one
534 * second. Otherwise the other syncer tasks may get
535 * excessively backlogged.
537 if (starttime != time_second && matchmnt == NULL) {
542 if (matchmnt == NULL) {
543 --softdep_worklist_busy;
544 if (softdep_worklist_req && softdep_worklist_busy == 0)
545 wakeup(&softdep_worklist_req);
553 * Process one item on the worklist.
556 process_worklist_item(struct mount *matchmnt, int flags)
559 struct dirrem *dirrem;
565 if (matchmnt != NULL)
566 matchfs = VFSTOUFS(matchmnt)->um_fs;
569 * Normally we just process each item on the worklist in order.
570 * However, if we are in a situation where we cannot lock any
571 * inodes, we have to skip over any dirrem requests whose
572 * vnodes are resident and locked.
574 LIST_FOREACH(wk, &softdep_workitem_pending, wk_list) {
575 if ((flags & LK_NOWAIT) == 0 || wk->wk_type != D_DIRREM)
577 dirrem = WK_DIRREM(wk);
578 vp = ufs_ihashlookup(VFSTOUFS(dirrem->dm_mnt)->um_dev,
580 if (vp == NULL || !vn_islocked(vp))
587 num_on_worklist -= 1;
589 switch (wk->wk_type) {
591 /* removal of a directory entry */
592 if (WK_DIRREM(wk)->dm_mnt == matchmnt)
594 handle_workitem_remove(WK_DIRREM(wk));
598 /* releasing blocks and/or fragments from a file */
599 if (WK_FREEBLKS(wk)->fb_fs == matchfs)
601 handle_workitem_freeblocks(WK_FREEBLKS(wk));
605 /* releasing a fragment when replaced as a file grows */
606 if (WK_FREEFRAG(wk)->ff_fs == matchfs)
608 handle_workitem_freefrag(WK_FREEFRAG(wk));
612 /* releasing an inode when its link count drops to 0 */
613 if (WK_FREEFILE(wk)->fx_fs == matchfs)
615 handle_workitem_freefile(WK_FREEFILE(wk));
619 panic("%s_process_worklist: Unknown type %s",
620 "softdep", TYPENAME(wk->wk_type));
628 * Move dependencies from one buffer to another.
630 * bioops callback - hold io_token
633 softdep_move_dependencies(struct buf *oldbp, struct buf *newbp)
635 struct worklist *wk, *wktail;
637 if (LIST_FIRST(&newbp->b_dep) != NULL)
638 panic("softdep_move_dependencies: need merge code");
641 while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
642 LIST_REMOVE(wk, wk_list);
644 LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
646 LIST_INSERT_AFTER(wktail, wk, wk_list);
648 newbp->b_ops = &softdep_bioops;
654 * Purge the work list of all items associated with a particular mount point.
657 softdep_flushfiles(struct mount *oldmnt, int flags)
663 * Await our turn to clear out the queue, then serialize access.
666 while (softdep_worklist_busy != 0) {
667 softdep_worklist_req += 1;
668 lksleep(&softdep_worklist_req, &lk, 0, "softflush", 0);
669 softdep_worklist_req -= 1;
671 softdep_worklist_busy = -1;
674 if ((error = ffs_flushfiles(oldmnt, flags)) != 0) {
675 softdep_worklist_busy = 0;
676 if (softdep_worklist_req)
677 wakeup(&softdep_worklist_req);
681 * Alternately flush the block device associated with the mount
682 * point and process any dependencies that the flushing
683 * creates. In theory, this loop can happen at most twice,
684 * but we give it a few extra just to be sure.
686 devvp = VFSTOUFS(oldmnt)->um_devvp;
687 for (loopcnt = 10; loopcnt > 0; ) {
688 if (softdep_process_worklist(oldmnt) == 0) {
691 * Do another flush in case any vnodes were brought in
692 * as part of the cleanup operations.
694 if ((error = ffs_flushfiles(oldmnt, flags)) != 0)
697 * If we still found nothing to do, we are really done.
699 if (softdep_process_worklist(oldmnt) == 0)
702 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
703 error = VOP_FSYNC(devvp, MNT_WAIT, 0);
709 softdep_worklist_busy = 0;
710 if (softdep_worklist_req)
711 wakeup(&softdep_worklist_req);
715 * If we are unmounting then it is an error to fail. If we
716 * are simply trying to downgrade to read-only, then filesystem
717 * activity can keep us busy forever, so we just fail with EBUSY.
720 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
721 panic("softdep_flushfiles: looping");
730 * There are three types of structures that can be looked up:
731 * 1) pagedep structures identified by mount point, inode number,
733 * 2) inodedep structures identified by mount point and inode number.
734 * 3) newblk structures identified by mount point and
735 * physical block number.
737 * The "pagedep" and "inodedep" dependency structures are hashed
738 * separately from the file blocks and inodes to which they correspond.
739 * This separation helps when the in-memory copy of an inode or
740 * file block must be replaced. It also obviates the need to access
741 * an inode or file page when simply updating (or de-allocating)
742 * dependency structures. Lookup of newblk structures is needed to
743 * find newly allocated blocks when trying to associate them with
744 * their allocdirect or allocindir structure.
746 * The lookup routines optionally create and hash a new instance when
747 * an existing entry is not found.
749 #define DEPALLOC 0x0001 /* allocate structure if lookup fails */
750 #define NODELAY 0x0002 /* cannot do background work */
753 * Structures and routines associated with pagedep caching.
755 LIST_HEAD(pagedep_hashhead, pagedep) *pagedep_hashtbl;
756 u_long pagedep_hash; /* size of hash table - 1 */
757 #define PAGEDEP_HASH(mp, inum, lbn) \
758 (&pagedep_hashtbl[((((register_t)(mp)) >> 13) + (inum) + (lbn)) & \
760 static struct sema pagedep_in_progress;
763 * Helper routine for pagedep_lookup()
767 pagedep_find(struct pagedep_hashhead *pagedephd, ino_t ino, ufs_lbn_t lbn,
770 struct pagedep *pagedep;
772 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
773 if (ino == pagedep->pd_ino &&
774 lbn == pagedep->pd_lbn &&
775 mp == pagedep->pd_mnt) {
783 * Look up a pagedep. Return 1 if found, 0 if not found.
784 * If not found, allocate if DEPALLOC flag is passed.
785 * Found or allocated entry is returned in pagedeppp.
786 * This routine must be called with splbio interrupts blocked.
789 pagedep_lookup(struct inode *ip, ufs_lbn_t lbn, int flags,
790 struct pagedep **pagedeppp)
792 struct pagedep *pagedep;
793 struct pagedep_hashhead *pagedephd;
797 KKASSERT(lock_held(&lk) > 0);
799 mp = ITOV(ip)->v_mount;
800 pagedephd = PAGEDEP_HASH(mp, ip->i_number, lbn);
802 *pagedeppp = pagedep_find(pagedephd, ip->i_number, lbn, mp);
805 if ((flags & DEPALLOC) == 0)
807 if (sema_get(&pagedep_in_progress, &lk) == 0)
811 pagedep = kmalloc(sizeof(struct pagedep), M_PAGEDEP,
812 M_SOFTDEP_FLAGS | M_ZERO);
814 if (pagedep_find(pagedephd, ip->i_number, lbn, mp)) {
815 kprintf("pagedep_lookup: blocking race avoided\n");
816 sema_release(&pagedep_in_progress);
817 kfree(pagedep, M_PAGEDEP);
821 pagedep->pd_list.wk_type = D_PAGEDEP;
822 pagedep->pd_mnt = mp;
823 pagedep->pd_ino = ip->i_number;
824 pagedep->pd_lbn = lbn;
825 LIST_INIT(&pagedep->pd_dirremhd);
826 LIST_INIT(&pagedep->pd_pendinghd);
827 for (i = 0; i < DAHASHSZ; i++)
828 LIST_INIT(&pagedep->pd_diraddhd[i]);
829 LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
830 sema_release(&pagedep_in_progress);
831 *pagedeppp = pagedep;
836 * Structures and routines associated with inodedep caching.
838 LIST_HEAD(inodedep_hashhead, inodedep) *inodedep_hashtbl;
839 static u_long inodedep_hash; /* size of hash table - 1 */
840 static long num_inodedep; /* number of inodedep allocated */
841 #define INODEDEP_HASH(fs, inum) \
842 (&inodedep_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & inodedep_hash])
843 static struct sema inodedep_in_progress;
846 * Helper routine for inodedep_lookup()
850 inodedep_find(struct inodedep_hashhead *inodedephd, struct fs *fs, ino_t inum)
852 struct inodedep *inodedep;
854 LIST_FOREACH(inodedep, inodedephd, id_hash) {
855 if (inum == inodedep->id_ino && fs == inodedep->id_fs)
862 * Look up a inodedep. Return 1 if found, 0 if not found.
863 * If not found, allocate if DEPALLOC flag is passed.
864 * Found or allocated entry is returned in inodedeppp.
865 * This routine must be called with splbio interrupts blocked.
868 inodedep_lookup(struct fs *fs, ino_t inum, int flags,
869 struct inodedep **inodedeppp)
871 struct inodedep *inodedep;
872 struct inodedep_hashhead *inodedephd;
875 KKASSERT(lock_held(&lk) > 0);
878 inodedephd = INODEDEP_HASH(fs, inum);
880 *inodedeppp = inodedep_find(inodedephd, fs, inum);
883 if ((flags & DEPALLOC) == 0)
886 * If we are over our limit, try to improve the situation.
888 if (num_inodedep > max_softdeps && firsttry &&
889 speedup_syncer() == 0 && (flags & NODELAY) == 0 &&
890 request_cleanup(FLUSH_INODES, 1)) {
894 if (sema_get(&inodedep_in_progress, &lk) == 0)
898 inodedep = kmalloc(sizeof(struct inodedep), M_INODEDEP,
899 M_SOFTDEP_FLAGS | M_ZERO);
901 if (inodedep_find(inodedephd, fs, inum)) {
902 kprintf("inodedep_lookup: blocking race avoided\n");
903 sema_release(&inodedep_in_progress);
904 kfree(inodedep, M_INODEDEP);
907 inodedep->id_list.wk_type = D_INODEDEP;
908 inodedep->id_fs = fs;
909 inodedep->id_ino = inum;
910 inodedep->id_state = ALLCOMPLETE;
911 inodedep->id_nlinkdelta = 0;
912 inodedep->id_savedino = NULL;
913 inodedep->id_savedsize = -1;
914 inodedep->id_buf = NULL;
915 LIST_INIT(&inodedep->id_pendinghd);
916 LIST_INIT(&inodedep->id_inowait);
917 LIST_INIT(&inodedep->id_bufwait);
918 TAILQ_INIT(&inodedep->id_inoupdt);
919 TAILQ_INIT(&inodedep->id_newinoupdt);
921 LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
922 sema_release(&inodedep_in_progress);
923 *inodedeppp = inodedep;
928 * Structures and routines associated with newblk caching.
930 LIST_HEAD(newblk_hashhead, newblk) *newblk_hashtbl;
931 u_long newblk_hash; /* size of hash table - 1 */
932 #define NEWBLK_HASH(fs, inum) \
933 (&newblk_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & newblk_hash])
934 static struct sema newblk_in_progress;
937 * Helper routine for newblk_lookup()
941 newblk_find(struct newblk_hashhead *newblkhd, struct fs *fs,
942 ufs_daddr_t newblkno)
944 struct newblk *newblk;
946 LIST_FOREACH(newblk, newblkhd, nb_hash) {
947 if (newblkno == newblk->nb_newblkno && fs == newblk->nb_fs)
954 * Look up a newblk. Return 1 if found, 0 if not found.
955 * If not found, allocate if DEPALLOC flag is passed.
956 * Found or allocated entry is returned in newblkpp.
959 newblk_lookup(struct fs *fs, ufs_daddr_t newblkno, int flags,
960 struct newblk **newblkpp)
962 struct newblk *newblk;
963 struct newblk_hashhead *newblkhd;
965 newblkhd = NEWBLK_HASH(fs, newblkno);
967 *newblkpp = newblk_find(newblkhd, fs, newblkno);
970 if ((flags & DEPALLOC) == 0)
972 if (sema_get(&newblk_in_progress, NULL) == 0)
975 newblk = kmalloc(sizeof(struct newblk), M_NEWBLK,
976 M_SOFTDEP_FLAGS | M_ZERO);
978 if (newblk_find(newblkhd, fs, newblkno)) {
979 kprintf("newblk_lookup: blocking race avoided\n");
980 sema_release(&pagedep_in_progress);
981 kfree(newblk, M_NEWBLK);
984 newblk->nb_state = 0;
986 newblk->nb_newblkno = newblkno;
987 LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
988 sema_release(&newblk_in_progress);
994 * Executed during filesystem system initialization before
995 * mounting any filesystems.
998 softdep_initialize(void)
1000 LIST_INIT(&mkdirlisthd);
1001 LIST_INIT(&softdep_workitem_pending);
1002 max_softdeps = min(desiredvnodes * 8,
1003 M_INODEDEP->ks_limit / (2 * sizeof(struct inodedep)));
1004 pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
1006 lockinit(&lk, "ffs_softdep", 0, LK_CANRECURSE);
1007 sema_init(&pagedep_in_progress, "pagedep", 0);
1008 inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP, &inodedep_hash);
1009 sema_init(&inodedep_in_progress, "inodedep", 0);
1010 newblk_hashtbl = hashinit(64, M_NEWBLK, &newblk_hash);
1011 sema_init(&newblk_in_progress, "newblk", 0);
1012 add_bio_ops(&softdep_bioops);
1016 * Called at mount time to notify the dependency code that a
1017 * filesystem wishes to use it.
1020 softdep_mount(struct vnode *devvp, struct mount *mp, struct fs *fs)
1022 struct csum cstotal;
1027 mp->mnt_flag &= ~MNT_ASYNC;
1028 mp->mnt_flag |= MNT_SOFTDEP;
1029 mp->mnt_bioops = &softdep_bioops;
1031 * When doing soft updates, the counters in the
1032 * superblock may have gotten out of sync, so we have
1033 * to scan the cylinder groups and recalculate them.
1035 if (fs->fs_clean != 0)
1037 bzero(&cstotal, sizeof cstotal);
1038 for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
1039 if ((error = bread(devvp, fsbtodoff(fs, cgtod(fs, cyl)),
1040 fs->fs_cgsize, &bp)) != 0) {
1044 cgp = (struct cg *)bp->b_data;
1045 cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
1046 cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
1047 cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
1048 cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
1049 fs->fs_cs(fs, cyl) = cgp->cg_cs;
1053 if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
1054 kprintf("ffs_mountfs: superblock updated for soft updates\n");
1056 bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
1061 * Protecting the freemaps (or bitmaps).
1063 * To eliminate the need to execute fsck before mounting a filesystem
1064 * after a power failure, one must (conservatively) guarantee that the
1065 * on-disk copy of the bitmaps never indicate that a live inode or block is
1066 * free. So, when a block or inode is allocated, the bitmap should be
1067 * updated (on disk) before any new pointers. When a block or inode is
1068 * freed, the bitmap should not be updated until all pointers have been
1069 * reset. The latter dependency is handled by the delayed de-allocation
1070 * approach described below for block and inode de-allocation. The former
1071 * dependency is handled by calling the following procedure when a block or
1072 * inode is allocated. When an inode is allocated an "inodedep" is created
1073 * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
1074 * Each "inodedep" is also inserted into the hash indexing structure so
1075 * that any additional link additions can be made dependent on the inode
1078 * The ufs filesystem maintains a number of free block counts (e.g., per
1079 * cylinder group, per cylinder and per <cylinder, rotational position> pair)
1080 * in addition to the bitmaps. These counts are used to improve efficiency
1081 * during allocation and therefore must be consistent with the bitmaps.
1082 * There is no convenient way to guarantee post-crash consistency of these
1083 * counts with simple update ordering, for two main reasons: (1) The counts
1084 * and bitmaps for a single cylinder group block are not in the same disk
1085 * sector. If a disk write is interrupted (e.g., by power failure), one may
1086 * be written and the other not. (2) Some of the counts are located in the
1087 * superblock rather than the cylinder group block. So, we focus our soft
1088 * updates implementation on protecting the bitmaps. When mounting a
1089 * filesystem, we recompute the auxiliary counts from the bitmaps.
1093 * Called just after updating the cylinder group block to allocate an inode.
1096 * bp: buffer for cylgroup block with inode map
1097 * ip: inode related to allocation
1098 * newinum: new inode number being allocated
1101 softdep_setup_inomapdep(struct buf *bp, struct inode *ip, ino_t newinum)
1103 struct inodedep *inodedep;
1104 struct bmsafemap *bmsafemap;
1107 * Create a dependency for the newly allocated inode.
1108 * Panic if it already exists as something is seriously wrong.
1109 * Otherwise add it to the dependency list for the buffer holding
1110 * the cylinder group map from which it was allocated.
1113 if ((inodedep_lookup(ip->i_fs, newinum, DEPALLOC|NODELAY, &inodedep))) {
1114 panic("softdep_setup_inomapdep: found inode");
1116 inodedep->id_buf = bp;
1117 inodedep->id_state &= ~DEPCOMPLETE;
1118 bmsafemap = bmsafemap_lookup(bp);
1119 LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
1124 * Called just after updating the cylinder group block to
1125 * allocate block or fragment.
1128 * bp: buffer for cylgroup block with block map
1129 * fs: filesystem doing allocation
1130 * newblkno: number of newly allocated block
1133 softdep_setup_blkmapdep(struct buf *bp, struct fs *fs,
1134 ufs_daddr_t newblkno)
1136 struct newblk *newblk;
1137 struct bmsafemap *bmsafemap;
1140 * Create a dependency for the newly allocated block.
1141 * Add it to the dependency list for the buffer holding
1142 * the cylinder group map from which it was allocated.
1144 if (newblk_lookup(fs, newblkno, DEPALLOC, &newblk) != 0)
1145 panic("softdep_setup_blkmapdep: found block");
1147 newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(bp);
1148 LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
1153 * Find the bmsafemap associated with a cylinder group buffer.
1154 * If none exists, create one. The buffer must be locked when
1155 * this routine is called and this routine must be called with
1156 * splbio interrupts blocked.
1158 static struct bmsafemap *
1159 bmsafemap_lookup(struct buf *bp)
1161 struct bmsafemap *bmsafemap;
1162 struct worklist *wk;
1164 KKASSERT(lock_held(&lk) > 0);
1166 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
1167 if (wk->wk_type == D_BMSAFEMAP)
1168 return (WK_BMSAFEMAP(wk));
1171 bmsafemap = kmalloc(sizeof(struct bmsafemap), M_BMSAFEMAP,
1173 bmsafemap->sm_list.wk_type = D_BMSAFEMAP;
1174 bmsafemap->sm_list.wk_state = 0;
1175 bmsafemap->sm_buf = bp;
1176 LIST_INIT(&bmsafemap->sm_allocdirecthd);
1177 LIST_INIT(&bmsafemap->sm_allocindirhd);
1178 LIST_INIT(&bmsafemap->sm_inodedephd);
1179 LIST_INIT(&bmsafemap->sm_newblkhd);
1181 WORKLIST_INSERT_BP(bp, &bmsafemap->sm_list);
1186 * Direct block allocation dependencies.
1188 * When a new block is allocated, the corresponding disk locations must be
1189 * initialized (with zeros or new data) before the on-disk inode points to
1190 * them. Also, the freemap from which the block was allocated must be
1191 * updated (on disk) before the inode's pointer. These two dependencies are
1192 * independent of each other and are needed for all file blocks and indirect
1193 * blocks that are pointed to directly by the inode. Just before the
1194 * "in-core" version of the inode is updated with a newly allocated block
1195 * number, a procedure (below) is called to setup allocation dependency
1196 * structures. These structures are removed when the corresponding
1197 * dependencies are satisfied or when the block allocation becomes obsolete
1198 * (i.e., the file is deleted, the block is de-allocated, or the block is a
1199 * fragment that gets upgraded). All of these cases are handled in
1200 * procedures described later.
1202 * When a file extension causes a fragment to be upgraded, either to a larger
1203 * fragment or to a full block, the on-disk location may change (if the
1204 * previous fragment could not simply be extended). In this case, the old
1205 * fragment must be de-allocated, but not until after the inode's pointer has
1206 * been updated. In most cases, this is handled by later procedures, which
1207 * will construct a "freefrag" structure to be added to the workitem queue
1208 * when the inode update is complete (or obsolete). The main exception to
1209 * this is when an allocation occurs while a pending allocation dependency
1210 * (for the same block pointer) remains. This case is handled in the main
1211 * allocation dependency setup procedure by immediately freeing the
1212 * unreferenced fragments.
1215 * ip: inode to which block is being added
1216 * lbn: block pointer within inode
1217 * newblkno: disk block number being added
1218 * oldblkno: previous block number, 0 unless frag
1219 * newsize: size of new block
1220 * oldsize: size of new block
1221 * bp: bp for allocated block
1224 softdep_setup_allocdirect(struct inode *ip, ufs_lbn_t lbn, ufs_daddr_t newblkno,
1225 ufs_daddr_t oldblkno, long newsize, long oldsize,
1228 struct allocdirect *adp, *oldadp;
1229 struct allocdirectlst *adphead;
1230 struct bmsafemap *bmsafemap;
1231 struct inodedep *inodedep;
1232 struct pagedep *pagedep;
1233 struct newblk *newblk;
1235 adp = kmalloc(sizeof(struct allocdirect), M_ALLOCDIRECT,
1236 M_SOFTDEP_FLAGS | M_ZERO);
1237 adp->ad_list.wk_type = D_ALLOCDIRECT;
1239 adp->ad_newblkno = newblkno;
1240 adp->ad_oldblkno = oldblkno;
1241 adp->ad_newsize = newsize;
1242 adp->ad_oldsize = oldsize;
1243 adp->ad_state = ATTACHED;
1244 if (newblkno == oldblkno)
1245 adp->ad_freefrag = NULL;
1247 adp->ad_freefrag = newfreefrag(ip, oldblkno, oldsize);
1249 if (newblk_lookup(ip->i_fs, newblkno, 0, &newblk) == 0)
1250 panic("softdep_setup_allocdirect: lost block");
1253 inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC | NODELAY, &inodedep);
1254 adp->ad_inodedep = inodedep;
1256 if (newblk->nb_state == DEPCOMPLETE) {
1257 adp->ad_state |= DEPCOMPLETE;
1260 bmsafemap = newblk->nb_bmsafemap;
1261 adp->ad_buf = bmsafemap->sm_buf;
1262 LIST_REMOVE(newblk, nb_deps);
1263 LIST_INSERT_HEAD(&bmsafemap->sm_allocdirecthd, adp, ad_deps);
1265 LIST_REMOVE(newblk, nb_hash);
1266 kfree(newblk, M_NEWBLK);
1268 WORKLIST_INSERT_BP(bp, &adp->ad_list);
1269 if (lbn >= NDADDR) {
1270 /* allocating an indirect block */
1271 if (oldblkno != 0) {
1272 panic("softdep_setup_allocdirect: non-zero indir");
1276 * Allocating a direct block.
1278 * If we are allocating a directory block, then we must
1279 * allocate an associated pagedep to track additions and
1282 if ((ip->i_mode & IFMT) == IFDIR &&
1283 pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0) {
1284 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
1288 * The list of allocdirects must be kept in sorted and ascending
1289 * order so that the rollback routines can quickly determine the
1290 * first uncommitted block (the size of the file stored on disk
1291 * ends at the end of the lowest committed fragment, or if there
1292 * are no fragments, at the end of the highest committed block).
1293 * Since files generally grow, the typical case is that the new
1294 * block is to be added at the end of the list. We speed this
1295 * special case by checking against the last allocdirect in the
1296 * list before laboriously traversing the list looking for the
1299 adphead = &inodedep->id_newinoupdt;
1300 oldadp = TAILQ_LAST(adphead, allocdirectlst);
1301 if (oldadp == NULL || oldadp->ad_lbn <= lbn) {
1302 /* insert at end of list */
1303 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
1304 if (oldadp != NULL && oldadp->ad_lbn == lbn)
1305 allocdirect_merge(adphead, adp, oldadp);
1309 TAILQ_FOREACH(oldadp, adphead, ad_next) {
1310 if (oldadp->ad_lbn >= lbn)
1313 if (oldadp == NULL) {
1314 panic("softdep_setup_allocdirect: lost entry");
1316 /* insert in middle of list */
1317 TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
1318 if (oldadp->ad_lbn == lbn)
1319 allocdirect_merge(adphead, adp, oldadp);
1324 * Replace an old allocdirect dependency with a newer one.
1325 * This routine must be called with splbio interrupts blocked.
1328 * adphead: head of list holding allocdirects
1329 * newadp: allocdirect being added
1330 * oldadp: existing allocdirect being checked
1333 allocdirect_merge(struct allocdirectlst *adphead,
1334 struct allocdirect *newadp,
1335 struct allocdirect *oldadp)
1337 struct freefrag *freefrag;
1339 KKASSERT(lock_held(&lk) > 0);
1341 if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
1342 newadp->ad_oldsize != oldadp->ad_newsize ||
1343 newadp->ad_lbn >= NDADDR) {
1344 panic("allocdirect_check: old %d != new %d || lbn %ld >= %d",
1345 newadp->ad_oldblkno, oldadp->ad_newblkno, newadp->ad_lbn,
1348 newadp->ad_oldblkno = oldadp->ad_oldblkno;
1349 newadp->ad_oldsize = oldadp->ad_oldsize;
1351 * If the old dependency had a fragment to free or had never
1352 * previously had a block allocated, then the new dependency
1353 * can immediately post its freefrag and adopt the old freefrag.
1354 * This action is done by swapping the freefrag dependencies.
1355 * The new dependency gains the old one's freefrag, and the
1356 * old one gets the new one and then immediately puts it on
1357 * the worklist when it is freed by free_allocdirect. It is
1358 * not possible to do this swap when the old dependency had a
1359 * non-zero size but no previous fragment to free. This condition
1360 * arises when the new block is an extension of the old block.
1361 * Here, the first part of the fragment allocated to the new
1362 * dependency is part of the block currently claimed on disk by
1363 * the old dependency, so cannot legitimately be freed until the
1364 * conditions for the new dependency are fulfilled.
1366 if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
1367 freefrag = newadp->ad_freefrag;
1368 newadp->ad_freefrag = oldadp->ad_freefrag;
1369 oldadp->ad_freefrag = freefrag;
1371 free_allocdirect(adphead, oldadp, 0);
1375 * Allocate a new freefrag structure if needed.
1377 static struct freefrag *
1378 newfreefrag(struct inode *ip, ufs_daddr_t blkno, long size)
1380 struct freefrag *freefrag;
1386 if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
1387 panic("newfreefrag: frag size");
1388 freefrag = kmalloc(sizeof(struct freefrag), M_FREEFRAG,
1390 freefrag->ff_list.wk_type = D_FREEFRAG;
1391 freefrag->ff_state = ip->i_uid & ~ONWORKLIST; /* XXX - used below */
1392 freefrag->ff_inum = ip->i_number;
1393 freefrag->ff_fs = fs;
1394 freefrag->ff_devvp = ip->i_devvp;
1395 freefrag->ff_blkno = blkno;
1396 freefrag->ff_fragsize = size;
1401 * This workitem de-allocates fragments that were replaced during
1402 * file block allocation.
1405 handle_workitem_freefrag(struct freefrag *freefrag)
1409 tip.i_fs = freefrag->ff_fs;
1410 tip.i_devvp = freefrag->ff_devvp;
1411 tip.i_dev = freefrag->ff_devvp->v_rdev;
1412 tip.i_number = freefrag->ff_inum;
1413 tip.i_uid = freefrag->ff_state & ~ONWORKLIST; /* XXX - set above */
1414 ffs_blkfree(&tip, freefrag->ff_blkno, freefrag->ff_fragsize);
1415 kfree(freefrag, M_FREEFRAG);
1419 * Indirect block allocation dependencies.
1421 * The same dependencies that exist for a direct block also exist when
1422 * a new block is allocated and pointed to by an entry in a block of
1423 * indirect pointers. The undo/redo states described above are also
1424 * used here. Because an indirect block contains many pointers that
1425 * may have dependencies, a second copy of the entire in-memory indirect
1426 * block is kept. The buffer cache copy is always completely up-to-date.
1427 * The second copy, which is used only as a source for disk writes,
1428 * contains only the safe pointers (i.e., those that have no remaining
1429 * update dependencies). The second copy is freed when all pointers
1430 * are safe. The cache is not allowed to replace indirect blocks with
1431 * pending update dependencies. If a buffer containing an indirect
1432 * block with dependencies is written, these routines will mark it
1433 * dirty again. It can only be successfully written once all the
1434 * dependencies are removed. The ffs_fsync routine in conjunction with
1435 * softdep_sync_metadata work together to get all the dependencies
1436 * removed so that a file can be successfully written to disk. Three
1437 * procedures are used when setting up indirect block pointer
1438 * dependencies. The division is necessary because of the organization
1439 * of the "balloc" routine and because of the distinction between file
1440 * pages and file metadata blocks.
1444 * Allocate a new allocindir structure.
1447 * ip: inode for file being extended
1448 * ptrno: offset of pointer in indirect block
1449 * newblkno: disk block number being added
1450 * oldblkno: previous block number, 0 if none
1452 static struct allocindir *
1453 newallocindir(struct inode *ip, int ptrno, ufs_daddr_t newblkno,
1454 ufs_daddr_t oldblkno)
1456 struct allocindir *aip;
1458 aip = kmalloc(sizeof(struct allocindir), M_ALLOCINDIR,
1459 M_SOFTDEP_FLAGS | M_ZERO);
1460 aip->ai_list.wk_type = D_ALLOCINDIR;
1461 aip->ai_state = ATTACHED;
1462 aip->ai_offset = ptrno;
1463 aip->ai_newblkno = newblkno;
1464 aip->ai_oldblkno = oldblkno;
1465 aip->ai_freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize);
1470 * Called just before setting an indirect block pointer
1471 * to a newly allocated file page.
1474 * ip: inode for file being extended
1475 * lbn: allocated block number within file
1476 * bp: buffer with indirect blk referencing page
1477 * ptrno: offset of pointer in indirect block
1478 * newblkno: disk block number being added
1479 * oldblkno: previous block number, 0 if none
1480 * nbp: buffer holding allocated page
1483 softdep_setup_allocindir_page(struct inode *ip, ufs_lbn_t lbn,
1484 struct buf *bp, int ptrno,
1485 ufs_daddr_t newblkno, ufs_daddr_t oldblkno,
1488 struct allocindir *aip;
1489 struct pagedep *pagedep;
1491 aip = newallocindir(ip, ptrno, newblkno, oldblkno);
1494 * If we are allocating a directory page, then we must
1495 * allocate an associated pagedep to track additions and
1498 if ((ip->i_mode & IFMT) == IFDIR &&
1499 pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0)
1500 WORKLIST_INSERT_BP(nbp, &pagedep->pd_list);
1501 WORKLIST_INSERT_BP(nbp, &aip->ai_list);
1503 setup_allocindir_phase2(bp, ip, aip);
1507 * Called just before setting an indirect block pointer to a
1508 * newly allocated indirect block.
1510 * nbp: newly allocated indirect block
1511 * ip: inode for file being extended
1512 * bp: indirect block referencing allocated block
1513 * ptrno: offset of pointer in indirect block
1514 * newblkno: disk block number being added
1517 softdep_setup_allocindir_meta(struct buf *nbp, struct inode *ip,
1518 struct buf *bp, int ptrno,
1519 ufs_daddr_t newblkno)
1521 struct allocindir *aip;
1523 aip = newallocindir(ip, ptrno, newblkno, 0);
1525 WORKLIST_INSERT_BP(nbp, &aip->ai_list);
1527 setup_allocindir_phase2(bp, ip, aip);
1531 * Called to finish the allocation of the "aip" allocated
1532 * by one of the two routines above.
1535 * bp: in-memory copy of the indirect block
1536 * ip: inode for file being extended
1537 * aip: allocindir allocated by the above routines
1540 setup_allocindir_phase2(struct buf *bp, struct inode *ip,
1541 struct allocindir *aip)
1543 struct worklist *wk;
1544 struct indirdep *indirdep, *newindirdep;
1545 struct bmsafemap *bmsafemap;
1546 struct allocindir *oldaip;
1547 struct freefrag *freefrag;
1548 struct newblk *newblk;
1550 if (bp->b_loffset >= 0)
1551 panic("setup_allocindir_phase2: not indir blk");
1552 for (indirdep = NULL, newindirdep = NULL; ; ) {
1554 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
1555 if (wk->wk_type != D_INDIRDEP)
1557 indirdep = WK_INDIRDEP(wk);
1560 if (indirdep == NULL && newindirdep) {
1561 indirdep = newindirdep;
1562 WORKLIST_INSERT_BP(bp, &indirdep->ir_list);
1567 if (newblk_lookup(ip->i_fs, aip->ai_newblkno, 0,
1569 panic("setup_allocindir: lost block");
1571 if (newblk->nb_state == DEPCOMPLETE) {
1572 aip->ai_state |= DEPCOMPLETE;
1575 bmsafemap = newblk->nb_bmsafemap;
1576 aip->ai_buf = bmsafemap->sm_buf;
1577 LIST_REMOVE(newblk, nb_deps);
1578 LIST_INSERT_HEAD(&bmsafemap->sm_allocindirhd,
1581 LIST_REMOVE(newblk, nb_hash);
1582 kfree(newblk, M_NEWBLK);
1583 aip->ai_indirdep = indirdep;
1585 * Check to see if there is an existing dependency
1586 * for this block. If there is, merge the old
1587 * dependency into the new one.
1589 if (aip->ai_oldblkno == 0)
1593 LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next)
1594 if (oldaip->ai_offset == aip->ai_offset)
1596 if (oldaip != NULL) {
1597 if (oldaip->ai_newblkno != aip->ai_oldblkno) {
1598 panic("setup_allocindir_phase2: blkno");
1600 aip->ai_oldblkno = oldaip->ai_oldblkno;
1601 freefrag = oldaip->ai_freefrag;
1602 oldaip->ai_freefrag = aip->ai_freefrag;
1603 aip->ai_freefrag = freefrag;
1604 free_allocindir(oldaip, NULL);
1606 LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
1607 ((ufs_daddr_t *)indirdep->ir_savebp->b_data)
1608 [aip->ai_offset] = aip->ai_oldblkno;
1613 * Avoid any possibility of data corruption by
1614 * ensuring that our old version is thrown away.
1616 newindirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
1617 brelse(newindirdep->ir_savebp);
1618 WORKITEM_FREE((caddr_t)newindirdep, D_INDIRDEP);
1622 newindirdep = kmalloc(sizeof(struct indirdep), M_INDIRDEP,
1624 newindirdep->ir_list.wk_type = D_INDIRDEP;
1625 newindirdep->ir_state = ATTACHED;
1626 LIST_INIT(&newindirdep->ir_deplisthd);
1627 LIST_INIT(&newindirdep->ir_donehd);
1628 if (bp->b_bio2.bio_offset == NOOFFSET) {
1629 VOP_BMAP(bp->b_vp, bp->b_bio1.bio_offset,
1630 &bp->b_bio2.bio_offset, NULL, NULL,
1633 KKASSERT(bp->b_bio2.bio_offset != NOOFFSET);
1634 newindirdep->ir_savebp = getblk(ip->i_devvp,
1635 bp->b_bio2.bio_offset,
1636 bp->b_bcount, 0, 0);
1637 BUF_KERNPROC(newindirdep->ir_savebp);
1638 bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
1643 * Block de-allocation dependencies.
1645 * When blocks are de-allocated, the on-disk pointers must be nullified before
1646 * the blocks are made available for use by other files. (The true
1647 * requirement is that old pointers must be nullified before new on-disk
1648 * pointers are set. We chose this slightly more stringent requirement to
1649 * reduce complexity.) Our implementation handles this dependency by updating
1650 * the inode (or indirect block) appropriately but delaying the actual block
1651 * de-allocation (i.e., freemap and free space count manipulation) until
1652 * after the updated versions reach stable storage. After the disk is
1653 * updated, the blocks can be safely de-allocated whenever it is convenient.
1654 * This implementation handles only the common case of reducing a file's
1655 * length to zero. Other cases are handled by the conventional synchronous
1658 * The ffs implementation with which we worked double-checks
1659 * the state of the block pointers and file size as it reduces
1660 * a file's length. Some of this code is replicated here in our
1661 * soft updates implementation. The freeblks->fb_chkcnt field is
1662 * used to transfer a part of this information to the procedure
1663 * that eventually de-allocates the blocks.
1665 * This routine should be called from the routine that shortens
1666 * a file's length, before the inode's size or block pointers
1667 * are modified. It will save the block pointer information for
1668 * later release and zero the inode so that the calling routine
1671 struct softdep_setup_freeblocks_info {
1676 static int softdep_setup_freeblocks_bp(struct buf *bp, void *data);
1680 * ip: The inode whose length is to be reduced
1681 * length: The new length for the file
1684 softdep_setup_freeblocks(struct inode *ip, off_t length)
1686 struct softdep_setup_freeblocks_info info;
1687 struct freeblks *freeblks;
1688 struct inodedep *inodedep;
1689 struct allocdirect *adp;
1693 int i, error, delay;
1698 panic("softde_setup_freeblocks: non-zero length");
1699 freeblks = kmalloc(sizeof(struct freeblks), M_FREEBLKS,
1700 M_SOFTDEP_FLAGS | M_ZERO);
1701 freeblks->fb_list.wk_type = D_FREEBLKS;
1702 freeblks->fb_state = ATTACHED;
1703 freeblks->fb_uid = ip->i_uid;
1704 freeblks->fb_previousinum = ip->i_number;
1705 freeblks->fb_devvp = ip->i_devvp;
1706 freeblks->fb_fs = fs;
1707 freeblks->fb_oldsize = ip->i_size;
1708 freeblks->fb_newsize = length;
1709 freeblks->fb_chkcnt = ip->i_blocks;
1710 for (i = 0; i < NDADDR; i++) {
1711 freeblks->fb_dblks[i] = ip->i_db[i];
1714 for (i = 0; i < NIADDR; i++) {
1715 freeblks->fb_iblks[i] = ip->i_ib[i];
1721 * Push the zero'ed inode to to its disk buffer so that we are free
1722 * to delete its dependencies below. Once the dependencies are gone
1723 * the buffer can be safely released.
1725 if ((error = bread(ip->i_devvp,
1726 fsbtodoff(fs, ino_to_fsba(fs, ip->i_number)),
1727 (int)fs->fs_bsize, &bp)) != 0)
1728 softdep_error("softdep_setup_freeblocks", error);
1729 *((struct ufs1_dinode *)bp->b_data + ino_to_fsbo(fs, ip->i_number)) =
1732 * Find and eliminate any inode dependencies.
1735 (void) inodedep_lookup(fs, ip->i_number, DEPALLOC, &inodedep);
1736 if ((inodedep->id_state & IOSTARTED) != 0) {
1737 panic("softdep_setup_freeblocks: inode busy");
1740 * Add the freeblks structure to the list of operations that
1741 * must await the zero'ed inode being written to disk. If we
1742 * still have a bitmap dependency (delay == 0), then the inode
1743 * has never been written to disk, so we can process the
1744 * freeblks below once we have deleted the dependencies.
1746 delay = (inodedep->id_state & DEPCOMPLETE);
1748 WORKLIST_INSERT(&inodedep->id_bufwait, &freeblks->fb_list);
1750 * Because the file length has been truncated to zero, any
1751 * pending block allocation dependency structures associated
1752 * with this inode are obsolete and can simply be de-allocated.
1753 * We must first merge the two dependency lists to get rid of
1754 * any duplicate freefrag structures, then purge the merged list.
1756 merge_inode_lists(inodedep);
1757 while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
1758 free_allocdirect(&inodedep->id_inoupdt, adp, 1);
1762 * We must wait for any I/O in progress to finish so that
1763 * all potential buffers on the dirty list will be visible.
1764 * Once they are all there, walk the list and get rid of
1769 drain_output(vp, 1);
1773 lwkt_gettoken(&vp->v_token);
1775 count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
1776 softdep_setup_freeblocks_bp, &info);
1777 } while (count != 0);
1778 lwkt_reltoken(&vp->v_token);
1780 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) != 0)
1781 (void)free_inodedep(inodedep);
1784 freeblks->fb_state |= DEPCOMPLETE;
1786 * If the inode with zeroed block pointers is now on disk
1787 * we can start freeing blocks. Add freeblks to the worklist
1788 * instead of calling handle_workitem_freeblocks directly as
1789 * it is more likely that additional IO is needed to complete
1790 * the request here than in the !delay case.
1792 if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
1793 add_to_worklist(&freeblks->fb_list);
1798 * If the inode has never been written to disk (delay == 0),
1799 * then we can process the freeblks now that we have deleted
1803 handle_workitem_freeblocks(freeblks);
1807 softdep_setup_freeblocks_bp(struct buf *bp, void *data)
1809 struct softdep_setup_freeblocks_info *info = data;
1810 struct inodedep *inodedep;
1812 if (getdirtybuf(&bp, MNT_WAIT) == 0) {
1813 kprintf("softdep_setup_freeblocks_bp(1): caught bp %p going away\n", bp);
1816 if (bp->b_vp != ITOV(info->ip) || (bp->b_flags & B_DELWRI) == 0) {
1817 kprintf("softdep_setup_freeblocks_bp(2): caught bp %p going away\n", bp);
1821 (void) inodedep_lookup(info->fs, info->ip->i_number, 0, &inodedep);
1822 deallocate_dependencies(bp, inodedep);
1823 bp->b_flags |= B_INVAL | B_NOCACHE;
1831 * Reclaim any dependency structures from a buffer that is about to
1832 * be reallocated to a new vnode. The buffer must be locked, thus,
1833 * no I/O completion operations can occur while we are manipulating
1834 * its associated dependencies. The mutex is held so that other I/O's
1835 * associated with related dependencies do not occur.
1838 deallocate_dependencies(struct buf *bp, struct inodedep *inodedep)
1840 struct worklist *wk;
1841 struct indirdep *indirdep;
1842 struct allocindir *aip;
1843 struct pagedep *pagedep;
1844 struct dirrem *dirrem;
1848 while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
1849 switch (wk->wk_type) {
1852 indirdep = WK_INDIRDEP(wk);
1854 * None of the indirect pointers will ever be visible,
1855 * so they can simply be tossed. GOINGAWAY ensures
1856 * that allocated pointers will be saved in the buffer
1857 * cache until they are freed. Note that they will
1858 * only be able to be found by their physical address
1859 * since the inode mapping the logical address will
1860 * be gone. The save buffer used for the safe copy
1861 * was allocated in setup_allocindir_phase2 using
1862 * the physical address so it could be used for this
1863 * purpose. Hence we swap the safe copy with the real
1864 * copy, allowing the safe copy to be freed and holding
1865 * on to the real copy for later use in indir_trunc.
1867 * NOTE: ir_savebp is relative to the block device
1868 * so b_bio1 contains the device block number.
1870 if (indirdep->ir_state & GOINGAWAY) {
1871 panic("deallocate_dependencies: already gone");
1873 indirdep->ir_state |= GOINGAWAY;
1874 while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
1875 free_allocindir(aip, inodedep);
1876 if (bp->b_bio1.bio_offset >= 0 ||
1877 bp->b_bio2.bio_offset != indirdep->ir_savebp->b_bio1.bio_offset) {
1878 panic("deallocate_dependencies: not indir");
1880 bcopy(bp->b_data, indirdep->ir_savebp->b_data,
1882 WORKLIST_REMOVE(wk);
1883 WORKLIST_INSERT_BP(indirdep->ir_savebp, wk);
1887 pagedep = WK_PAGEDEP(wk);
1889 * None of the directory additions will ever be
1890 * visible, so they can simply be tossed.
1892 for (i = 0; i < DAHASHSZ; i++)
1894 LIST_FIRST(&pagedep->pd_diraddhd[i])))
1896 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
1899 * Copy any directory remove dependencies to the list
1900 * to be processed after the zero'ed inode is written.
1901 * If the inode has already been written, then they
1902 * can be dumped directly onto the work list.
1904 LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
1905 LIST_REMOVE(dirrem, dm_next);
1906 dirrem->dm_dirinum = pagedep->pd_ino;
1907 if (inodedep == NULL ||
1908 (inodedep->id_state & ALLCOMPLETE) ==
1910 add_to_worklist(&dirrem->dm_list);
1912 WORKLIST_INSERT(&inodedep->id_bufwait,
1915 WORKLIST_REMOVE(&pagedep->pd_list);
1916 LIST_REMOVE(pagedep, pd_hash);
1917 WORKITEM_FREE(pagedep, D_PAGEDEP);
1921 free_allocindir(WK_ALLOCINDIR(wk), inodedep);
1926 panic("deallocate_dependencies: Unexpected type %s",
1927 TYPENAME(wk->wk_type));
1931 panic("deallocate_dependencies: Unknown type %s",
1932 TYPENAME(wk->wk_type));
1939 * Free an allocdirect. Generate a new freefrag work request if appropriate.
1940 * This routine must be called with splbio interrupts blocked.
1943 free_allocdirect(struct allocdirectlst *adphead,
1944 struct allocdirect *adp, int delay)
1946 KKASSERT(lock_held(&lk) > 0);
1948 if ((adp->ad_state & DEPCOMPLETE) == 0)
1949 LIST_REMOVE(adp, ad_deps);
1950 TAILQ_REMOVE(adphead, adp, ad_next);
1951 if ((adp->ad_state & COMPLETE) == 0)
1952 WORKLIST_REMOVE(&adp->ad_list);
1953 if (adp->ad_freefrag != NULL) {
1955 WORKLIST_INSERT(&adp->ad_inodedep->id_bufwait,
1956 &adp->ad_freefrag->ff_list);
1958 add_to_worklist(&adp->ad_freefrag->ff_list);
1960 WORKITEM_FREE(adp, D_ALLOCDIRECT);
1964 * Prepare an inode to be freed. The actual free operation is not
1965 * done until the zero'ed inode has been written to disk.
1968 softdep_freefile(struct vnode *pvp, ino_t ino, int mode)
1970 struct inode *ip = VTOI(pvp);
1971 struct inodedep *inodedep;
1972 struct freefile *freefile;
1975 * This sets up the inode de-allocation dependency.
1977 freefile = kmalloc(sizeof(struct freefile), M_FREEFILE,
1979 freefile->fx_list.wk_type = D_FREEFILE;
1980 freefile->fx_list.wk_state = 0;
1981 freefile->fx_mode = mode;
1982 freefile->fx_oldinum = ino;
1983 freefile->fx_devvp = ip->i_devvp;
1984 freefile->fx_fs = ip->i_fs;
1987 * If the inodedep does not exist, then the zero'ed inode has
1988 * been written to disk. If the allocated inode has never been
1989 * written to disk, then the on-disk inode is zero'ed. In either
1990 * case we can free the file immediately.
1993 if (inodedep_lookup(ip->i_fs, ino, 0, &inodedep) == 0 ||
1994 check_inode_unwritten(inodedep)) {
1996 handle_workitem_freefile(freefile);
1999 WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
2004 * Check to see if an inode has never been written to disk. If
2005 * so free the inodedep and return success, otherwise return failure.
2006 * This routine must be called with splbio interrupts blocked.
2008 * If we still have a bitmap dependency, then the inode has never
2009 * been written to disk. Drop the dependency as it is no longer
2010 * necessary since the inode is being deallocated. We set the
2011 * ALLCOMPLETE flags since the bitmap now properly shows that the
2012 * inode is not allocated. Even if the inode is actively being
2013 * written, it has been rolled back to its zero'ed state, so we
2014 * are ensured that a zero inode is what is on the disk. For short
2015 * lived files, this change will usually result in removing all the
2016 * dependencies from the inode so that it can be freed immediately.
2019 check_inode_unwritten(struct inodedep *inodedep)
2022 if ((inodedep->id_state & DEPCOMPLETE) != 0 ||
2023 LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2024 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2025 LIST_FIRST(&inodedep->id_inowait) != NULL ||
2026 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2027 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2028 inodedep->id_nlinkdelta != 0)
2032 * Another process might be in initiate_write_inodeblock
2033 * trying to allocate memory without holding "Softdep Lock".
2035 if ((inodedep->id_state & IOSTARTED) != 0 &&
2036 inodedep->id_savedino == NULL)
2039 inodedep->id_state |= ALLCOMPLETE;
2040 LIST_REMOVE(inodedep, id_deps);
2041 inodedep->id_buf = NULL;
2042 if (inodedep->id_state & ONWORKLIST)
2043 WORKLIST_REMOVE(&inodedep->id_list);
2044 if (inodedep->id_savedino != NULL) {
2045 kfree(inodedep->id_savedino, M_INODEDEP);
2046 inodedep->id_savedino = NULL;
2048 if (free_inodedep(inodedep) == 0) {
2049 panic("check_inode_unwritten: busy inode");
2055 * Try to free an inodedep structure. Return 1 if it could be freed.
2058 free_inodedep(struct inodedep *inodedep)
2061 if ((inodedep->id_state & ONWORKLIST) != 0 ||
2062 (inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
2063 LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2064 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2065 LIST_FIRST(&inodedep->id_inowait) != NULL ||
2066 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2067 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2068 inodedep->id_nlinkdelta != 0 || inodedep->id_savedino != NULL)
2070 LIST_REMOVE(inodedep, id_hash);
2071 WORKITEM_FREE(inodedep, D_INODEDEP);
2077 * This workitem routine performs the block de-allocation.
2078 * The workitem is added to the pending list after the updated
2079 * inode block has been written to disk. As mentioned above,
2080 * checks regarding the number of blocks de-allocated (compared
2081 * to the number of blocks allocated for the file) are also
2082 * performed in this function.
2085 handle_workitem_freeblocks(struct freeblks *freeblks)
2090 int i, level, bsize;
2091 long nblocks, blocksreleased = 0;
2092 int error, allerror = 0;
2093 ufs_lbn_t baselbns[NIADDR], tmpval;
2095 tip.i_number = freeblks->fb_previousinum;
2096 tip.i_devvp = freeblks->fb_devvp;
2097 tip.i_dev = freeblks->fb_devvp->v_rdev;
2098 tip.i_fs = freeblks->fb_fs;
2099 tip.i_size = freeblks->fb_oldsize;
2100 tip.i_uid = freeblks->fb_uid;
2101 fs = freeblks->fb_fs;
2103 baselbns[0] = NDADDR;
2104 for (i = 1; i < NIADDR; i++) {
2105 tmpval *= NINDIR(fs);
2106 baselbns[i] = baselbns[i - 1] + tmpval;
2108 nblocks = btodb(fs->fs_bsize);
2111 * Indirect blocks first.
2113 for (level = (NIADDR - 1); level >= 0; level--) {
2114 if ((bn = freeblks->fb_iblks[level]) == 0)
2116 if ((error = indir_trunc(&tip, fsbtodoff(fs, bn), level,
2117 baselbns[level], &blocksreleased)) == 0)
2119 ffs_blkfree(&tip, bn, fs->fs_bsize);
2120 blocksreleased += nblocks;
2123 * All direct blocks or frags.
2125 for (i = (NDADDR - 1); i >= 0; i--) {
2126 if ((bn = freeblks->fb_dblks[i]) == 0)
2128 bsize = blksize(fs, &tip, i);
2129 ffs_blkfree(&tip, bn, bsize);
2130 blocksreleased += btodb(bsize);
2134 if (freeblks->fb_chkcnt != blocksreleased)
2135 kprintf("handle_workitem_freeblocks: block count\n");
2137 softdep_error("handle_workitem_freeblks", allerror);
2138 #endif /* DIAGNOSTIC */
2139 WORKITEM_FREE(freeblks, D_FREEBLKS);
2143 * Release blocks associated with the inode ip and stored in the indirect
2144 * block at doffset. If level is greater than SINGLE, the block is an
2145 * indirect block and recursive calls to indirtrunc must be used to
2146 * cleanse other indirect blocks.
2149 indir_trunc(struct inode *ip, off_t doffset, int level, ufs_lbn_t lbn,
2156 struct worklist *wk;
2157 struct indirdep *indirdep;
2158 int i, lbnadd, nblocks;
2159 int error, allerror = 0;
2163 for (i = level; i > 0; i--)
2164 lbnadd *= NINDIR(fs);
2166 * Get buffer of block pointers to be freed. This routine is not
2167 * called until the zero'ed inode has been written, so it is safe
2168 * to free blocks as they are encountered. Because the inode has
2169 * been zero'ed, calls to bmap on these blocks will fail. So, we
2170 * have to use the on-disk address and the block device for the
2171 * filesystem to look them up. If the file was deleted before its
2172 * indirect blocks were all written to disk, the routine that set
2173 * us up (deallocate_dependencies) will have arranged to leave
2174 * a complete copy of the indirect block in memory for our use.
2175 * Otherwise we have to read the blocks in from the disk.
2178 if ((bp = findblk(ip->i_devvp, doffset, FINDBLK_TEST)) != NULL &&
2179 (wk = LIST_FIRST(&bp->b_dep)) != NULL) {
2181 * bp must be ir_savebp, which is held locked for our use.
2183 if (wk->wk_type != D_INDIRDEP ||
2184 (indirdep = WK_INDIRDEP(wk))->ir_savebp != bp ||
2185 (indirdep->ir_state & GOINGAWAY) == 0) {
2186 panic("indir_trunc: lost indirdep");
2188 WORKLIST_REMOVE(wk);
2189 WORKITEM_FREE(indirdep, D_INDIRDEP);
2190 if (LIST_FIRST(&bp->b_dep) != NULL) {
2191 panic("indir_trunc: dangling dep");
2196 error = bread(ip->i_devvp, doffset, (int)fs->fs_bsize, &bp);
2201 * Recursively free indirect blocks.
2203 bap = (ufs_daddr_t *)bp->b_data;
2204 nblocks = btodb(fs->fs_bsize);
2205 for (i = NINDIR(fs) - 1; i >= 0; i--) {
2206 if ((nb = bap[i]) == 0)
2209 if ((error = indir_trunc(ip, fsbtodoff(fs, nb),
2210 level - 1, lbn + (i * lbnadd), countp)) != 0)
2213 ffs_blkfree(ip, nb, fs->fs_bsize);
2216 bp->b_flags |= B_INVAL | B_NOCACHE;
2222 * Free an allocindir.
2223 * This routine must be called with splbio interrupts blocked.
2226 free_allocindir(struct allocindir *aip, struct inodedep *inodedep)
2228 struct freefrag *freefrag;
2230 KKASSERT(lock_held(&lk) > 0);
2232 if ((aip->ai_state & DEPCOMPLETE) == 0)
2233 LIST_REMOVE(aip, ai_deps);
2234 if (aip->ai_state & ONWORKLIST)
2235 WORKLIST_REMOVE(&aip->ai_list);
2236 LIST_REMOVE(aip, ai_next);
2237 if ((freefrag = aip->ai_freefrag) != NULL) {
2238 if (inodedep == NULL)
2239 add_to_worklist(&freefrag->ff_list);
2241 WORKLIST_INSERT(&inodedep->id_bufwait,
2242 &freefrag->ff_list);
2244 WORKITEM_FREE(aip, D_ALLOCINDIR);
2248 * Directory entry addition dependencies.
2250 * When adding a new directory entry, the inode (with its incremented link
2251 * count) must be written to disk before the directory entry's pointer to it.
2252 * Also, if the inode is newly allocated, the corresponding freemap must be
2253 * updated (on disk) before the directory entry's pointer. These requirements
2254 * are met via undo/redo on the directory entry's pointer, which consists
2255 * simply of the inode number.
2257 * As directory entries are added and deleted, the free space within a
2258 * directory block can become fragmented. The ufs filesystem will compact
2259 * a fragmented directory block to make space for a new entry. When this
2260 * occurs, the offsets of previously added entries change. Any "diradd"
2261 * dependency structures corresponding to these entries must be updated with
2266 * This routine is called after the in-memory inode's link
2267 * count has been incremented, but before the directory entry's
2268 * pointer to the inode has been set.
2271 * bp: buffer containing directory block
2272 * dp: inode for directory
2273 * diroffset: offset of new entry in directory
2274 * newinum: inode referenced by new directory entry
2275 * newdirbp: non-NULL => contents of new mkdir
2278 softdep_setup_directory_add(struct buf *bp, struct inode *dp, off_t diroffset,
2279 ino_t newinum, struct buf *newdirbp)
2281 int offset; /* offset of new entry within directory block */
2282 ufs_lbn_t lbn; /* block in directory containing new entry */
2285 struct pagedep *pagedep;
2286 struct inodedep *inodedep;
2287 struct mkdir *mkdir1, *mkdir2;
2290 * Whiteouts have no dependencies.
2292 if (newinum == WINO) {
2293 if (newdirbp != NULL)
2299 lbn = lblkno(fs, diroffset);
2300 offset = blkoff(fs, diroffset);
2301 dap = kmalloc(sizeof(struct diradd), M_DIRADD,
2302 M_SOFTDEP_FLAGS | M_ZERO);
2303 dap->da_list.wk_type = D_DIRADD;
2304 dap->da_offset = offset;
2305 dap->da_newinum = newinum;
2306 dap->da_state = ATTACHED;
2307 if (newdirbp == NULL) {
2308 dap->da_state |= DEPCOMPLETE;
2311 dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
2312 mkdir1 = kmalloc(sizeof(struct mkdir), M_MKDIR,
2314 mkdir1->md_list.wk_type = D_MKDIR;
2315 mkdir1->md_state = MKDIR_BODY;
2316 mkdir1->md_diradd = dap;
2317 mkdir2 = kmalloc(sizeof(struct mkdir), M_MKDIR,
2319 mkdir2->md_list.wk_type = D_MKDIR;
2320 mkdir2->md_state = MKDIR_PARENT;
2321 mkdir2->md_diradd = dap;
2323 * Dependency on "." and ".." being written to disk.
2325 mkdir1->md_buf = newdirbp;
2327 LIST_INSERT_HEAD(&mkdirlisthd, mkdir1, md_mkdirs);
2328 WORKLIST_INSERT_BP(newdirbp, &mkdir1->md_list);
2332 * Dependency on link count increase for parent directory
2335 if (inodedep_lookup(dp->i_fs, dp->i_number, 0, &inodedep) == 0
2336 || (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2337 dap->da_state &= ~MKDIR_PARENT;
2338 WORKITEM_FREE(mkdir2, D_MKDIR);
2340 LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
2341 WORKLIST_INSERT(&inodedep->id_bufwait,&mkdir2->md_list);
2345 * Link into parent directory pagedep to await its being written.
2347 if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2348 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
2349 dap->da_pagedep = pagedep;
2350 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
2353 * Link into its inodedep. Put it on the id_bufwait list if the inode
2354 * is not yet written. If it is written, do the post-inode write
2355 * processing to put it on the id_pendinghd list.
2357 (void) inodedep_lookup(fs, newinum, DEPALLOC, &inodedep);
2358 if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
2359 diradd_inode_written(dap, inodedep);
2361 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2366 * This procedure is called to change the offset of a directory
2367 * entry when compacting a directory block which must be owned
2368 * exclusively by the caller. Note that the actual entry movement
2369 * must be done in this procedure to ensure that no I/O completions
2370 * occur while the move is in progress.
2373 * dp: inode for directory
2374 * base: address of dp->i_offset
2375 * oldloc: address of old directory location
2376 * newloc: address of new directory location
2377 * entrysize: size of directory entry
2380 softdep_change_directoryentry_offset(struct inode *dp, caddr_t base,
2381 caddr_t oldloc, caddr_t newloc,
2384 int offset, oldoffset, newoffset;
2385 struct pagedep *pagedep;
2390 lbn = lblkno(dp->i_fs, dp->i_offset);
2391 offset = blkoff(dp->i_fs, dp->i_offset);
2392 if (pagedep_lookup(dp, lbn, 0, &pagedep) == 0)
2394 oldoffset = offset + (oldloc - base);
2395 newoffset = offset + (newloc - base);
2397 LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(oldoffset)], da_pdlist) {
2398 if (dap->da_offset != oldoffset)
2400 dap->da_offset = newoffset;
2401 if (DIRADDHASH(newoffset) == DIRADDHASH(oldoffset))
2403 LIST_REMOVE(dap, da_pdlist);
2404 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(newoffset)],
2410 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist) {
2411 if (dap->da_offset == oldoffset) {
2412 dap->da_offset = newoffset;
2418 bcopy(oldloc, newloc, entrysize);
2423 * Free a diradd dependency structure. This routine must be called
2424 * with splbio interrupts blocked.
2427 free_diradd(struct diradd *dap)
2429 struct dirrem *dirrem;
2430 struct pagedep *pagedep;
2431 struct inodedep *inodedep;
2432 struct mkdir *mkdir, *nextmd;
2434 KKASSERT(lock_held(&lk) > 0);
2436 WORKLIST_REMOVE(&dap->da_list);
2437 LIST_REMOVE(dap, da_pdlist);
2438 if ((dap->da_state & DIRCHG) == 0) {
2439 pagedep = dap->da_pagedep;
2441 dirrem = dap->da_previous;
2442 pagedep = dirrem->dm_pagedep;
2443 dirrem->dm_dirinum = pagedep->pd_ino;
2444 add_to_worklist(&dirrem->dm_list);
2446 if (inodedep_lookup(VFSTOUFS(pagedep->pd_mnt)->um_fs, dap->da_newinum,
2448 (void) free_inodedep(inodedep);
2449 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
2450 for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
2451 nextmd = LIST_NEXT(mkdir, md_mkdirs);
2452 if (mkdir->md_diradd != dap)
2454 dap->da_state &= ~mkdir->md_state;
2455 WORKLIST_REMOVE(&mkdir->md_list);
2456 LIST_REMOVE(mkdir, md_mkdirs);
2457 WORKITEM_FREE(mkdir, D_MKDIR);
2459 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
2460 panic("free_diradd: unfound ref");
2463 WORKITEM_FREE(dap, D_DIRADD);
2467 * Directory entry removal dependencies.
2469 * When removing a directory entry, the entry's inode pointer must be
2470 * zero'ed on disk before the corresponding inode's link count is decremented
2471 * (possibly freeing the inode for re-use). This dependency is handled by
2472 * updating the directory entry but delaying the inode count reduction until
2473 * after the directory block has been written to disk. After this point, the
2474 * inode count can be decremented whenever it is convenient.
2478 * This routine should be called immediately after removing
2479 * a directory entry. The inode's link count should not be
2480 * decremented by the calling procedure -- the soft updates
2481 * code will do this task when it is safe.
2484 * bp: buffer containing directory block
2485 * dp: inode for the directory being modified
2486 * ip: inode for directory entry being removed
2487 * isrmdir: indicates if doing RMDIR
2490 softdep_setup_remove(struct buf *bp, struct inode *dp, struct inode *ip,
2493 struct dirrem *dirrem, *prevdirrem;
2496 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.
2498 dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
2501 * If the COMPLETE flag is clear, then there were no active
2502 * entries and we want to roll back to a zeroed entry until
2503 * the new inode is committed to disk. If the COMPLETE flag is
2504 * set then we have deleted an entry that never made it to
2505 * disk. If the entry we deleted resulted from a name change,
2506 * then the old name still resides on disk. We cannot delete
2507 * its inode (returned to us in prevdirrem) until the zeroed
2508 * directory entry gets to disk. The new inode has never been
2509 * referenced on the disk, so can be deleted immediately.
2511 if ((dirrem->dm_state & COMPLETE) == 0) {
2512 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
2516 if (prevdirrem != NULL)
2517 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
2518 prevdirrem, dm_next);
2519 dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
2521 handle_workitem_remove(dirrem);
2526 * Allocate a new dirrem if appropriate and return it along with
2527 * its associated pagedep. Called without a lock, returns with lock.
2529 static long num_dirrem; /* number of dirrem allocated */
2533 * bp: buffer containing directory block
2534 * dp: inode for the directory being modified
2535 * ip: inode for directory entry being removed
2536 * isrmdir: indicates if doing RMDIR
2537 * prevdirremp: previously referenced inode, if any
2539 static struct dirrem *
2540 newdirrem(struct buf *bp, struct inode *dp, struct inode *ip,
2541 int isrmdir, struct dirrem **prevdirremp)
2546 struct dirrem *dirrem;
2547 struct pagedep *pagedep;
2550 * Whiteouts have no deletion dependencies.
2553 panic("newdirrem: whiteout");
2555 * If we are over our limit, try to improve the situation.
2556 * Limiting the number of dirrem structures will also limit
2557 * the number of freefile and freeblks structures.
2559 if (num_dirrem > max_softdeps / 2 && speedup_syncer() == 0)
2560 (void) request_cleanup(FLUSH_REMOVE, 0);
2562 dirrem = kmalloc(sizeof(struct dirrem), M_DIRREM,
2563 M_SOFTDEP_FLAGS | M_ZERO);
2564 dirrem->dm_list.wk_type = D_DIRREM;
2565 dirrem->dm_state = isrmdir ? RMDIR : 0;
2566 dirrem->dm_mnt = ITOV(ip)->v_mount;
2567 dirrem->dm_oldinum = ip->i_number;
2568 *prevdirremp = NULL;
2571 lbn = lblkno(dp->i_fs, dp->i_offset);
2572 offset = blkoff(dp->i_fs, dp->i_offset);
2573 if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2574 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
2575 dirrem->dm_pagedep = pagedep;
2577 * Check for a diradd dependency for the same directory entry.
2578 * If present, then both dependencies become obsolete and can
2579 * be de-allocated. Check for an entry on both the pd_dirraddhd
2580 * list and the pd_pendinghd list.
2583 LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
2584 if (dap->da_offset == offset)
2588 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
2589 if (dap->da_offset == offset)
2595 * Must be ATTACHED at this point.
2597 if ((dap->da_state & ATTACHED) == 0) {
2598 panic("newdirrem: not ATTACHED");
2600 if (dap->da_newinum != ip->i_number) {
2601 panic("newdirrem: inum %"PRId64" should be %"PRId64,
2602 ip->i_number, dap->da_newinum);
2605 * If we are deleting a changed name that never made it to disk,
2606 * then return the dirrem describing the previous inode (which
2607 * represents the inode currently referenced from this entry on disk).
2609 if ((dap->da_state & DIRCHG) != 0) {
2610 *prevdirremp = dap->da_previous;
2611 dap->da_state &= ~DIRCHG;
2612 dap->da_pagedep = pagedep;
2615 * We are deleting an entry that never made it to disk.
2616 * Mark it COMPLETE so we can delete its inode immediately.
2618 dirrem->dm_state |= COMPLETE;
2624 * Directory entry change dependencies.
2626 * Changing an existing directory entry requires that an add operation
2627 * be completed first followed by a deletion. The semantics for the addition
2628 * are identical to the description of adding a new entry above except
2629 * that the rollback is to the old inode number rather than zero. Once
2630 * the addition dependency is completed, the removal is done as described
2631 * in the removal routine above.
2635 * This routine should be called immediately after changing
2636 * a directory entry. The inode's link count should not be
2637 * decremented by the calling procedure -- the soft updates
2638 * code will perform this task when it is safe.
2641 * bp: buffer containing directory block
2642 * dp: inode for the directory being modified
2643 * ip: inode for directory entry being removed
2644 * newinum: new inode number for changed entry
2645 * isrmdir: indicates if doing RMDIR
2648 softdep_setup_directory_change(struct buf *bp, struct inode *dp,
2649 struct inode *ip, ino_t newinum,
2653 struct diradd *dap = NULL;
2654 struct dirrem *dirrem, *prevdirrem;
2655 struct pagedep *pagedep;
2656 struct inodedep *inodedep;
2658 offset = blkoff(dp->i_fs, dp->i_offset);
2661 * Whiteouts do not need diradd dependencies.
2663 if (newinum != WINO) {
2664 dap = kmalloc(sizeof(struct diradd), M_DIRADD,
2665 M_SOFTDEP_FLAGS | M_ZERO);
2666 dap->da_list.wk_type = D_DIRADD;
2667 dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
2668 dap->da_offset = offset;
2669 dap->da_newinum = newinum;
2673 * Allocate a new dirrem and ACQUIRE_LOCK.
2675 dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
2676 pagedep = dirrem->dm_pagedep;
2678 * The possible values for isrmdir:
2679 * 0 - non-directory file rename
2680 * 1 - directory rename within same directory
2681 * inum - directory rename to new directory of given inode number
2682 * When renaming to a new directory, we are both deleting and
2683 * creating a new directory entry, so the link count on the new
2684 * directory should not change. Thus we do not need the followup
2685 * dirrem which is usually done in handle_workitem_remove. We set
2686 * the DIRCHG flag to tell handle_workitem_remove to skip the
2690 dirrem->dm_state |= DIRCHG;
2693 * Whiteouts have no additional dependencies,
2694 * so just put the dirrem on the correct list.
2696 if (newinum == WINO) {
2697 if ((dirrem->dm_state & COMPLETE) == 0) {
2698 LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
2701 dirrem->dm_dirinum = pagedep->pd_ino;
2702 add_to_worklist(&dirrem->dm_list);
2709 * If the COMPLETE flag is clear, then there were no active
2710 * entries and we want to roll back to the previous inode until
2711 * the new inode is committed to disk. If the COMPLETE flag is
2712 * set, then we have deleted an entry that never made it to disk.
2713 * If the entry we deleted resulted from a name change, then the old
2714 * inode reference still resides on disk. Any rollback that we do
2715 * needs to be to that old inode (returned to us in prevdirrem). If
2716 * the entry we deleted resulted from a create, then there is
2717 * no entry on the disk, so we want to roll back to zero rather
2718 * than the uncommitted inode. In either of the COMPLETE cases we
2719 * want to immediately free the unwritten and unreferenced inode.
2721 if ((dirrem->dm_state & COMPLETE) == 0) {
2722 dap->da_previous = dirrem;
2724 if (prevdirrem != NULL) {
2725 dap->da_previous = prevdirrem;
2727 dap->da_state &= ~DIRCHG;
2728 dap->da_pagedep = pagedep;
2730 dirrem->dm_dirinum = pagedep->pd_ino;
2731 add_to_worklist(&dirrem->dm_list);
2734 * Link into its inodedep. Put it on the id_bufwait list if the inode
2735 * is not yet written. If it is written, do the post-inode write
2736 * processing to put it on the id_pendinghd list.
2738 if (inodedep_lookup(dp->i_fs, newinum, DEPALLOC, &inodedep) == 0 ||
2739 (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2740 dap->da_state |= COMPLETE;
2741 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
2742 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
2744 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
2746 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2752 * Called whenever the link count on an inode is changed.
2753 * It creates an inode dependency so that the new reference(s)
2754 * to the inode cannot be committed to disk until the updated
2755 * inode has been written.
2758 * ip: the inode with the increased link count
2761 softdep_change_linkcnt(struct inode *ip)
2763 struct inodedep *inodedep;
2766 (void) inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC, &inodedep);
2767 if (ip->i_nlink < ip->i_effnlink) {
2768 panic("softdep_change_linkcnt: bad delta");
2770 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2775 * This workitem decrements the inode's link count.
2776 * If the link count reaches zero, the file is removed.
2779 handle_workitem_remove(struct dirrem *dirrem)
2781 struct inodedep *inodedep;
2787 error = VFS_VGET(dirrem->dm_mnt, NULL, dirrem->dm_oldinum, &vp);
2789 softdep_error("handle_workitem_remove: vget", error);
2794 if ((inodedep_lookup(ip->i_fs, dirrem->dm_oldinum, 0, &inodedep)) == 0){
2795 panic("handle_workitem_remove: lost inodedep");
2798 * Normal file deletion.
2800 if ((dirrem->dm_state & RMDIR) == 0) {
2802 ip->i_flag |= IN_CHANGE;
2803 if (ip->i_nlink < ip->i_effnlink) {
2804 panic("handle_workitem_remove: bad file delta");
2806 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2810 WORKITEM_FREE(dirrem, D_DIRREM);
2814 * Directory deletion. Decrement reference count for both the
2815 * just deleted parent directory entry and the reference for ".".
2816 * Next truncate the directory to length zero. When the
2817 * truncation completes, arrange to have the reference count on
2818 * the parent decremented to account for the loss of "..".
2821 ip->i_flag |= IN_CHANGE;
2822 if (ip->i_nlink < ip->i_effnlink) {
2823 panic("handle_workitem_remove: bad dir delta");
2825 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2827 if ((error = ffs_truncate(vp, (off_t)0, 0, proc0.p_ucred)) != 0)
2828 softdep_error("handle_workitem_remove: truncate", error);
2830 * Rename a directory to a new parent. Since, we are both deleting
2831 * and creating a new directory entry, the link count on the new
2832 * directory should not change. Thus we skip the followup dirrem.
2834 if (dirrem->dm_state & DIRCHG) {
2837 WORKITEM_FREE(dirrem, D_DIRREM);
2841 * If the inodedep does not exist, then the zero'ed inode has
2842 * been written to disk. If the allocated inode has never been
2843 * written to disk, then the on-disk inode is zero'ed. In either
2844 * case we can remove the file immediately.
2847 dirrem->dm_state = 0;
2848 oldinum = dirrem->dm_oldinum;
2849 dirrem->dm_oldinum = dirrem->dm_dirinum;
2850 if (inodedep_lookup(ip->i_fs, oldinum, 0, &inodedep) == 0 ||
2851 check_inode_unwritten(inodedep)) {
2854 handle_workitem_remove(dirrem);
2857 WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
2859 ip->i_flag |= IN_CHANGE;
2865 * Inode de-allocation dependencies.
2867 * When an inode's link count is reduced to zero, it can be de-allocated. We
2868 * found it convenient to postpone de-allocation until after the inode is
2869 * written to disk with its new link count (zero). At this point, all of the
2870 * on-disk inode's block pointers are nullified and, with careful dependency
2871 * list ordering, all dependencies related to the inode will be satisfied and
2872 * the corresponding dependency structures de-allocated. So, if/when the
2873 * inode is reused, there will be no mixing of old dependencies with new
2874 * ones. This artificial dependency is set up by the block de-allocation
2875 * procedure above (softdep_setup_freeblocks) and completed by the
2876 * following procedure.
2879 handle_workitem_freefile(struct freefile *freefile)
2883 struct inodedep *idp;
2888 error = inodedep_lookup(freefile->fx_fs, freefile->fx_oldinum, 0, &idp);
2891 panic("handle_workitem_freefile: inodedep survived");
2893 tip.i_devvp = freefile->fx_devvp;
2894 tip.i_dev = freefile->fx_devvp->v_rdev;
2895 tip.i_fs = freefile->fx_fs;
2897 if ((error = ffs_freefile(&vp, freefile->fx_oldinum, freefile->fx_mode)) != 0)
2898 softdep_error("handle_workitem_freefile", error);
2899 WORKITEM_FREE(freefile, D_FREEFILE);
2903 * Helper function which unlinks marker element from work list and returns
2904 * the next element on the list.
2906 static __inline struct worklist *
2907 markernext(struct worklist *marker)
2909 struct worklist *next;
2911 next = LIST_NEXT(marker, wk_list);
2912 LIST_REMOVE(marker, wk_list);
2917 * checkread, checkwrite
2919 * bioops callback - hold io_token
2922 softdep_checkread(struct buf *bp)
2924 /* nothing to do, mp lock not needed */
2929 * bioops callback - hold io_token
2932 softdep_checkwrite(struct buf *bp)
2934 /* nothing to do, mp lock not needed */
2941 * The dependency structures constructed above are most actively used when file
2942 * system blocks are written to disk. No constraints are placed on when a
2943 * block can be written, but unsatisfied update dependencies are made safe by
2944 * modifying (or replacing) the source memory for the duration of the disk
2945 * write. When the disk write completes, the memory block is again brought
2948 * In-core inode structure reclamation.
2950 * Because there are a finite number of "in-core" inode structures, they are
2951 * reused regularly. By transferring all inode-related dependencies to the
2952 * in-memory inode block and indexing them separately (via "inodedep"s), we
2953 * can allow "in-core" inode structures to be reused at any time and avoid
2954 * any increase in contention.
2956 * Called just before entering the device driver to initiate a new disk I/O.
2957 * The buffer must be locked, thus, no I/O completion operations can occur
2958 * while we are manipulating its associated dependencies.
2960 * bioops callback - hold io_token
2963 * bp: structure describing disk write to occur
2966 softdep_disk_io_initiation(struct buf *bp)
2968 struct worklist *wk;
2969 struct worklist marker;
2970 struct indirdep *indirdep;
2973 * We only care about write operations. There should never
2974 * be dependencies for reads.
2976 if (bp->b_cmd == BUF_CMD_READ)
2977 panic("softdep_disk_io_initiation: read");
2980 marker.wk_type = D_LAST + 1; /* Not a normal workitem */
2983 * Do any necessary pre-I/O processing.
2985 for (wk = LIST_FIRST(&bp->b_dep); wk; wk = markernext(&marker)) {
2986 LIST_INSERT_AFTER(wk, &marker, wk_list);
2988 switch (wk->wk_type) {
2990 initiate_write_filepage(WK_PAGEDEP(wk), bp);
2994 initiate_write_inodeblock(WK_INODEDEP(wk), bp);
2998 indirdep = WK_INDIRDEP(wk);
2999 if (indirdep->ir_state & GOINGAWAY)
3000 panic("disk_io_initiation: indirdep gone");
3002 * If there are no remaining dependencies, this
3003 * will be writing the real pointers, so the
3004 * dependency can be freed.
3006 if (LIST_FIRST(&indirdep->ir_deplisthd) == NULL) {
3007 indirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
3008 brelse(indirdep->ir_savebp);
3009 /* inline expand WORKLIST_REMOVE(wk); */
3010 wk->wk_state &= ~ONWORKLIST;
3011 LIST_REMOVE(wk, wk_list);
3012 WORKITEM_FREE(indirdep, D_INDIRDEP);
3016 * Replace up-to-date version with safe version.
3018 indirdep->ir_saveddata = kmalloc(bp->b_bcount,
3022 indirdep->ir_state &= ~ATTACHED;
3023 indirdep->ir_state |= UNDONE;
3024 bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
3025 bcopy(indirdep->ir_savebp->b_data, bp->b_data,
3037 panic("handle_disk_io_initiation: Unexpected type %s",
3038 TYPENAME(wk->wk_type));
3046 * Called from within the procedure above to deal with unsatisfied
3047 * allocation dependencies in a directory. The buffer must be locked,
3048 * thus, no I/O completion operations can occur while we are
3049 * manipulating its associated dependencies.
3052 initiate_write_filepage(struct pagedep *pagedep, struct buf *bp)
3058 if (pagedep->pd_state & IOSTARTED) {
3060 * This can only happen if there is a driver that does not
3061 * understand chaining. Here biodone will reissue the call
3062 * to strategy for the incomplete buffers.
3064 kprintf("initiate_write_filepage: already started\n");
3067 pagedep->pd_state |= IOSTARTED;
3069 for (i = 0; i < DAHASHSZ; i++) {
3070 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
3071 ep = (struct direct *)
3072 ((char *)bp->b_data + dap->da_offset);
3073 if (ep->d_ino != dap->da_newinum) {
3074 panic("%s: dir inum %d != new %"PRId64,
3075 "initiate_write_filepage",
3076 ep->d_ino, dap->da_newinum);
3078 if (dap->da_state & DIRCHG)
3079 ep->d_ino = dap->da_previous->dm_oldinum;
3082 dap->da_state &= ~ATTACHED;
3083 dap->da_state |= UNDONE;
3090 * Called from within the procedure above to deal with unsatisfied
3091 * allocation dependencies in an inodeblock. The buffer must be
3092 * locked, thus, no I/O completion operations can occur while we
3093 * are manipulating its associated dependencies.
3096 * bp: The inode block
3099 initiate_write_inodeblock(struct inodedep *inodedep, struct buf *bp)
3101 struct allocdirect *adp, *lastadp;
3102 struct ufs1_dinode *dp;
3103 struct ufs1_dinode *sip;
3105 ufs_lbn_t prevlbn = 0;
3108 if (inodedep->id_state & IOSTARTED)
3109 panic("initiate_write_inodeblock: already started");
3110 inodedep->id_state |= IOSTARTED;
3111 fs = inodedep->id_fs;
3112 dp = (struct ufs1_dinode *)bp->b_data +
3113 ino_to_fsbo(fs, inodedep->id_ino);
3115 * If the bitmap is not yet written, then the allocated
3116 * inode cannot be written to disk.
3118 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
3119 if (inodedep->id_savedino != NULL)
3120 panic("initiate_write_inodeblock: already doing I/O");
3121 sip = kmalloc(sizeof(struct ufs1_dinode), M_INODEDEP,
3123 inodedep->id_savedino = sip;
3124 *inodedep->id_savedino = *dp;
3125 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
3126 dp->di_gen = inodedep->id_savedino->di_gen;
3130 * If no dependencies, then there is nothing to roll back.
3132 inodedep->id_savedsize = dp->di_size;
3133 if (TAILQ_FIRST(&inodedep->id_inoupdt) == NULL)
3136 * Set the dependencies to busy.
3139 for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3140 adp = TAILQ_NEXT(adp, ad_next)) {
3142 if (deplist != 0 && prevlbn >= adp->ad_lbn) {
3143 panic("softdep_write_inodeblock: lbn order");
3145 prevlbn = adp->ad_lbn;
3146 if (adp->ad_lbn < NDADDR &&
3147 dp->di_db[adp->ad_lbn] != adp->ad_newblkno) {
3148 panic("%s: direct pointer #%ld mismatch %d != %d",
3149 "softdep_write_inodeblock", adp->ad_lbn,
3150 dp->di_db[adp->ad_lbn], adp->ad_newblkno);
3152 if (adp->ad_lbn >= NDADDR &&
3153 dp->di_ib[adp->ad_lbn - NDADDR] != adp->ad_newblkno) {
3154 panic("%s: indirect pointer #%ld mismatch %d != %d",
3155 "softdep_write_inodeblock", adp->ad_lbn - NDADDR,
3156 dp->di_ib[adp->ad_lbn - NDADDR], adp->ad_newblkno);
3158 deplist |= 1 << adp->ad_lbn;
3159 if ((adp->ad_state & ATTACHED) == 0) {
3160 panic("softdep_write_inodeblock: Unknown state 0x%x",
3163 #endif /* DIAGNOSTIC */
3164 adp->ad_state &= ~ATTACHED;
3165 adp->ad_state |= UNDONE;
3168 * The on-disk inode cannot claim to be any larger than the last
3169 * fragment that has been written. Otherwise, the on-disk inode
3170 * might have fragments that were not the last block in the file
3171 * which would corrupt the filesystem.
3173 for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3174 lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
3175 if (adp->ad_lbn >= NDADDR)
3177 dp->di_db[adp->ad_lbn] = adp->ad_oldblkno;
3178 /* keep going until hitting a rollback to a frag */
3179 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
3181 dp->di_size = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
3182 for (i = adp->ad_lbn + 1; i < NDADDR; i++) {
3184 if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0) {
3185 panic("softdep_write_inodeblock: lost dep1");
3187 #endif /* DIAGNOSTIC */
3190 for (i = 0; i < NIADDR; i++) {
3192 if (dp->di_ib[i] != 0 &&
3193 (deplist & ((1 << NDADDR) << i)) == 0) {
3194 panic("softdep_write_inodeblock: lost dep2");
3196 #endif /* DIAGNOSTIC */
3203 * If we have zero'ed out the last allocated block of the file,
3204 * roll back the size to the last currently allocated block.
3205 * We know that this last allocated block is a full-sized as
3206 * we already checked for fragments in the loop above.
3208 if (lastadp != NULL &&
3209 dp->di_size <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
3210 for (i = lastadp->ad_lbn; i >= 0; i--)
3211 if (dp->di_db[i] != 0)
3213 dp->di_size = (i + 1) * fs->fs_bsize;
3216 * The only dependencies are for indirect blocks.
3218 * The file size for indirect block additions is not guaranteed.
3219 * Such a guarantee would be non-trivial to achieve. The conventional
3220 * synchronous write implementation also does not make this guarantee.
3221 * Fsck should catch and fix discrepancies. Arguably, the file size
3222 * can be over-estimated without destroying integrity when the file
3223 * moves into the indirect blocks (i.e., is large). If we want to
3224 * postpone fsck, we are stuck with this argument.
3226 for (; adp; adp = TAILQ_NEXT(adp, ad_next))
3227 dp->di_ib[adp->ad_lbn - NDADDR] = 0;
3232 * This routine is called during the completion interrupt
3233 * service routine for a disk write (from the procedure called
3234 * by the device driver to inform the filesystem caches of
3235 * a request completion). It should be called early in this
3236 * procedure, before the block is made available to other
3237 * processes or other routines are called.
3239 * bioops callback - hold io_token
3242 * bp: describes the completed disk write
3245 softdep_disk_write_complete(struct buf *bp)
3247 struct worklist *wk;
3248 struct workhead reattach;
3249 struct newblk *newblk;
3250 struct allocindir *aip;
3251 struct allocdirect *adp;
3252 struct indirdep *indirdep;
3253 struct inodedep *inodedep;
3254 struct bmsafemap *bmsafemap;
3258 LIST_INIT(&reattach);
3259 while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
3260 WORKLIST_REMOVE(wk);
3261 switch (wk->wk_type) {
3264 if (handle_written_filepage(WK_PAGEDEP(wk), bp))
3265 WORKLIST_INSERT(&reattach, wk);
3269 if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
3270 WORKLIST_INSERT(&reattach, wk);
3274 bmsafemap = WK_BMSAFEMAP(wk);
3275 while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkhd))) {
3276 newblk->nb_state |= DEPCOMPLETE;
3277 newblk->nb_bmsafemap = NULL;
3278 LIST_REMOVE(newblk, nb_deps);
3281 LIST_FIRST(&bmsafemap->sm_allocdirecthd))) {
3282 adp->ad_state |= DEPCOMPLETE;
3284 LIST_REMOVE(adp, ad_deps);
3285 handle_allocdirect_partdone(adp);
3288 LIST_FIRST(&bmsafemap->sm_allocindirhd))) {
3289 aip->ai_state |= DEPCOMPLETE;
3291 LIST_REMOVE(aip, ai_deps);
3292 handle_allocindir_partdone(aip);
3295 LIST_FIRST(&bmsafemap->sm_inodedephd)) != NULL) {
3296 inodedep->id_state |= DEPCOMPLETE;
3297 LIST_REMOVE(inodedep, id_deps);
3298 inodedep->id_buf = NULL;
3300 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
3304 handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
3308 adp = WK_ALLOCDIRECT(wk);
3309 adp->ad_state |= COMPLETE;
3310 handle_allocdirect_partdone(adp);
3314 aip = WK_ALLOCINDIR(wk);
3315 aip->ai_state |= COMPLETE;
3316 handle_allocindir_partdone(aip);
3320 indirdep = WK_INDIRDEP(wk);
3321 if (indirdep->ir_state & GOINGAWAY) {
3322 panic("disk_write_complete: indirdep gone");
3324 bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
3325 kfree(indirdep->ir_saveddata, M_INDIRDEP);
3326 indirdep->ir_saveddata = 0;
3327 indirdep->ir_state &= ~UNDONE;
3328 indirdep->ir_state |= ATTACHED;
3329 while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
3330 handle_allocindir_partdone(aip);
3331 if (aip == LIST_FIRST(&indirdep->ir_donehd)) {
3332 panic("disk_write_complete: not gone");
3335 WORKLIST_INSERT(&reattach, wk);
3336 if ((bp->b_flags & B_DELWRI) == 0)
3337 stat_indir_blk_ptrs++;
3342 panic("handle_disk_write_complete: Unknown type %s",
3343 TYPENAME(wk->wk_type));
3348 * Reattach any requests that must be redone.
3350 while ((wk = LIST_FIRST(&reattach)) != NULL) {
3351 WORKLIST_REMOVE(wk);
3352 WORKLIST_INSERT_BP(bp, wk);
3359 * Called from within softdep_disk_write_complete above. Note that
3360 * this routine is always called from interrupt level with further
3361 * splbio interrupts blocked.
3364 * adp: the completed allocdirect
3367 handle_allocdirect_partdone(struct allocdirect *adp)
3369 struct allocdirect *listadp;
3370 struct inodedep *inodedep;
3373 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3375 if (adp->ad_buf != NULL)
3376 panic("handle_allocdirect_partdone: dangling dep");
3379 * The on-disk inode cannot claim to be any larger than the last
3380 * fragment that has been written. Otherwise, the on-disk inode
3381 * might have fragments that were not the last block in the file
3382 * which would corrupt the filesystem. Thus, we cannot free any
3383 * allocdirects after one whose ad_oldblkno claims a fragment as
3384 * these blocks must be rolled back to zero before writing the inode.
3385 * We check the currently active set of allocdirects in id_inoupdt.
3387 inodedep = adp->ad_inodedep;
3388 bsize = inodedep->id_fs->fs_bsize;
3389 TAILQ_FOREACH(listadp, &inodedep->id_inoupdt, ad_next) {
3390 /* found our block */
3393 /* continue if ad_oldlbn is not a fragment */
3394 if (listadp->ad_oldsize == 0 ||
3395 listadp->ad_oldsize == bsize)
3397 /* hit a fragment */
3401 * If we have reached the end of the current list without
3402 * finding the just finished dependency, then it must be
3403 * on the future dependency list. Future dependencies cannot
3404 * be freed until they are moved to the current list.
3406 if (listadp == NULL) {
3408 TAILQ_FOREACH(listadp, &inodedep->id_newinoupdt, ad_next)
3409 /* found our block */
3412 if (listadp == NULL)
3413 panic("handle_allocdirect_partdone: lost dep");
3418 * If we have found the just finished dependency, then free
3419 * it along with anything that follows it that is complete.
3421 for (; adp; adp = listadp) {
3422 listadp = TAILQ_NEXT(adp, ad_next);
3423 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3425 free_allocdirect(&inodedep->id_inoupdt, adp, 1);
3430 * Called from within softdep_disk_write_complete above. Note that
3431 * this routine is always called from interrupt level with further
3432 * splbio interrupts blocked.
3435 * aip: the completed allocindir
3438 handle_allocindir_partdone(struct allocindir *aip)
3440 struct indirdep *indirdep;
3442 if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
3444 if (aip->ai_buf != NULL)
3445 panic("handle_allocindir_partdone: dangling dependency");
3447 indirdep = aip->ai_indirdep;
3448 if (indirdep->ir_state & UNDONE) {
3449 LIST_REMOVE(aip, ai_next);
3450 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
3453 ((ufs_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
3455 LIST_REMOVE(aip, ai_next);
3456 if (aip->ai_freefrag != NULL)
3457 add_to_worklist(&aip->ai_freefrag->ff_list);
3458 WORKITEM_FREE(aip, D_ALLOCINDIR);
3462 * Called from within softdep_disk_write_complete above to restore
3463 * in-memory inode block contents to their most up-to-date state. Note
3464 * that this routine is always called from interrupt level with further
3465 * splbio interrupts blocked.
3468 * bp: buffer containing the inode block
3471 handle_written_inodeblock(struct inodedep *inodedep, struct buf *bp)
3473 struct worklist *wk, *filefree;
3474 struct allocdirect *adp, *nextadp;
3475 struct ufs1_dinode *dp;
3478 if ((inodedep->id_state & IOSTARTED) == 0)
3479 panic("handle_written_inodeblock: not started");
3481 inodedep->id_state &= ~IOSTARTED;
3482 dp = (struct ufs1_dinode *)bp->b_data +
3483 ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
3485 * If we had to rollback the inode allocation because of
3486 * bitmaps being incomplete, then simply restore it.
3487 * Keep the block dirty so that it will not be reclaimed until
3488 * all associated dependencies have been cleared and the
3489 * corresponding updates written to disk.
3491 if (inodedep->id_savedino != NULL) {
3492 *dp = *inodedep->id_savedino;
3493 kfree(inodedep->id_savedino, M_INODEDEP);
3494 inodedep->id_savedino = NULL;
3495 if ((bp->b_flags & B_DELWRI) == 0)
3496 stat_inode_bitmap++;
3500 inodedep->id_state |= COMPLETE;
3502 * Roll forward anything that had to be rolled back before
3503 * the inode could be updated.
3506 for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
3507 nextadp = TAILQ_NEXT(adp, ad_next);
3508 if (adp->ad_state & ATTACHED)
3509 panic("handle_written_inodeblock: new entry");
3511 if (adp->ad_lbn < NDADDR) {
3512 if (dp->di_db[adp->ad_lbn] != adp->ad_oldblkno) {
3513 panic("%s: %s #%ld mismatch %d != %d",
3514 "handle_written_inodeblock",
3515 "direct pointer", adp->ad_lbn,
3516 dp->di_db[adp->ad_lbn], adp->ad_oldblkno);
3518 dp->di_db[adp->ad_lbn] = adp->ad_newblkno;
3520 if (dp->di_ib[adp->ad_lbn - NDADDR] != 0) {
3521 panic("%s: %s #%ld allocated as %d",
3522 "handle_written_inodeblock",
3523 "indirect pointer", adp->ad_lbn - NDADDR,
3524 dp->di_ib[adp->ad_lbn - NDADDR]);
3526 dp->di_ib[adp->ad_lbn - NDADDR] = adp->ad_newblkno;
3528 adp->ad_state &= ~UNDONE;
3529 adp->ad_state |= ATTACHED;
3532 if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
3533 stat_direct_blk_ptrs++;
3535 * Reset the file size to its most up-to-date value.
3537 if (inodedep->id_savedsize == -1) {
3538 panic("handle_written_inodeblock: bad size");
3540 if (dp->di_size != inodedep->id_savedsize) {
3541 dp->di_size = inodedep->id_savedsize;
3544 inodedep->id_savedsize = -1;
3546 * If there were any rollbacks in the inode block, then it must be
3547 * marked dirty so that its will eventually get written back in
3553 * Process any allocdirects that completed during the update.
3555 if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
3556 handle_allocdirect_partdone(adp);
3558 * Process deallocations that were held pending until the
3559 * inode had been written to disk. Freeing of the inode
3560 * is delayed until after all blocks have been freed to
3561 * avoid creation of new <vfsid, inum, lbn> triples
3562 * before the old ones have been deleted.
3565 while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
3566 WORKLIST_REMOVE(wk);
3567 switch (wk->wk_type) {
3571 * We defer adding filefree to the worklist until
3572 * all other additions have been made to ensure
3573 * that it will be done after all the old blocks
3576 if (filefree != NULL) {
3577 panic("handle_written_inodeblock: filefree");
3583 handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
3587 diradd_inode_written(WK_DIRADD(wk), inodedep);
3591 wk->wk_state |= COMPLETE;
3592 if ((wk->wk_state & ALLCOMPLETE) != ALLCOMPLETE)
3594 /* -- fall through -- */
3597 add_to_worklist(wk);
3601 panic("handle_written_inodeblock: Unknown type %s",
3602 TYPENAME(wk->wk_type));
3606 if (filefree != NULL) {
3607 if (free_inodedep(inodedep) == 0) {
3608 panic("handle_written_inodeblock: live inodedep");
3610 add_to_worklist(filefree);
3615 * If no outstanding dependencies, free it.
3617 if (free_inodedep(inodedep) || TAILQ_FIRST(&inodedep->id_inoupdt) == 0)
3619 return (hadchanges);
3623 * Process a diradd entry after its dependent inode has been written.
3624 * This routine must be called with splbio interrupts blocked.
3627 diradd_inode_written(struct diradd *dap, struct inodedep *inodedep)
3629 struct pagedep *pagedep;
3631 dap->da_state |= COMPLETE;
3632 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3633 if (dap->da_state & DIRCHG)
3634 pagedep = dap->da_previous->dm_pagedep;
3636 pagedep = dap->da_pagedep;
3637 LIST_REMOVE(dap, da_pdlist);
3638 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3640 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
3644 * Handle the completion of a mkdir dependency.
3647 handle_written_mkdir(struct mkdir *mkdir, int type)
3650 struct pagedep *pagedep;
3652 if (mkdir->md_state != type) {
3653 panic("handle_written_mkdir: bad type");
3655 dap = mkdir->md_diradd;
3656 dap->da_state &= ~type;
3657 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
3658 dap->da_state |= DEPCOMPLETE;
3659 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3660 if (dap->da_state & DIRCHG)
3661 pagedep = dap->da_previous->dm_pagedep;
3663 pagedep = dap->da_pagedep;
3664 LIST_REMOVE(dap, da_pdlist);
3665 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3667 LIST_REMOVE(mkdir, md_mkdirs);
3668 WORKITEM_FREE(mkdir, D_MKDIR);
3672 * Called from within softdep_disk_write_complete above.
3673 * A write operation was just completed. Removed inodes can
3674 * now be freed and associated block pointers may be committed.
3675 * Note that this routine is always called from interrupt level
3676 * with further splbio interrupts blocked.
3679 * bp: buffer containing the written page
3682 handle_written_filepage(struct pagedep *pagedep, struct buf *bp)
3684 struct dirrem *dirrem;
3685 struct diradd *dap, *nextdap;
3689 if ((pagedep->pd_state & IOSTARTED) == 0) {
3690 panic("handle_written_filepage: not started");
3692 pagedep->pd_state &= ~IOSTARTED;
3694 * Process any directory removals that have been committed.
3696 while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
3697 LIST_REMOVE(dirrem, dm_next);
3698 dirrem->dm_dirinum = pagedep->pd_ino;
3699 add_to_worklist(&dirrem->dm_list);
3702 * Free any directory additions that have been committed.
3704 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
3707 * Uncommitted directory entries must be restored.
3709 for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
3710 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
3712 nextdap = LIST_NEXT(dap, da_pdlist);
3713 if (dap->da_state & ATTACHED) {
3714 panic("handle_written_filepage: attached");
3716 ep = (struct direct *)
3717 ((char *)bp->b_data + dap->da_offset);
3718 ep->d_ino = dap->da_newinum;
3719 dap->da_state &= ~UNDONE;
3720 dap->da_state |= ATTACHED;
3723 * If the inode referenced by the directory has
3724 * been written out, then the dependency can be
3725 * moved to the pending list.
3727 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3728 LIST_REMOVE(dap, da_pdlist);
3729 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
3735 * If there were any rollbacks in the directory, then it must be
3736 * marked dirty so that its will eventually get written back in
3740 if ((bp->b_flags & B_DELWRI) == 0)
3745 * If no dependencies remain, the pagedep will be freed.
3746 * Otherwise it will remain to update the page before it
3747 * is written back to disk.
3749 if (LIST_FIRST(&pagedep->pd_pendinghd) == 0) {
3750 for (i = 0; i < DAHASHSZ; i++)
3751 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) != NULL)
3753 if (i == DAHASHSZ) {
3754 LIST_REMOVE(pagedep, pd_hash);
3755 WORKITEM_FREE(pagedep, D_PAGEDEP);
3763 * Writing back in-core inode structures.
3765 * The filesystem only accesses an inode's contents when it occupies an
3766 * "in-core" inode structure. These "in-core" structures are separate from
3767 * the page frames used to cache inode blocks. Only the latter are
3768 * transferred to/from the disk. So, when the updated contents of the
3769 * "in-core" inode structure are copied to the corresponding in-memory inode
3770 * block, the dependencies are also transferred. The following procedure is
3771 * called when copying a dirty "in-core" inode to a cached inode block.
3775 * Called when an inode is loaded from disk. If the effective link count
3776 * differed from the actual link count when it was last flushed, then we
3777 * need to ensure that the correct effective link count is put back.
3780 * ip: the "in_core" copy of the inode
3783 softdep_load_inodeblock(struct inode *ip)
3785 struct inodedep *inodedep;
3788 * Check for alternate nlink count.
3790 ip->i_effnlink = ip->i_nlink;
3792 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3796 ip->i_effnlink -= inodedep->id_nlinkdelta;
3801 * This routine is called just before the "in-core" inode
3802 * information is to be copied to the in-memory inode block.
3803 * Recall that an inode block contains several inodes. If
3804 * the force flag is set, then the dependencies will be
3805 * cleared so that the update can always be made. Note that
3806 * the buffer is locked when this routine is called, so we
3807 * will never be in the middle of writing the inode block
3811 * ip: the "in_core" copy of the inode
3812 * bp: the buffer containing the inode block
3813 * waitfor: nonzero => update must be allowed
3816 softdep_update_inodeblock(struct inode *ip, struct buf *bp,
3819 struct inodedep *inodedep;
3820 struct worklist *wk;
3825 * If the effective link count is not equal to the actual link
3826 * count, then we must track the difference in an inodedep while
3827 * the inode is (potentially) tossed out of the cache. Otherwise,
3828 * if there is no existing inodedep, then there are no dependencies
3832 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3834 if (ip->i_effnlink != ip->i_nlink)
3835 panic("softdep_update_inodeblock: bad link count");
3838 if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink) {
3839 panic("softdep_update_inodeblock: bad delta");
3842 * Changes have been initiated. Anything depending on these
3843 * changes cannot occur until this inode has been written.
3845 inodedep->id_state &= ~COMPLETE;
3846 if ((inodedep->id_state & ONWORKLIST) == 0)
3847 WORKLIST_INSERT_BP(bp, &inodedep->id_list);
3849 * Any new dependencies associated with the incore inode must
3850 * now be moved to the list associated with the buffer holding
3851 * the in-memory copy of the inode. Once merged process any
3852 * allocdirects that are completed by the merger.
3854 merge_inode_lists(inodedep);
3855 if (TAILQ_FIRST(&inodedep->id_inoupdt) != NULL)
3856 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt));
3858 * Now that the inode has been pushed into the buffer, the
3859 * operations dependent on the inode being written to disk
3860 * can be moved to the id_bufwait so that they will be
3861 * processed when the buffer I/O completes.
3863 while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
3864 WORKLIST_REMOVE(wk);
3865 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
3868 * Newly allocated inodes cannot be written until the bitmap
3869 * that allocates them have been written (indicated by
3870 * DEPCOMPLETE being set in id_state). If we are doing a
3871 * forced sync (e.g., an fsync on a file), we force the bitmap
3872 * to be written so that the update can be done.
3879 if ((inodedep->id_state & DEPCOMPLETE) != 0) {
3883 gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
3885 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) != 0)
3890 ibp = inodedep->id_buf;
3892 if ((error = bwrite(ibp)) != 0)
3893 softdep_error("softdep_update_inodeblock: bwrite", error);
3897 * Merge the new inode dependency list (id_newinoupdt) into the old
3898 * inode dependency list (id_inoupdt). This routine must be called
3899 * with splbio interrupts blocked.
3902 merge_inode_lists(struct inodedep *inodedep)
3904 struct allocdirect *listadp, *newadp;
3906 newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3907 for (listadp = TAILQ_FIRST(&inodedep->id_inoupdt); listadp && newadp;) {
3908 if (listadp->ad_lbn < newadp->ad_lbn) {
3909 listadp = TAILQ_NEXT(listadp, ad_next);
3912 TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3913 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
3914 if (listadp->ad_lbn == newadp->ad_lbn) {
3915 allocdirect_merge(&inodedep->id_inoupdt, newadp,
3919 newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3921 while ((newadp = TAILQ_FIRST(&inodedep->id_newinoupdt)) != NULL) {
3922 TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3923 TAILQ_INSERT_TAIL(&inodedep->id_inoupdt, newadp, ad_next);
3928 * If we are doing an fsync, then we must ensure that any directory
3929 * entries for the inode have been written after the inode gets to disk.
3931 * bioops callback - hold io_token
3934 * vp: the "in_core" copy of the inode
3937 softdep_fsync(struct vnode *vp)
3939 struct inodedep *inodedep;
3940 struct pagedep *pagedep;
3941 struct worklist *wk;
3948 int error, flushparent;
3953 * Move check from original kernel code, possibly not needed any
3954 * more with the per-mount bioops.
3956 if ((vp->v_mount->mnt_flag & MNT_SOFTDEP) == 0)
3962 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0) {
3966 if (LIST_FIRST(&inodedep->id_inowait) != NULL ||
3967 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
3968 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
3969 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL) {
3970 panic("softdep_fsync: pending ops");
3972 for (error = 0, flushparent = 0; ; ) {
3973 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
3975 if (wk->wk_type != D_DIRADD) {
3976 panic("softdep_fsync: Unexpected type %s",
3977 TYPENAME(wk->wk_type));
3979 dap = WK_DIRADD(wk);
3981 * Flush our parent if this directory entry
3982 * has a MKDIR_PARENT dependency.
3984 if (dap->da_state & DIRCHG)
3985 pagedep = dap->da_previous->dm_pagedep;
3987 pagedep = dap->da_pagedep;
3988 mnt = pagedep->pd_mnt;
3989 parentino = pagedep->pd_ino;
3990 lbn = pagedep->pd_lbn;
3991 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE) {
3992 panic("softdep_fsync: dirty");
3994 flushparent = dap->da_state & MKDIR_PARENT;
3996 * If we are being fsync'ed as part of vgone'ing this vnode,
3997 * then we will not be able to release and recover the
3998 * vnode below, so we just have to give up on writing its
3999 * directory entry out. It will eventually be written, just
4000 * not now, but then the user was not asking to have it
4001 * written, so we are not breaking any promises.
4003 if (vp->v_flag & VRECLAIMED)
4006 * We prevent deadlock by always fetching inodes from the
4007 * root, moving down the directory tree. Thus, when fetching
4008 * our parent directory, we must unlock ourselves before
4009 * requesting the lock on our parent. See the comment in
4010 * ufs_lookup for details on possible races.
4014 error = VFS_VGET(mnt, NULL, parentino, &pvp);
4015 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4020 if ((error = ffs_update(pvp, 1)) != 0) {
4026 * Flush directory page containing the inode's name.
4028 error = bread(pvp, lblktodoff(fs, lbn), blksize(fs, VTOI(pvp), lbn), &bp);
4036 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0)
4044 * Flush all the dirty bitmaps associated with the block device
4045 * before flushing the rest of the dirty blocks so as to reduce
4046 * the number of dependencies that will have to be rolled back.
4048 static int softdep_fsync_mountdev_bp(struct buf *bp, void *data);
4051 softdep_fsync_mountdev(struct vnode *vp)
4053 if (!vn_isdisk(vp, NULL))
4054 panic("softdep_fsync_mountdev: vnode not a disk");
4056 lwkt_gettoken(&vp->v_token);
4057 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
4058 softdep_fsync_mountdev_bp, vp);
4059 lwkt_reltoken(&vp->v_token);
4060 drain_output(vp, 1);
4065 softdep_fsync_mountdev_bp(struct buf *bp, void *data)
4067 struct worklist *wk;
4068 struct vnode *vp = data;
4071 * If it is already scheduled, skip to the next buffer.
4073 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT))
4075 if (bp->b_vp != vp || (bp->b_flags & B_DELWRI) == 0) {
4077 kprintf("softdep_fsync_mountdev_bp: warning, buffer %p ripped out from under vnode %p\n", bp, vp);
4081 * We are only interested in bitmaps with outstanding
4084 if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
4085 wk->wk_type != D_BMSAFEMAP) {
4097 * This routine is called when we are trying to synchronously flush a
4098 * file. This routine must eliminate any filesystem metadata dependencies
4099 * so that the syncing routine can succeed by pushing the dirty blocks
4100 * associated with the file. If any I/O errors occur, they are returned.
4102 struct softdep_sync_metadata_info {
4107 static int softdep_sync_metadata_bp(struct buf *bp, void *data);
4110 softdep_sync_metadata(struct vnode *vp, struct thread *td)
4112 struct softdep_sync_metadata_info info;
4116 * Check whether this vnode is involved in a filesystem
4117 * that is doing soft dependency processing.
4119 if (!vn_isdisk(vp, NULL)) {
4120 if (!DOINGSOFTDEP(vp))
4123 if (vp->v_rdev->si_mountpoint == NULL ||
4124 (vp->v_rdev->si_mountpoint->mnt_flag & MNT_SOFTDEP) == 0)
4127 * Ensure that any direct block dependencies have been cleared.
4130 if ((error = flush_inodedep_deps(VTOI(vp)->i_fs, VTOI(vp)->i_number))) {
4135 * For most files, the only metadata dependencies are the
4136 * cylinder group maps that allocate their inode or blocks.
4137 * The block allocation dependencies can be found by traversing
4138 * the dependency lists for any buffers that remain on their
4139 * dirty buffer list. The inode allocation dependency will
4140 * be resolved when the inode is updated with MNT_WAIT.
4141 * This work is done in two passes. The first pass grabs most
4142 * of the buffers and begins asynchronously writing them. The
4143 * only way to wait for these asynchronous writes is to sleep
4144 * on the filesystem vnode which may stay busy for a long time
4145 * if the filesystem is active. So, instead, we make a second
4146 * pass over the dependencies blocking on each write. In the
4147 * usual case we will be blocking against a write that we
4148 * initiated, so when it is done the dependency will have been
4149 * resolved. Thus the second pass is expected to end quickly.
4151 waitfor = MNT_NOWAIT;
4154 * We must wait for any I/O in progress to finish so that
4155 * all potential buffers on the dirty list will be visible.
4157 drain_output(vp, 1);
4160 info.waitfor = waitfor;
4161 lwkt_gettoken(&vp->v_token);
4162 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
4163 softdep_sync_metadata_bp, &info);
4164 lwkt_reltoken(&vp->v_token);
4167 return(-error); /* error code */
4171 * The brief unlock is to allow any pent up dependency
4172 * processing to be done. Then proceed with the second pass.
4174 if (waitfor & MNT_NOWAIT) {
4182 * If we have managed to get rid of all the dirty buffers,
4183 * then we are done. For certain directories and block
4184 * devices, we may need to do further work.
4186 * We must wait for any I/O in progress to finish so that
4187 * all potential buffers on the dirty list will be visible.
4189 drain_output(vp, 1);
4190 if (RB_EMPTY(&vp->v_rbdirty_tree)) {
4197 * If we are trying to sync a block device, some of its buffers may
4198 * contain metadata that cannot be written until the contents of some
4199 * partially written files have been written to disk. The only easy
4200 * way to accomplish this is to sync the entire filesystem (luckily
4201 * this happens rarely).
4203 if (vn_isdisk(vp, NULL) &&
4205 vp->v_rdev->si_mountpoint && !vn_islocked(vp) &&
4206 (error = VFS_SYNC(vp->v_rdev->si_mountpoint, MNT_WAIT)) != 0)
4212 softdep_sync_metadata_bp(struct buf *bp, void *data)
4214 struct softdep_sync_metadata_info *info = data;
4215 struct pagedep *pagedep;
4216 struct allocdirect *adp;
4217 struct allocindir *aip;
4218 struct worklist *wk;
4223 if (getdirtybuf(&bp, MNT_WAIT) == 0) {
4224 kprintf("softdep_sync_metadata_bp(1): caught buf %p going away\n", bp);
4227 if (bp->b_vp != info->vp || (bp->b_flags & B_DELWRI) == 0) {
4228 kprintf("softdep_sync_metadata_bp(2): caught buf %p going away vp %p\n", bp, info->vp);
4234 * As we hold the buffer locked, none of its dependencies
4237 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4238 switch (wk->wk_type) {
4241 adp = WK_ALLOCDIRECT(wk);
4242 if (adp->ad_state & DEPCOMPLETE)
4245 if (getdirtybuf(&nbp, info->waitfor) == 0)
4248 if (info->waitfor & MNT_NOWAIT) {
4250 } else if ((error = bwrite(nbp)) != 0) {
4259 aip = WK_ALLOCINDIR(wk);
4260 if (aip->ai_state & DEPCOMPLETE)
4263 if (getdirtybuf(&nbp, info->waitfor) == 0)
4266 if (info->waitfor & MNT_NOWAIT) {
4268 } else if ((error = bwrite(nbp)) != 0) {
4279 LIST_FOREACH(aip, &WK_INDIRDEP(wk)->ir_deplisthd, ai_next) {
4280 if (aip->ai_state & DEPCOMPLETE)
4283 if (getdirtybuf(&nbp, MNT_WAIT) == 0)
4286 if ((error = bwrite(nbp)) != 0) {
4297 if ((error = flush_inodedep_deps(WK_INODEDEP(wk)->id_fs,
4298 WK_INODEDEP(wk)->id_ino)) != 0) {
4308 * We are trying to sync a directory that may
4309 * have dependencies on both its own metadata
4310 * and/or dependencies on the inodes of any
4311 * recently allocated files. We walk its diradd
4312 * lists pushing out the associated inode.
4314 pagedep = WK_PAGEDEP(wk);
4315 for (i = 0; i < DAHASHSZ; i++) {
4316 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
4319 flush_pagedep_deps(info->vp,
4321 &pagedep->pd_diraddhd[i]))) {
4332 * This case should never happen if the vnode has
4333 * been properly sync'ed. However, if this function
4334 * is used at a place where the vnode has not yet
4335 * been sync'ed, this dependency can show up. So,
4336 * rather than panic, just flush it.
4338 nbp = WK_MKDIR(wk)->md_buf;
4339 if (getdirtybuf(&nbp, info->waitfor) == 0)
4342 if (info->waitfor & MNT_NOWAIT) {
4344 } else if ((error = bwrite(nbp)) != 0) {
4354 * This case should never happen if the vnode has
4355 * been properly sync'ed. However, if this function
4356 * is used at a place where the vnode has not yet
4357 * been sync'ed, this dependency can show up. So,
4358 * rather than panic, just flush it.
4360 * nbp can wind up == bp if a device node for the
4361 * same filesystem is being fsynced at the same time,
4362 * leading to a panic if we don't catch the case.
4364 nbp = WK_BMSAFEMAP(wk)->sm_buf;
4367 if (getdirtybuf(&nbp, info->waitfor) == 0)
4370 if (info->waitfor & MNT_NOWAIT) {
4372 } else if ((error = bwrite(nbp)) != 0) {
4381 panic("softdep_sync_metadata: Unknown type %s",
4382 TYPENAME(wk->wk_type));
4393 * Flush the dependencies associated with an inodedep.
4394 * Called with splbio blocked.
4397 flush_inodedep_deps(struct fs *fs, ino_t ino)
4399 struct inodedep *inodedep;
4400 struct allocdirect *adp;
4405 * This work is done in two passes. The first pass grabs most
4406 * of the buffers and begins asynchronously writing them. The
4407 * only way to wait for these asynchronous writes is to sleep
4408 * on the filesystem vnode which may stay busy for a long time
4409 * if the filesystem is active. So, instead, we make a second
4410 * pass over the dependencies blocking on each write. In the
4411 * usual case we will be blocking against a write that we
4412 * initiated, so when it is done the dependency will have been
4413 * resolved. Thus the second pass is expected to end quickly.
4414 * We give a brief window at the top of the loop to allow
4415 * any pending I/O to complete.
4417 for (waitfor = MNT_NOWAIT; ; ) {
4420 if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4422 TAILQ_FOREACH(adp, &inodedep->id_inoupdt, ad_next) {
4423 if (adp->ad_state & DEPCOMPLETE)
4426 if (getdirtybuf(&bp, waitfor) == 0) {
4427 if (waitfor & MNT_NOWAIT)
4432 if (waitfor & MNT_NOWAIT) {
4434 } else if ((error = bwrite(bp)) != 0) {
4443 TAILQ_FOREACH(adp, &inodedep->id_newinoupdt, ad_next) {
4444 if (adp->ad_state & DEPCOMPLETE)
4447 if (getdirtybuf(&bp, waitfor) == 0) {
4448 if (waitfor & MNT_NOWAIT)
4453 if (waitfor & MNT_NOWAIT) {
4455 } else if ((error = bwrite(bp)) != 0) {
4465 * If pass2, we are done, otherwise do pass 2.
4467 if (waitfor == MNT_WAIT)
4472 * Try freeing inodedep in case all dependencies have been removed.
4474 if (inodedep_lookup(fs, ino, 0, &inodedep) != 0)
4475 (void) free_inodedep(inodedep);
4480 * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
4481 * Called with splbio blocked.
4484 flush_pagedep_deps(struct vnode *pvp, struct mount *mp,
4485 struct diraddhd *diraddhdp)
4487 struct inodedep *inodedep;
4488 struct ufsmount *ump;
4491 int gotit, error = 0;
4496 while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
4498 * Flush ourselves if this directory entry
4499 * has a MKDIR_PARENT dependency.
4501 if (dap->da_state & MKDIR_PARENT) {
4503 if ((error = ffs_update(pvp, 1)) != 0)
4507 * If that cleared dependencies, go on to next.
4509 if (dap != LIST_FIRST(diraddhdp))
4511 if (dap->da_state & MKDIR_PARENT) {
4512 panic("flush_pagedep_deps: MKDIR_PARENT");
4516 * A newly allocated directory must have its "." and
4517 * ".." entries written out before its name can be
4518 * committed in its parent. We do not want or need
4519 * the full semantics of a synchronous VOP_FSYNC as
4520 * that may end up here again, once for each directory
4521 * level in the filesystem. Instead, we push the blocks
4522 * and wait for them to clear. We have to fsync twice
4523 * because the first call may choose to defer blocks
4524 * that still have dependencies, but deferral will
4525 * happen at most once.
4527 inum = dap->da_newinum;
4528 if (dap->da_state & MKDIR_BODY) {
4530 if ((error = VFS_VGET(mp, NULL, inum, &vp)) != 0)
4532 if ((error=VOP_FSYNC(vp, MNT_NOWAIT, 0)) ||
4533 (error=VOP_FSYNC(vp, MNT_NOWAIT, 0))) {
4537 drain_output(vp, 0);
4541 * If that cleared dependencies, go on to next.
4543 if (dap != LIST_FIRST(diraddhdp))
4545 if (dap->da_state & MKDIR_BODY) {
4546 panic("flush_pagedep_deps: MKDIR_BODY");
4550 * Flush the inode on which the directory entry depends.
4551 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
4552 * the only remaining dependency is that the updated inode
4553 * count must get pushed to disk. The inode has already
4554 * been pushed into its inode buffer (via VOP_UPDATE) at
4555 * the time of the reference count change. So we need only
4556 * locate that buffer, ensure that there will be no rollback
4557 * caused by a bitmap dependency, then write the inode buffer.
4559 if (inodedep_lookup(ump->um_fs, inum, 0, &inodedep) == 0) {
4560 panic("flush_pagedep_deps: lost inode");
4563 * If the inode still has bitmap dependencies,
4564 * push them to disk.
4566 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4567 gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
4569 if (gotit && (error = bwrite(inodedep->id_buf)) != 0)
4572 if (dap != LIST_FIRST(diraddhdp))
4576 * If the inode is still sitting in a buffer waiting
4577 * to be written, push it to disk.
4580 if ((error = bread(ump->um_devvp,
4581 fsbtodoff(ump->um_fs, ino_to_fsba(ump->um_fs, inum)),
4582 (int)ump->um_fs->fs_bsize, &bp)) != 0)
4584 if ((error = bwrite(bp)) != 0)
4588 * If we have failed to get rid of all the dependencies
4589 * then something is seriously wrong.
4591 if (dap == LIST_FIRST(diraddhdp)) {
4592 panic("flush_pagedep_deps: flush failed");
4601 * A large burst of file addition or deletion activity can drive the
4602 * memory load excessively high. First attempt to slow things down
4603 * using the techniques below. If that fails, this routine requests
4604 * the offending operations to fall back to running synchronously
4605 * until the memory load returns to a reasonable level.
4608 softdep_slowdown(struct vnode *vp)
4610 int max_softdeps_hard;
4612 max_softdeps_hard = max_softdeps * 11 / 10;
4613 if (num_dirrem < max_softdeps_hard / 2 &&
4614 num_inodedep < max_softdeps_hard)
4616 stat_sync_limit_hit += 1;
4621 * If memory utilization has gotten too high, deliberately slow things
4622 * down and speed up the I/O processing.
4625 request_cleanup(int resource, int islocked)
4627 struct thread *td = curthread; /* XXX */
4630 * We never hold up the filesystem syncer process.
4632 if (td == filesys_syncer)
4635 * First check to see if the work list has gotten backlogged.
4636 * If it has, co-opt this process to help clean up two entries.
4637 * Because this process may hold inodes locked, we cannot
4638 * handle any remove requests that might block on a locked
4639 * inode as that could lead to deadlock.
4641 if (num_on_worklist > max_softdeps / 10) {
4642 process_worklist_item(NULL, LK_NOWAIT);
4643 process_worklist_item(NULL, LK_NOWAIT);
4644 stat_worklist_push += 2;
4649 * If we are resource constrained on inode dependencies, try
4650 * flushing some dirty inodes. Otherwise, we are constrained
4651 * by file deletions, so try accelerating flushes of directories
4652 * with removal dependencies. We would like to do the cleanup
4653 * here, but we probably hold an inode locked at this point and
4654 * that might deadlock against one that we try to clean. So,
4655 * the best that we can do is request the syncer daemon to do
4656 * the cleanup for us.
4661 stat_ino_limit_push += 1;
4662 req_clear_inodedeps += 1;
4663 stat_countp = &stat_ino_limit_hit;
4667 stat_blk_limit_push += 1;
4668 req_clear_remove += 1;
4669 stat_countp = &stat_blk_limit_hit;
4673 panic("request_cleanup: unknown type");
4676 * Hopefully the syncer daemon will catch up and awaken us.
4677 * We wait at most tickdelay before proceeding in any case.
4681 lksleep(&proc_waiting, &lk, 0, "softupdate",
4682 tickdelay > 2 ? tickdelay : 2);
4689 * Flush out a directory with at least one removal dependency in an effort to
4690 * reduce the number of dirrem, freefile, and freeblks dependency structures.
4693 clear_remove(struct thread *td)
4695 struct pagedep_hashhead *pagedephd;
4696 struct pagedep *pagedep;
4697 static int next = 0;
4704 for (cnt = 0; cnt < pagedep_hash; cnt++) {
4705 pagedephd = &pagedep_hashtbl[next++];
4706 if (next >= pagedep_hash)
4708 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
4709 if (LIST_FIRST(&pagedep->pd_dirremhd) == NULL)
4711 mp = pagedep->pd_mnt;
4712 ino = pagedep->pd_ino;
4714 if ((error = VFS_VGET(mp, NULL, ino, &vp)) != 0) {
4715 softdep_error("clear_remove: vget", error);
4718 if ((error = VOP_FSYNC(vp, MNT_NOWAIT, 0)))
4719 softdep_error("clear_remove: fsync", error);
4720 drain_output(vp, 0);
4729 * Clear out a block of dirty inodes in an effort to reduce
4730 * the number of inodedep dependency structures.
4732 struct clear_inodedeps_info {
4738 clear_inodedeps_mountlist_callback(struct mount *mp, void *data)
4740 struct clear_inodedeps_info *info = data;
4742 if ((mp->mnt_flag & MNT_SOFTDEP) && info->fs == VFSTOUFS(mp)->um_fs) {
4750 clear_inodedeps(struct thread *td)
4752 struct clear_inodedeps_info info;
4753 struct inodedep_hashhead *inodedephd;
4754 struct inodedep *inodedep;
4755 static int next = 0;
4759 ino_t firstino, lastino, ino;
4763 * Pick a random inode dependency to be cleared.
4764 * We will then gather up all the inodes in its block
4765 * that have dependencies and flush them out.
4767 for (cnt = 0; cnt < inodedep_hash; cnt++) {
4768 inodedephd = &inodedep_hashtbl[next++];
4769 if (next >= inodedep_hash)
4771 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
4774 if (inodedep == NULL) {
4779 * Ugly code to find mount point given pointer to superblock.
4781 fs = inodedep->id_fs;
4784 mountlist_scan(clear_inodedeps_mountlist_callback,
4785 &info, MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
4787 * Find the last inode in the block with dependencies.
4789 firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
4790 for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
4791 if (inodedep_lookup(fs, lastino, 0, &inodedep) != 0)
4794 * Asynchronously push all but the last inode with dependencies.
4795 * Synchronously push the last inode with dependencies to ensure
4796 * that the inode block gets written to free up the inodedeps.
4798 for (ino = firstino; ino <= lastino; ino++) {
4799 if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4802 if ((error = VFS_VGET(info.mp, NULL, ino, &vp)) != 0) {
4803 softdep_error("clear_inodedeps: vget", error);
4806 if (ino == lastino) {
4807 if ((error = VOP_FSYNC(vp, MNT_WAIT, 0)))
4808 softdep_error("clear_inodedeps: fsync1", error);
4810 if ((error = VOP_FSYNC(vp, MNT_NOWAIT, 0)))
4811 softdep_error("clear_inodedeps: fsync2", error);
4812 drain_output(vp, 0);
4821 * Function to determine if the buffer has outstanding dependencies
4822 * that will cause a roll-back if the buffer is written. If wantcount
4823 * is set, return number of dependencies, otherwise just yes or no.
4825 * bioops callback - hold io_token
4828 softdep_count_dependencies(struct buf *bp, int wantcount)
4830 struct worklist *wk;
4831 struct inodedep *inodedep;
4832 struct indirdep *indirdep;
4833 struct allocindir *aip;
4834 struct pagedep *pagedep;
4841 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4842 switch (wk->wk_type) {
4845 inodedep = WK_INODEDEP(wk);
4846 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4847 /* bitmap allocation dependency */
4852 if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
4853 /* direct block pointer dependency */
4861 indirdep = WK_INDIRDEP(wk);
4863 LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
4864 /* indirect block pointer dependency */
4872 pagedep = WK_PAGEDEP(wk);
4873 for (i = 0; i < DAHASHSZ; i++) {
4875 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
4876 /* directory entry dependency */
4888 /* never a dependency on these blocks */
4892 panic("softdep_check_for_rollback: Unexpected type %s",
4893 TYPENAME(wk->wk_type));
4906 * Acquire exclusive access to a buffer. Requires softdep lock
4907 * to be held on entry. If waitfor is MNT_WAIT, may release/reacquire
4910 * Returns 1 if the buffer was locked, 0 otherwise.
4913 getdirtybuf(struct buf **bpp, int waitfor)
4923 /* Must acquire buffer lock with ffs_softdep lock held */
4924 KKASSERT(lock_held(&lk) > 0);
4925 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT);
4929 if (waitfor != MNT_WAIT)
4933 * Release ffs_softdep lock around sleep/wait for buffer lock.
4935 * We must acquire buffer lock with softdep lock held, so
4936 * we must retry locking the buffer after we wake.
4939 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL);
4943 else if (error == ENOLCK)
4946 panic("getdirtybuf: Inconsistent lock");
4949 /* Buffer wasn't dirty */
4950 if ((bp->b_flags & B_DELWRI) == 0) {
4959 * Wait for pending output on a vnode to complete.
4960 * Must be called with vnode locked.
4963 drain_output(struct vnode *vp, int islocked)
4968 while (bio_track_active(&vp->v_track_write)) {
4970 bio_track_wait(&vp->v_track_write, 0, 0);
4978 * Called whenever a buffer that is being invalidated or reallocated
4979 * contains dependencies. This should only happen if an I/O error has
4980 * occurred. The routine is called with the buffer locked.
4982 * bioops callback - hold io_token
4985 softdep_deallocate_dependencies(struct buf *bp)
4987 /* nothing to do, mp lock not needed */
4988 if ((bp->b_flags & B_ERROR) == 0)
4989 panic("softdep_deallocate_dependencies: dangling deps");
4990 softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntfromname, bp->b_error);
4991 panic("softdep_deallocate_dependencies: unrecovered I/O error");
4995 * Function to handle asynchronous write errors in the filesystem.
4998 softdep_error(char *func, int error)
5000 /* XXX should do something better! */
5001 kprintf("%s: got error %d while accessing filesystem\n", func, error);