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 void pause_timer(void *);
193 static int request_cleanup(int, int);
194 static int process_worklist_item(struct mount *, int);
195 static void add_to_worklist(struct worklist *);
198 * Exported softdep operations.
200 static void softdep_disk_io_initiation(struct buf *);
201 static void softdep_disk_write_complete(struct buf *);
202 static void softdep_deallocate_dependencies(struct buf *);
203 static int softdep_fsync(struct vnode *);
204 static int softdep_process_worklist(struct mount *);
205 static void softdep_move_dependencies(struct buf *, struct buf *);
206 static int softdep_count_dependencies(struct buf *bp, int);
207 static int softdep_checkread(struct buf *bp);
208 static int softdep_checkwrite(struct buf *bp);
210 static struct bio_ops softdep_bioops = {
211 .io_start = softdep_disk_io_initiation,
212 .io_complete = softdep_disk_write_complete,
213 .io_deallocate = softdep_deallocate_dependencies,
214 .io_fsync = softdep_fsync,
215 .io_sync = softdep_process_worklist,
216 .io_movedeps = softdep_move_dependencies,
217 .io_countdeps = softdep_count_dependencies,
218 .io_checkread = softdep_checkread,
219 .io_checkwrite = softdep_checkwrite
223 * Locking primitives.
225 static void acquire_lock(struct lock *);
226 static void free_lock(struct lock *);
228 static int lock_held(struct lock *);
230 static int interlocked_sleep(struct lock *, void *, int,
233 static struct lock lk;
235 #define ACQUIRE_LOCK(lkp) acquire_lock(lkp)
236 #define FREE_LOCK(lkp) free_lock(lkp)
239 acquire_lock(struct lock *lkp)
241 lockmgr(lkp, LK_EXCLUSIVE);
245 free_lock(struct lock *lkp)
247 lockmgr(lkp, LK_RELEASE);
252 lock_held(struct lock *lkp)
254 return lockcountnb(lkp);
259 interlocked_sleep(struct lock *lkp, void *ident, int flags,
260 const char *wmesg, int timo)
264 KKASSERT(lock_held(lkp) > 0);
265 retval = lksleep(ident, lkp, flags, wmesg, timo);
270 * Place holder for real semaphores.
279 static void sema_init(struct sema *, char *, int, int);
280 static int sema_get(struct sema *, struct lock *);
281 static void sema_release(struct sema *);
283 #define NOHOLDER ((struct thread *) -1)
286 sema_init(struct sema *semap, char *name, int prio, int timo)
289 semap->holder = NOHOLDER;
297 sema_get(struct sema *semap, struct lock *interlock)
300 if (semap->value++ > 0) {
301 if (interlock != NULL) {
302 interlocked_sleep(interlock, (caddr_t)semap,
303 semap->prio, semap->name, semap->timo);
304 FREE_LOCK(interlock);
306 tsleep((caddr_t)semap, semap->prio, semap->name,
311 semap->holder = curthread;
312 if (interlock != NULL)
313 FREE_LOCK(interlock);
318 sema_release(struct sema *semap)
321 if (semap->value <= 0 || semap->holder != curthread) {
322 panic("sema_release: not held");
324 if (--semap->value > 0) {
328 semap->holder = NOHOLDER;
332 * Worklist queue management.
333 * These routines require that the lock be held.
335 static void worklist_insert(struct workhead *, struct worklist *);
336 static void worklist_remove(struct worklist *);
337 static void workitem_free(struct worklist *, int);
339 #define WORKLIST_INSERT_BP(bp, item) do { \
340 (bp)->b_ops = &softdep_bioops; \
341 worklist_insert(&(bp)->b_dep, item); \
344 #define WORKLIST_INSERT(head, item) worklist_insert(head, item)
345 #define WORKLIST_REMOVE(item) worklist_remove(item)
346 #define WORKITEM_FREE(item, type) workitem_free((struct worklist *)item, type)
349 worklist_insert(struct workhead *head, struct worklist *item)
352 KKASSERT(lock_held(&lk) > 0);
354 if (item->wk_state & ONWORKLIST) {
355 panic("worklist_insert: already on list");
357 item->wk_state |= ONWORKLIST;
358 LIST_INSERT_HEAD(head, item, wk_list);
362 worklist_remove(struct worklist *item)
365 KKASSERT(lock_held(&lk));
366 if ((item->wk_state & ONWORKLIST) == 0)
367 panic("worklist_remove: not on list");
369 item->wk_state &= ~ONWORKLIST;
370 LIST_REMOVE(item, wk_list);
374 workitem_free(struct worklist *item, int type)
377 if (item->wk_state & ONWORKLIST)
378 panic("workitem_free: still on list");
379 if (item->wk_type != type)
380 panic("workitem_free: type mismatch");
382 kfree(item, DtoM(type));
386 * Workitem queue management
388 static struct workhead softdep_workitem_pending;
389 static int num_on_worklist; /* number of worklist items to be processed */
390 static int softdep_worklist_busy; /* 1 => trying to do unmount */
391 static int softdep_worklist_req; /* serialized waiters */
392 static int max_softdeps; /* maximum number of structs before slowdown */
393 static int tickdelay = 2; /* number of ticks to pause during slowdown */
394 static int *stat_countp; /* statistic to count in proc_waiting timeout */
395 static int proc_waiting; /* tracks whether we have a timeout posted */
396 static struct callout handle; /* handle on posted proc_waiting timeout */
397 static struct thread *filesys_syncer; /* proc of filesystem syncer process */
398 static int req_clear_inodedeps; /* syncer process flush some inodedeps */
399 #define FLUSH_INODES 1
400 static int req_clear_remove; /* syncer process flush some freeblks */
401 #define FLUSH_REMOVE 2
405 static int stat_worklist_push; /* number of worklist cleanups */
406 static int stat_blk_limit_push; /* number of times block limit neared */
407 static int stat_ino_limit_push; /* number of times inode limit neared */
408 static int stat_blk_limit_hit; /* number of times block slowdown imposed */
409 static int stat_ino_limit_hit; /* number of times inode slowdown imposed */
410 static int stat_sync_limit_hit; /* number of synchronous slowdowns imposed */
411 static int stat_indir_blk_ptrs; /* bufs redirtied as indir ptrs not written */
412 static int stat_inode_bitmap; /* bufs redirtied as inode bitmap not written */
413 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
414 static int stat_dir_entry; /* bufs redirtied as dir entry cannot write */
417 #include <sys/sysctl.h>
418 SYSCTL_INT(_debug, OID_AUTO, max_softdeps, CTLFLAG_RW, &max_softdeps, 0,
419 "Maximum soft dependencies before slowdown occurs");
420 SYSCTL_INT(_debug, OID_AUTO, tickdelay, CTLFLAG_RW, &tickdelay, 0,
421 "Ticks to delay before allocating during slowdown");
422 SYSCTL_INT(_debug, OID_AUTO, worklist_push, CTLFLAG_RW, &stat_worklist_push, 0,
423 "Number of worklist cleanups");
424 SYSCTL_INT(_debug, OID_AUTO, blk_limit_push, CTLFLAG_RW, &stat_blk_limit_push, 0,
425 "Number of times block limit neared");
426 SYSCTL_INT(_debug, OID_AUTO, ino_limit_push, CTLFLAG_RW, &stat_ino_limit_push, 0,
427 "Number of times inode limit neared");
428 SYSCTL_INT(_debug, OID_AUTO, blk_limit_hit, CTLFLAG_RW, &stat_blk_limit_hit, 0,
429 "Number of times block slowdown imposed");
430 SYSCTL_INT(_debug, OID_AUTO, ino_limit_hit, CTLFLAG_RW, &stat_ino_limit_hit, 0,
431 "Number of times inode slowdown imposed ");
432 SYSCTL_INT(_debug, OID_AUTO, sync_limit_hit, CTLFLAG_RW, &stat_sync_limit_hit, 0,
433 "Number of synchronous slowdowns imposed");
434 SYSCTL_INT(_debug, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW, &stat_indir_blk_ptrs, 0,
435 "Bufs redirtied as indir ptrs not written");
436 SYSCTL_INT(_debug, OID_AUTO, inode_bitmap, CTLFLAG_RW, &stat_inode_bitmap, 0,
437 "Bufs redirtied as inode bitmap not written");
438 SYSCTL_INT(_debug, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW, &stat_direct_blk_ptrs, 0,
439 "Bufs redirtied as direct ptrs not written");
440 SYSCTL_INT(_debug, OID_AUTO, dir_entry, CTLFLAG_RW, &stat_dir_entry, 0,
441 "Bufs redirtied as dir entry cannot write");
445 * Add an item to the end of the work queue.
446 * This routine requires that the lock be held.
447 * This is the only routine that adds items to the list.
448 * The following routine is the only one that removes items
449 * and does so in order from first to last.
452 add_to_worklist(struct worklist *wk)
454 static struct worklist *worklist_tail;
456 if (wk->wk_state & ONWORKLIST) {
457 panic("add_to_worklist: already on list");
459 wk->wk_state |= ONWORKLIST;
460 if (LIST_FIRST(&softdep_workitem_pending) == NULL)
461 LIST_INSERT_HEAD(&softdep_workitem_pending, wk, wk_list);
463 LIST_INSERT_AFTER(worklist_tail, wk, wk_list);
465 num_on_worklist += 1;
469 * Process that runs once per second to handle items in the background queue.
471 * Note that we ensure that everything is done in the order in which they
472 * appear in the queue. The code below depends on this property to ensure
473 * that blocks of a file are freed before the inode itself is freed. This
474 * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
475 * until all the old ones have been purged from the dependency lists.
477 * bioops callback - hold io_token
480 softdep_process_worklist(struct mount *matchmnt)
482 thread_t td = curthread;
483 int matchcnt, loopcount;
489 * Record the process identifier of our caller so that we can give
490 * this process preferential treatment in request_cleanup below.
496 * There is no danger of having multiple processes run this
497 * code, but we have to single-thread it when softdep_flushfiles()
498 * is in operation to get an accurate count of the number of items
499 * related to its mount point that are in the list.
501 if (matchmnt == NULL) {
502 if (softdep_worklist_busy < 0) {
506 softdep_worklist_busy += 1;
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 starttime = time_second;
524 while (num_on_worklist > 0) {
525 matchcnt += process_worklist_item(matchmnt, 0);
528 * If a umount operation wants to run the worklist
531 if (softdep_worklist_req && matchmnt == NULL) {
537 * If requested, try removing inode or removal dependencies.
539 if (req_clear_inodedeps) {
541 req_clear_inodedeps -= 1;
542 wakeup_one(&proc_waiting);
544 if (req_clear_remove) {
546 req_clear_remove -= 1;
547 wakeup_one(&proc_waiting);
550 * We do not generally want to stop for buffer space, but if
551 * we are really being a buffer hog, we will stop and wait.
553 if (loopcount++ % 128 == 0) {
560 * Never allow processing to run for more than one
561 * second. Otherwise the other syncer tasks may get
562 * excessively backlogged.
564 if (starttime != time_second && matchmnt == NULL) {
569 if (matchmnt == NULL) {
570 --softdep_worklist_busy;
571 if (softdep_worklist_req && softdep_worklist_busy == 0)
572 wakeup(&softdep_worklist_req);
580 * Process one item on the worklist.
583 process_worklist_item(struct mount *matchmnt, int flags)
586 struct dirrem *dirrem;
592 if (matchmnt != NULL)
593 matchfs = VFSTOUFS(matchmnt)->um_fs;
596 * Normally we just process each item on the worklist in order.
597 * However, if we are in a situation where we cannot lock any
598 * inodes, we have to skip over any dirrem requests whose
599 * vnodes are resident and locked.
601 LIST_FOREACH(wk, &softdep_workitem_pending, wk_list) {
602 if ((flags & LK_NOWAIT) == 0 || wk->wk_type != D_DIRREM)
604 dirrem = WK_DIRREM(wk);
605 vp = ufs_ihashlookup(VFSTOUFS(dirrem->dm_mnt)->um_dev,
607 if (vp == NULL || !vn_islocked(vp))
614 num_on_worklist -= 1;
616 switch (wk->wk_type) {
618 /* removal of a directory entry */
619 if (WK_DIRREM(wk)->dm_mnt == matchmnt)
621 handle_workitem_remove(WK_DIRREM(wk));
625 /* releasing blocks and/or fragments from a file */
626 if (WK_FREEBLKS(wk)->fb_fs == matchfs)
628 handle_workitem_freeblocks(WK_FREEBLKS(wk));
632 /* releasing a fragment when replaced as a file grows */
633 if (WK_FREEFRAG(wk)->ff_fs == matchfs)
635 handle_workitem_freefrag(WK_FREEFRAG(wk));
639 /* releasing an inode when its link count drops to 0 */
640 if (WK_FREEFILE(wk)->fx_fs == matchfs)
642 handle_workitem_freefile(WK_FREEFILE(wk));
646 panic("%s_process_worklist: Unknown type %s",
647 "softdep", TYPENAME(wk->wk_type));
655 * Move dependencies from one buffer to another.
657 * bioops callback - hold io_token
660 softdep_move_dependencies(struct buf *oldbp, struct buf *newbp)
662 struct worklist *wk, *wktail;
664 if (LIST_FIRST(&newbp->b_dep) != NULL)
665 panic("softdep_move_dependencies: need merge code");
668 while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
669 LIST_REMOVE(wk, wk_list);
671 LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
673 LIST_INSERT_AFTER(wktail, wk, wk_list);
675 newbp->b_ops = &softdep_bioops;
681 * Purge the work list of all items associated with a particular mount point.
684 softdep_flushfiles(struct mount *oldmnt, int flags)
690 * Await our turn to clear out the queue, then serialize access.
693 while (softdep_worklist_busy != 0) {
694 softdep_worklist_req += 1;
695 lksleep(&softdep_worklist_req, &lk, 0, "softflush", 0);
696 softdep_worklist_req -= 1;
698 softdep_worklist_busy = -1;
701 if ((error = ffs_flushfiles(oldmnt, flags)) != 0) {
702 softdep_worklist_busy = 0;
703 if (softdep_worklist_req)
704 wakeup(&softdep_worklist_req);
708 * Alternately flush the block device associated with the mount
709 * point and process any dependencies that the flushing
710 * creates. In theory, this loop can happen at most twice,
711 * but we give it a few extra just to be sure.
713 devvp = VFSTOUFS(oldmnt)->um_devvp;
714 for (loopcnt = 10; loopcnt > 0; ) {
715 if (softdep_process_worklist(oldmnt) == 0) {
718 * Do another flush in case any vnodes were brought in
719 * as part of the cleanup operations.
721 if ((error = ffs_flushfiles(oldmnt, flags)) != 0)
724 * If we still found nothing to do, we are really done.
726 if (softdep_process_worklist(oldmnt) == 0)
729 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
730 error = VOP_FSYNC(devvp, MNT_WAIT, 0);
736 softdep_worklist_busy = 0;
737 if (softdep_worklist_req)
738 wakeup(&softdep_worklist_req);
742 * If we are unmounting then it is an error to fail. If we
743 * are simply trying to downgrade to read-only, then filesystem
744 * activity can keep us busy forever, so we just fail with EBUSY.
747 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
748 panic("softdep_flushfiles: looping");
757 * There are three types of structures that can be looked up:
758 * 1) pagedep structures identified by mount point, inode number,
760 * 2) inodedep structures identified by mount point and inode number.
761 * 3) newblk structures identified by mount point and
762 * physical block number.
764 * The "pagedep" and "inodedep" dependency structures are hashed
765 * separately from the file blocks and inodes to which they correspond.
766 * This separation helps when the in-memory copy of an inode or
767 * file block must be replaced. It also obviates the need to access
768 * an inode or file page when simply updating (or de-allocating)
769 * dependency structures. Lookup of newblk structures is needed to
770 * find newly allocated blocks when trying to associate them with
771 * their allocdirect or allocindir structure.
773 * The lookup routines optionally create and hash a new instance when
774 * an existing entry is not found.
776 #define DEPALLOC 0x0001 /* allocate structure if lookup fails */
777 #define NODELAY 0x0002 /* cannot do background work */
780 * Structures and routines associated with pagedep caching.
782 LIST_HEAD(pagedep_hashhead, pagedep) *pagedep_hashtbl;
783 u_long pagedep_hash; /* size of hash table - 1 */
784 #define PAGEDEP_HASH(mp, inum, lbn) \
785 (&pagedep_hashtbl[((((register_t)(mp)) >> 13) + (inum) + (lbn)) & \
787 static struct sema pagedep_in_progress;
790 * Helper routine for pagedep_lookup()
794 pagedep_find(struct pagedep_hashhead *pagedephd, ino_t ino, ufs_lbn_t lbn,
797 struct pagedep *pagedep;
799 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
800 if (ino == pagedep->pd_ino &&
801 lbn == pagedep->pd_lbn &&
802 mp == pagedep->pd_mnt) {
810 * Look up a pagedep. Return 1 if found, 0 if not found.
811 * If not found, allocate if DEPALLOC flag is passed.
812 * Found or allocated entry is returned in pagedeppp.
813 * This routine must be called with splbio interrupts blocked.
816 pagedep_lookup(struct inode *ip, ufs_lbn_t lbn, int flags,
817 struct pagedep **pagedeppp)
819 struct pagedep *pagedep;
820 struct pagedep_hashhead *pagedephd;
824 KKASSERT(lock_held(&lk) > 0);
826 mp = ITOV(ip)->v_mount;
827 pagedephd = PAGEDEP_HASH(mp, ip->i_number, lbn);
829 *pagedeppp = pagedep_find(pagedephd, ip->i_number, lbn, mp);
832 if ((flags & DEPALLOC) == 0)
834 if (sema_get(&pagedep_in_progress, &lk) == 0) {
838 pagedep = kmalloc(sizeof(struct pagedep), M_PAGEDEP,
839 M_SOFTDEP_FLAGS | M_ZERO);
841 if (pagedep_find(pagedephd, ip->i_number, lbn, mp)) {
842 kprintf("pagedep_lookup: blocking race avoided\n");
844 sema_release(&pagedep_in_progress);
845 kfree(pagedep, M_PAGEDEP);
849 pagedep->pd_list.wk_type = D_PAGEDEP;
850 pagedep->pd_mnt = mp;
851 pagedep->pd_ino = ip->i_number;
852 pagedep->pd_lbn = lbn;
853 LIST_INIT(&pagedep->pd_dirremhd);
854 LIST_INIT(&pagedep->pd_pendinghd);
855 for (i = 0; i < DAHASHSZ; i++)
856 LIST_INIT(&pagedep->pd_diraddhd[i]);
858 LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
859 sema_release(&pagedep_in_progress);
860 *pagedeppp = pagedep;
865 * Structures and routines associated with inodedep caching.
867 LIST_HEAD(inodedep_hashhead, inodedep) *inodedep_hashtbl;
868 static u_long inodedep_hash; /* size of hash table - 1 */
869 static long num_inodedep; /* number of inodedep allocated */
870 #define INODEDEP_HASH(fs, inum) \
871 (&inodedep_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & inodedep_hash])
872 static struct sema inodedep_in_progress;
875 * Helper routine for inodedep_lookup()
879 inodedep_find(struct inodedep_hashhead *inodedephd, struct fs *fs, ino_t inum)
881 struct inodedep *inodedep;
883 LIST_FOREACH(inodedep, inodedephd, id_hash) {
884 if (inum == inodedep->id_ino && fs == inodedep->id_fs)
891 * Look up a inodedep. Return 1 if found, 0 if not found.
892 * If not found, allocate if DEPALLOC flag is passed.
893 * Found or allocated entry is returned in inodedeppp.
894 * This routine must be called with splbio interrupts blocked.
897 inodedep_lookup(struct fs *fs, ino_t inum, int flags,
898 struct inodedep **inodedeppp)
900 struct inodedep *inodedep;
901 struct inodedep_hashhead *inodedephd;
904 KKASSERT(lock_held(&lk) > 0);
907 inodedephd = INODEDEP_HASH(fs, inum);
909 *inodedeppp = inodedep_find(inodedephd, fs, inum);
912 if ((flags & DEPALLOC) == 0)
915 * If we are over our limit, try to improve the situation.
917 if (num_inodedep > max_softdeps && firsttry &&
918 speedup_syncer() == 0 && (flags & NODELAY) == 0 &&
919 request_cleanup(FLUSH_INODES, 1)) {
923 if (sema_get(&inodedep_in_progress, &lk) == 0) {
927 inodedep = kmalloc(sizeof(struct inodedep), M_INODEDEP,
928 M_SOFTDEP_FLAGS | M_ZERO);
929 if (inodedep_find(inodedephd, fs, inum)) {
930 kprintf("inodedep_lookup: blocking race avoided\n");
932 sema_release(&inodedep_in_progress);
933 kfree(inodedep, M_INODEDEP);
936 inodedep->id_list.wk_type = D_INODEDEP;
937 inodedep->id_fs = fs;
938 inodedep->id_ino = inum;
939 inodedep->id_state = ALLCOMPLETE;
940 inodedep->id_nlinkdelta = 0;
941 inodedep->id_savedino = NULL;
942 inodedep->id_savedsize = -1;
943 inodedep->id_buf = NULL;
944 LIST_INIT(&inodedep->id_pendinghd);
945 LIST_INIT(&inodedep->id_inowait);
946 LIST_INIT(&inodedep->id_bufwait);
947 TAILQ_INIT(&inodedep->id_inoupdt);
948 TAILQ_INIT(&inodedep->id_newinoupdt);
951 LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
952 sema_release(&inodedep_in_progress);
953 *inodedeppp = inodedep;
958 * Structures and routines associated with newblk caching.
960 LIST_HEAD(newblk_hashhead, newblk) *newblk_hashtbl;
961 u_long newblk_hash; /* size of hash table - 1 */
962 #define NEWBLK_HASH(fs, inum) \
963 (&newblk_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & newblk_hash])
964 static struct sema newblk_in_progress;
967 * Helper routine for newblk_lookup()
971 newblk_find(struct newblk_hashhead *newblkhd, struct fs *fs,
972 ufs_daddr_t newblkno)
974 struct newblk *newblk;
976 LIST_FOREACH(newblk, newblkhd, nb_hash) {
977 if (newblkno == newblk->nb_newblkno && fs == newblk->nb_fs)
984 * Look up a newblk. Return 1 if found, 0 if not found.
985 * If not found, allocate if DEPALLOC flag is passed.
986 * Found or allocated entry is returned in newblkpp.
989 newblk_lookup(struct fs *fs, ufs_daddr_t newblkno, int flags,
990 struct newblk **newblkpp)
992 struct newblk *newblk;
993 struct newblk_hashhead *newblkhd;
995 newblkhd = NEWBLK_HASH(fs, newblkno);
997 *newblkpp = newblk_find(newblkhd, fs, newblkno);
1000 if ((flags & DEPALLOC) == 0)
1002 if (sema_get(&newblk_in_progress, 0) == 0)
1004 newblk = kmalloc(sizeof(struct newblk), M_NEWBLK,
1005 M_SOFTDEP_FLAGS | M_ZERO);
1007 if (newblk_find(newblkhd, fs, newblkno)) {
1008 kprintf("newblk_lookup: blocking race avoided\n");
1009 sema_release(&pagedep_in_progress);
1010 kfree(newblk, M_NEWBLK);
1013 newblk->nb_state = 0;
1015 newblk->nb_newblkno = newblkno;
1016 LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
1017 sema_release(&newblk_in_progress);
1023 * Executed during filesystem system initialization before
1024 * mounting any filesystems.
1027 softdep_initialize(void)
1029 callout_init(&handle);
1031 LIST_INIT(&mkdirlisthd);
1032 LIST_INIT(&softdep_workitem_pending);
1033 max_softdeps = min(desiredvnodes * 8,
1034 M_INODEDEP->ks_limit / (2 * sizeof(struct inodedep)));
1035 pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
1037 lockinit(&lk, "ffs_softdep", 0, LK_CANRECURSE);
1038 sema_init(&pagedep_in_progress, "pagedep", 0, 0);
1039 inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP, &inodedep_hash);
1040 sema_init(&inodedep_in_progress, "inodedep", 0, 0);
1041 newblk_hashtbl = hashinit(64, M_NEWBLK, &newblk_hash);
1042 sema_init(&newblk_in_progress, "newblk", 0, 0);
1043 add_bio_ops(&softdep_bioops);
1047 * Called at mount time to notify the dependency code that a
1048 * filesystem wishes to use it.
1051 softdep_mount(struct vnode *devvp, struct mount *mp, struct fs *fs)
1053 struct csum cstotal;
1058 mp->mnt_flag &= ~MNT_ASYNC;
1059 mp->mnt_flag |= MNT_SOFTDEP;
1060 mp->mnt_bioops = &softdep_bioops;
1062 * When doing soft updates, the counters in the
1063 * superblock may have gotten out of sync, so we have
1064 * to scan the cylinder groups and recalculate them.
1066 if (fs->fs_clean != 0)
1068 bzero(&cstotal, sizeof cstotal);
1069 for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
1070 if ((error = bread(devvp, fsbtodoff(fs, cgtod(fs, cyl)),
1071 fs->fs_cgsize, &bp)) != 0) {
1075 cgp = (struct cg *)bp->b_data;
1076 cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
1077 cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
1078 cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
1079 cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
1080 fs->fs_cs(fs, cyl) = cgp->cg_cs;
1084 if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
1085 kprintf("ffs_mountfs: superblock updated for soft updates\n");
1087 bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
1092 * Protecting the freemaps (or bitmaps).
1094 * To eliminate the need to execute fsck before mounting a filesystem
1095 * after a power failure, one must (conservatively) guarantee that the
1096 * on-disk copy of the bitmaps never indicate that a live inode or block is
1097 * free. So, when a block or inode is allocated, the bitmap should be
1098 * updated (on disk) before any new pointers. When a block or inode is
1099 * freed, the bitmap should not be updated until all pointers have been
1100 * reset. The latter dependency is handled by the delayed de-allocation
1101 * approach described below for block and inode de-allocation. The former
1102 * dependency is handled by calling the following procedure when a block or
1103 * inode is allocated. When an inode is allocated an "inodedep" is created
1104 * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
1105 * Each "inodedep" is also inserted into the hash indexing structure so
1106 * that any additional link additions can be made dependent on the inode
1109 * The ufs filesystem maintains a number of free block counts (e.g., per
1110 * cylinder group, per cylinder and per <cylinder, rotational position> pair)
1111 * in addition to the bitmaps. These counts are used to improve efficiency
1112 * during allocation and therefore must be consistent with the bitmaps.
1113 * There is no convenient way to guarantee post-crash consistency of these
1114 * counts with simple update ordering, for two main reasons: (1) The counts
1115 * and bitmaps for a single cylinder group block are not in the same disk
1116 * sector. If a disk write is interrupted (e.g., by power failure), one may
1117 * be written and the other not. (2) Some of the counts are located in the
1118 * superblock rather than the cylinder group block. So, we focus our soft
1119 * updates implementation on protecting the bitmaps. When mounting a
1120 * filesystem, we recompute the auxiliary counts from the bitmaps.
1124 * Called just after updating the cylinder group block to allocate an inode.
1127 * bp: buffer for cylgroup block with inode map
1128 * ip: inode related to allocation
1129 * newinum: new inode number being allocated
1132 softdep_setup_inomapdep(struct buf *bp, struct inode *ip, ino_t newinum)
1134 struct inodedep *inodedep;
1135 struct bmsafemap *bmsafemap;
1138 * Create a dependency for the newly allocated inode.
1139 * Panic if it already exists as something is seriously wrong.
1140 * Otherwise add it to the dependency list for the buffer holding
1141 * the cylinder group map from which it was allocated.
1144 if ((inodedep_lookup(ip->i_fs, newinum, DEPALLOC|NODELAY, &inodedep))) {
1146 panic("softdep_setup_inomapdep: found inode");
1148 inodedep->id_buf = bp;
1149 inodedep->id_state &= ~DEPCOMPLETE;
1150 bmsafemap = bmsafemap_lookup(bp);
1151 LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
1156 * Called just after updating the cylinder group block to
1157 * allocate block or fragment.
1160 * bp: buffer for cylgroup block with block map
1161 * fs: filesystem doing allocation
1162 * newblkno: number of newly allocated block
1165 softdep_setup_blkmapdep(struct buf *bp, struct fs *fs,
1166 ufs_daddr_t newblkno)
1168 struct newblk *newblk;
1169 struct bmsafemap *bmsafemap;
1172 * Create a dependency for the newly allocated block.
1173 * Add it to the dependency list for the buffer holding
1174 * the cylinder group map from which it was allocated.
1176 if (newblk_lookup(fs, newblkno, DEPALLOC, &newblk) != 0)
1177 panic("softdep_setup_blkmapdep: found block");
1179 newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(bp);
1180 LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
1185 * Find the bmsafemap associated with a cylinder group buffer.
1186 * If none exists, create one. The buffer must be locked when
1187 * this routine is called and this routine must be called with
1188 * splbio interrupts blocked.
1190 static struct bmsafemap *
1191 bmsafemap_lookup(struct buf *bp)
1193 struct bmsafemap *bmsafemap;
1194 struct worklist *wk;
1196 KKASSERT(lock_held(&lk) > 0);
1198 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
1199 if (wk->wk_type == D_BMSAFEMAP)
1200 return (WK_BMSAFEMAP(wk));
1203 bmsafemap = kmalloc(sizeof(struct bmsafemap), M_BMSAFEMAP,
1205 bmsafemap->sm_list.wk_type = D_BMSAFEMAP;
1206 bmsafemap->sm_list.wk_state = 0;
1207 bmsafemap->sm_buf = bp;
1208 LIST_INIT(&bmsafemap->sm_allocdirecthd);
1209 LIST_INIT(&bmsafemap->sm_allocindirhd);
1210 LIST_INIT(&bmsafemap->sm_inodedephd);
1211 LIST_INIT(&bmsafemap->sm_newblkhd);
1213 WORKLIST_INSERT_BP(bp, &bmsafemap->sm_list);
1218 * Direct block allocation dependencies.
1220 * When a new block is allocated, the corresponding disk locations must be
1221 * initialized (with zeros or new data) before the on-disk inode points to
1222 * them. Also, the freemap from which the block was allocated must be
1223 * updated (on disk) before the inode's pointer. These two dependencies are
1224 * independent of each other and are needed for all file blocks and indirect
1225 * blocks that are pointed to directly by the inode. Just before the
1226 * "in-core" version of the inode is updated with a newly allocated block
1227 * number, a procedure (below) is called to setup allocation dependency
1228 * structures. These structures are removed when the corresponding
1229 * dependencies are satisfied or when the block allocation becomes obsolete
1230 * (i.e., the file is deleted, the block is de-allocated, or the block is a
1231 * fragment that gets upgraded). All of these cases are handled in
1232 * procedures described later.
1234 * When a file extension causes a fragment to be upgraded, either to a larger
1235 * fragment or to a full block, the on-disk location may change (if the
1236 * previous fragment could not simply be extended). In this case, the old
1237 * fragment must be de-allocated, but not until after the inode's pointer has
1238 * been updated. In most cases, this is handled by later procedures, which
1239 * will construct a "freefrag" structure to be added to the workitem queue
1240 * when the inode update is complete (or obsolete). The main exception to
1241 * this is when an allocation occurs while a pending allocation dependency
1242 * (for the same block pointer) remains. This case is handled in the main
1243 * allocation dependency setup procedure by immediately freeing the
1244 * unreferenced fragments.
1247 * ip: inode to which block is being added
1248 * lbn: block pointer within inode
1249 * newblkno: disk block number being added
1250 * oldblkno: previous block number, 0 unless frag
1251 * newsize: size of new block
1252 * oldsize: size of new block
1253 * bp: bp for allocated block
1256 softdep_setup_allocdirect(struct inode *ip, ufs_lbn_t lbn, ufs_daddr_t newblkno,
1257 ufs_daddr_t oldblkno, long newsize, long oldsize,
1260 struct allocdirect *adp, *oldadp;
1261 struct allocdirectlst *adphead;
1262 struct bmsafemap *bmsafemap;
1263 struct inodedep *inodedep;
1264 struct pagedep *pagedep;
1265 struct newblk *newblk;
1267 adp = kmalloc(sizeof(struct allocdirect), M_ALLOCDIRECT,
1268 M_SOFTDEP_FLAGS | M_ZERO);
1269 adp->ad_list.wk_type = D_ALLOCDIRECT;
1271 adp->ad_newblkno = newblkno;
1272 adp->ad_oldblkno = oldblkno;
1273 adp->ad_newsize = newsize;
1274 adp->ad_oldsize = oldsize;
1275 adp->ad_state = ATTACHED;
1276 if (newblkno == oldblkno)
1277 adp->ad_freefrag = NULL;
1279 adp->ad_freefrag = newfreefrag(ip, oldblkno, oldsize);
1281 if (newblk_lookup(ip->i_fs, newblkno, 0, &newblk) == 0)
1282 panic("softdep_setup_allocdirect: lost block");
1285 inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC | NODELAY, &inodedep);
1286 adp->ad_inodedep = inodedep;
1288 if (newblk->nb_state == DEPCOMPLETE) {
1289 adp->ad_state |= DEPCOMPLETE;
1292 bmsafemap = newblk->nb_bmsafemap;
1293 adp->ad_buf = bmsafemap->sm_buf;
1294 LIST_REMOVE(newblk, nb_deps);
1295 LIST_INSERT_HEAD(&bmsafemap->sm_allocdirecthd, adp, ad_deps);
1297 LIST_REMOVE(newblk, nb_hash);
1298 kfree(newblk, M_NEWBLK);
1300 WORKLIST_INSERT_BP(bp, &adp->ad_list);
1301 if (lbn >= NDADDR) {
1302 /* allocating an indirect block */
1303 if (oldblkno != 0) {
1305 panic("softdep_setup_allocdirect: non-zero indir");
1309 * Allocating a direct block.
1311 * If we are allocating a directory block, then we must
1312 * allocate an associated pagedep to track additions and
1315 if ((ip->i_mode & IFMT) == IFDIR &&
1316 pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0) {
1317 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
1321 * The list of allocdirects must be kept in sorted and ascending
1322 * order so that the rollback routines can quickly determine the
1323 * first uncommitted block (the size of the file stored on disk
1324 * ends at the end of the lowest committed fragment, or if there
1325 * are no fragments, at the end of the highest committed block).
1326 * Since files generally grow, the typical case is that the new
1327 * block is to be added at the end of the list. We speed this
1328 * special case by checking against the last allocdirect in the
1329 * list before laboriously traversing the list looking for the
1332 adphead = &inodedep->id_newinoupdt;
1333 oldadp = TAILQ_LAST(adphead, allocdirectlst);
1334 if (oldadp == NULL || oldadp->ad_lbn <= lbn) {
1335 /* insert at end of list */
1336 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
1337 if (oldadp != NULL && oldadp->ad_lbn == lbn)
1338 allocdirect_merge(adphead, adp, oldadp);
1342 TAILQ_FOREACH(oldadp, adphead, ad_next) {
1343 if (oldadp->ad_lbn >= lbn)
1346 if (oldadp == NULL) {
1348 panic("softdep_setup_allocdirect: lost entry");
1350 /* insert in middle of list */
1351 TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
1352 if (oldadp->ad_lbn == lbn)
1353 allocdirect_merge(adphead, adp, oldadp);
1358 * Replace an old allocdirect dependency with a newer one.
1359 * This routine must be called with splbio interrupts blocked.
1362 * adphead: head of list holding allocdirects
1363 * newadp: allocdirect being added
1364 * oldadp: existing allocdirect being checked
1367 allocdirect_merge(struct allocdirectlst *adphead,
1368 struct allocdirect *newadp,
1369 struct allocdirect *oldadp)
1371 struct freefrag *freefrag;
1373 KKASSERT(lock_held(&lk) > 0);
1375 if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
1376 newadp->ad_oldsize != oldadp->ad_newsize ||
1377 newadp->ad_lbn >= NDADDR) {
1379 panic("allocdirect_check: old %d != new %d || lbn %ld >= %d",
1380 newadp->ad_oldblkno, oldadp->ad_newblkno, newadp->ad_lbn,
1383 newadp->ad_oldblkno = oldadp->ad_oldblkno;
1384 newadp->ad_oldsize = oldadp->ad_oldsize;
1386 * If the old dependency had a fragment to free or had never
1387 * previously had a block allocated, then the new dependency
1388 * can immediately post its freefrag and adopt the old freefrag.
1389 * This action is done by swapping the freefrag dependencies.
1390 * The new dependency gains the old one's freefrag, and the
1391 * old one gets the new one and then immediately puts it on
1392 * the worklist when it is freed by free_allocdirect. It is
1393 * not possible to do this swap when the old dependency had a
1394 * non-zero size but no previous fragment to free. This condition
1395 * arises when the new block is an extension of the old block.
1396 * Here, the first part of the fragment allocated to the new
1397 * dependency is part of the block currently claimed on disk by
1398 * the old dependency, so cannot legitimately be freed until the
1399 * conditions for the new dependency are fulfilled.
1401 if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
1402 freefrag = newadp->ad_freefrag;
1403 newadp->ad_freefrag = oldadp->ad_freefrag;
1404 oldadp->ad_freefrag = freefrag;
1406 free_allocdirect(adphead, oldadp, 0);
1410 * Allocate a new freefrag structure if needed.
1412 static struct freefrag *
1413 newfreefrag(struct inode *ip, ufs_daddr_t blkno, long size)
1415 struct freefrag *freefrag;
1421 if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
1422 panic("newfreefrag: frag size");
1423 freefrag = kmalloc(sizeof(struct freefrag), M_FREEFRAG,
1425 freefrag->ff_list.wk_type = D_FREEFRAG;
1426 freefrag->ff_state = ip->i_uid & ~ONWORKLIST; /* XXX - used below */
1427 freefrag->ff_inum = ip->i_number;
1428 freefrag->ff_fs = fs;
1429 freefrag->ff_devvp = ip->i_devvp;
1430 freefrag->ff_blkno = blkno;
1431 freefrag->ff_fragsize = size;
1436 * This workitem de-allocates fragments that were replaced during
1437 * file block allocation.
1440 handle_workitem_freefrag(struct freefrag *freefrag)
1444 tip.i_fs = freefrag->ff_fs;
1445 tip.i_devvp = freefrag->ff_devvp;
1446 tip.i_dev = freefrag->ff_devvp->v_rdev;
1447 tip.i_number = freefrag->ff_inum;
1448 tip.i_uid = freefrag->ff_state & ~ONWORKLIST; /* XXX - set above */
1449 ffs_blkfree(&tip, freefrag->ff_blkno, freefrag->ff_fragsize);
1450 kfree(freefrag, M_FREEFRAG);
1454 * Indirect block allocation dependencies.
1456 * The same dependencies that exist for a direct block also exist when
1457 * a new block is allocated and pointed to by an entry in a block of
1458 * indirect pointers. The undo/redo states described above are also
1459 * used here. Because an indirect block contains many pointers that
1460 * may have dependencies, a second copy of the entire in-memory indirect
1461 * block is kept. The buffer cache copy is always completely up-to-date.
1462 * The second copy, which is used only as a source for disk writes,
1463 * contains only the safe pointers (i.e., those that have no remaining
1464 * update dependencies). The second copy is freed when all pointers
1465 * are safe. The cache is not allowed to replace indirect blocks with
1466 * pending update dependencies. If a buffer containing an indirect
1467 * block with dependencies is written, these routines will mark it
1468 * dirty again. It can only be successfully written once all the
1469 * dependencies are removed. The ffs_fsync routine in conjunction with
1470 * softdep_sync_metadata work together to get all the dependencies
1471 * removed so that a file can be successfully written to disk. Three
1472 * procedures are used when setting up indirect block pointer
1473 * dependencies. The division is necessary because of the organization
1474 * of the "balloc" routine and because of the distinction between file
1475 * pages and file metadata blocks.
1479 * Allocate a new allocindir structure.
1482 * ip: inode for file being extended
1483 * ptrno: offset of pointer in indirect block
1484 * newblkno: disk block number being added
1485 * oldblkno: previous block number, 0 if none
1487 static struct allocindir *
1488 newallocindir(struct inode *ip, int ptrno, ufs_daddr_t newblkno,
1489 ufs_daddr_t oldblkno)
1491 struct allocindir *aip;
1493 aip = kmalloc(sizeof(struct allocindir), M_ALLOCINDIR,
1494 M_SOFTDEP_FLAGS | M_ZERO);
1495 aip->ai_list.wk_type = D_ALLOCINDIR;
1496 aip->ai_state = ATTACHED;
1497 aip->ai_offset = ptrno;
1498 aip->ai_newblkno = newblkno;
1499 aip->ai_oldblkno = oldblkno;
1500 aip->ai_freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize);
1505 * Called just before setting an indirect block pointer
1506 * to a newly allocated file page.
1509 * ip: inode for file being extended
1510 * lbn: allocated block number within file
1511 * bp: buffer with indirect blk referencing page
1512 * ptrno: offset of pointer in indirect block
1513 * newblkno: disk block number being added
1514 * oldblkno: previous block number, 0 if none
1515 * nbp: buffer holding allocated page
1518 softdep_setup_allocindir_page(struct inode *ip, ufs_lbn_t lbn,
1519 struct buf *bp, int ptrno,
1520 ufs_daddr_t newblkno, ufs_daddr_t oldblkno,
1523 struct allocindir *aip;
1524 struct pagedep *pagedep;
1526 aip = newallocindir(ip, ptrno, newblkno, oldblkno);
1529 * If we are allocating a directory page, then we must
1530 * allocate an associated pagedep to track additions and
1533 if ((ip->i_mode & IFMT) == IFDIR &&
1534 pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0)
1535 WORKLIST_INSERT_BP(nbp, &pagedep->pd_list);
1536 WORKLIST_INSERT_BP(nbp, &aip->ai_list);
1538 setup_allocindir_phase2(bp, ip, aip);
1542 * Called just before setting an indirect block pointer to a
1543 * newly allocated indirect block.
1545 * nbp: newly allocated indirect block
1546 * ip: inode for file being extended
1547 * bp: indirect block referencing allocated block
1548 * ptrno: offset of pointer in indirect block
1549 * newblkno: disk block number being added
1552 softdep_setup_allocindir_meta(struct buf *nbp, struct inode *ip,
1553 struct buf *bp, int ptrno,
1554 ufs_daddr_t newblkno)
1556 struct allocindir *aip;
1558 aip = newallocindir(ip, ptrno, newblkno, 0);
1560 WORKLIST_INSERT_BP(nbp, &aip->ai_list);
1562 setup_allocindir_phase2(bp, ip, aip);
1566 * Called to finish the allocation of the "aip" allocated
1567 * by one of the two routines above.
1570 * bp: in-memory copy of the indirect block
1571 * ip: inode for file being extended
1572 * aip: allocindir allocated by the above routines
1575 setup_allocindir_phase2(struct buf *bp, struct inode *ip,
1576 struct allocindir *aip)
1578 struct worklist *wk;
1579 struct indirdep *indirdep, *newindirdep;
1580 struct bmsafemap *bmsafemap;
1581 struct allocindir *oldaip;
1582 struct freefrag *freefrag;
1583 struct newblk *newblk;
1585 if (bp->b_loffset >= 0)
1586 panic("setup_allocindir_phase2: not indir blk");
1587 for (indirdep = NULL, newindirdep = NULL; ; ) {
1589 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
1590 if (wk->wk_type != D_INDIRDEP)
1592 indirdep = WK_INDIRDEP(wk);
1595 if (indirdep == NULL && newindirdep) {
1596 indirdep = newindirdep;
1597 WORKLIST_INSERT_BP(bp, &indirdep->ir_list);
1602 if (newblk_lookup(ip->i_fs, aip->ai_newblkno, 0,
1604 panic("setup_allocindir: lost block");
1606 if (newblk->nb_state == DEPCOMPLETE) {
1607 aip->ai_state |= DEPCOMPLETE;
1610 bmsafemap = newblk->nb_bmsafemap;
1611 aip->ai_buf = bmsafemap->sm_buf;
1612 LIST_REMOVE(newblk, nb_deps);
1613 LIST_INSERT_HEAD(&bmsafemap->sm_allocindirhd,
1616 LIST_REMOVE(newblk, nb_hash);
1617 kfree(newblk, M_NEWBLK);
1618 aip->ai_indirdep = indirdep;
1620 * Check to see if there is an existing dependency
1621 * for this block. If there is, merge the old
1622 * dependency into the new one.
1624 if (aip->ai_oldblkno == 0)
1628 LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next)
1629 if (oldaip->ai_offset == aip->ai_offset)
1631 if (oldaip != NULL) {
1632 if (oldaip->ai_newblkno != aip->ai_oldblkno) {
1634 panic("setup_allocindir_phase2: blkno");
1636 aip->ai_oldblkno = oldaip->ai_oldblkno;
1637 freefrag = oldaip->ai_freefrag;
1638 oldaip->ai_freefrag = aip->ai_freefrag;
1639 aip->ai_freefrag = freefrag;
1640 free_allocindir(oldaip, NULL);
1642 LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
1643 ((ufs_daddr_t *)indirdep->ir_savebp->b_data)
1644 [aip->ai_offset] = aip->ai_oldblkno;
1649 * Avoid any possibility of data corruption by
1650 * ensuring that our old version is thrown away.
1652 newindirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
1653 brelse(newindirdep->ir_savebp);
1654 WORKITEM_FREE((caddr_t)newindirdep, D_INDIRDEP);
1658 newindirdep = kmalloc(sizeof(struct indirdep), M_INDIRDEP,
1660 newindirdep->ir_list.wk_type = D_INDIRDEP;
1661 newindirdep->ir_state = ATTACHED;
1662 LIST_INIT(&newindirdep->ir_deplisthd);
1663 LIST_INIT(&newindirdep->ir_donehd);
1664 if (bp->b_bio2.bio_offset == NOOFFSET) {
1665 VOP_BMAP(bp->b_vp, bp->b_bio1.bio_offset,
1666 &bp->b_bio2.bio_offset, NULL, NULL,
1669 KKASSERT(bp->b_bio2.bio_offset != NOOFFSET);
1670 newindirdep->ir_savebp = getblk(ip->i_devvp,
1671 bp->b_bio2.bio_offset,
1672 bp->b_bcount, 0, 0);
1673 BUF_KERNPROC(newindirdep->ir_savebp);
1674 bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
1679 * Block de-allocation dependencies.
1681 * When blocks are de-allocated, the on-disk pointers must be nullified before
1682 * the blocks are made available for use by other files. (The true
1683 * requirement is that old pointers must be nullified before new on-disk
1684 * pointers are set. We chose this slightly more stringent requirement to
1685 * reduce complexity.) Our implementation handles this dependency by updating
1686 * the inode (or indirect block) appropriately but delaying the actual block
1687 * de-allocation (i.e., freemap and free space count manipulation) until
1688 * after the updated versions reach stable storage. After the disk is
1689 * updated, the blocks can be safely de-allocated whenever it is convenient.
1690 * This implementation handles only the common case of reducing a file's
1691 * length to zero. Other cases are handled by the conventional synchronous
1694 * The ffs implementation with which we worked double-checks
1695 * the state of the block pointers and file size as it reduces
1696 * a file's length. Some of this code is replicated here in our
1697 * soft updates implementation. The freeblks->fb_chkcnt field is
1698 * used to transfer a part of this information to the procedure
1699 * that eventually de-allocates the blocks.
1701 * This routine should be called from the routine that shortens
1702 * a file's length, before the inode's size or block pointers
1703 * are modified. It will save the block pointer information for
1704 * later release and zero the inode so that the calling routine
1707 struct softdep_setup_freeblocks_info {
1712 static int softdep_setup_freeblocks_bp(struct buf *bp, void *data);
1716 * ip: The inode whose length is to be reduced
1717 * length: The new length for the file
1720 softdep_setup_freeblocks(struct inode *ip, off_t length)
1722 struct softdep_setup_freeblocks_info info;
1723 struct freeblks *freeblks;
1724 struct inodedep *inodedep;
1725 struct allocdirect *adp;
1729 int i, error, delay;
1734 panic("softde_setup_freeblocks: non-zero length");
1735 freeblks = kmalloc(sizeof(struct freeblks), M_FREEBLKS,
1736 M_SOFTDEP_FLAGS | M_ZERO);
1737 freeblks->fb_list.wk_type = D_FREEBLKS;
1738 freeblks->fb_state = ATTACHED;
1739 freeblks->fb_uid = ip->i_uid;
1740 freeblks->fb_previousinum = ip->i_number;
1741 freeblks->fb_devvp = ip->i_devvp;
1742 freeblks->fb_fs = fs;
1743 freeblks->fb_oldsize = ip->i_size;
1744 freeblks->fb_newsize = length;
1745 freeblks->fb_chkcnt = ip->i_blocks;
1746 for (i = 0; i < NDADDR; i++) {
1747 freeblks->fb_dblks[i] = ip->i_db[i];
1750 for (i = 0; i < NIADDR; i++) {
1751 freeblks->fb_iblks[i] = ip->i_ib[i];
1757 * Push the zero'ed inode to to its disk buffer so that we are free
1758 * to delete its dependencies below. Once the dependencies are gone
1759 * the buffer can be safely released.
1761 if ((error = bread(ip->i_devvp,
1762 fsbtodoff(fs, ino_to_fsba(fs, ip->i_number)),
1763 (int)fs->fs_bsize, &bp)) != 0)
1764 softdep_error("softdep_setup_freeblocks", error);
1765 *((struct ufs1_dinode *)bp->b_data + ino_to_fsbo(fs, ip->i_number)) =
1768 * Find and eliminate any inode dependencies.
1771 (void) inodedep_lookup(fs, ip->i_number, DEPALLOC, &inodedep);
1772 if ((inodedep->id_state & IOSTARTED) != 0) {
1774 panic("softdep_setup_freeblocks: inode busy");
1777 * Add the freeblks structure to the list of operations that
1778 * must await the zero'ed inode being written to disk. If we
1779 * still have a bitmap dependency (delay == 0), then the inode
1780 * has never been written to disk, so we can process the
1781 * freeblks below once we have deleted the dependencies.
1783 delay = (inodedep->id_state & DEPCOMPLETE);
1785 WORKLIST_INSERT(&inodedep->id_bufwait, &freeblks->fb_list);
1787 * Because the file length has been truncated to zero, any
1788 * pending block allocation dependency structures associated
1789 * with this inode are obsolete and can simply be de-allocated.
1790 * We must first merge the two dependency lists to get rid of
1791 * any duplicate freefrag structures, then purge the merged list.
1793 merge_inode_lists(inodedep);
1794 while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
1795 free_allocdirect(&inodedep->id_inoupdt, adp, 1);
1799 * We must wait for any I/O in progress to finish so that
1800 * all potential buffers on the dirty list will be visible.
1801 * Once they are all there, walk the list and get rid of
1806 drain_output(vp, 1);
1810 lwkt_gettoken(&vp->v_token);
1812 count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
1813 softdep_setup_freeblocks_bp, &info);
1814 } while (count != 0);
1815 lwkt_reltoken(&vp->v_token);
1817 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) != 0)
1818 (void)free_inodedep(inodedep);
1821 freeblks->fb_state |= DEPCOMPLETE;
1823 * If the inode with zeroed block pointers is now on disk
1824 * we can start freeing blocks. Add freeblks to the worklist
1825 * instead of calling handle_workitem_freeblocks directly as
1826 * it is more likely that additional IO is needed to complete
1827 * the request here than in the !delay case.
1829 if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
1830 add_to_worklist(&freeblks->fb_list);
1835 * If the inode has never been written to disk (delay == 0),
1836 * then we can process the freeblks now that we have deleted
1840 handle_workitem_freeblocks(freeblks);
1844 softdep_setup_freeblocks_bp(struct buf *bp, void *data)
1846 struct softdep_setup_freeblocks_info *info = data;
1847 struct inodedep *inodedep;
1849 if (getdirtybuf(&bp, MNT_WAIT) == 0) {
1850 kprintf("softdep_setup_freeblocks_bp(1): caught bp %p going away\n", bp);
1853 if (bp->b_vp != ITOV(info->ip) || (bp->b_flags & B_DELWRI) == 0) {
1854 kprintf("softdep_setup_freeblocks_bp(2): caught bp %p going away\n", bp);
1858 (void) inodedep_lookup(info->fs, info->ip->i_number, 0, &inodedep);
1859 deallocate_dependencies(bp, inodedep);
1860 bp->b_flags |= B_INVAL | B_NOCACHE;
1868 * Reclaim any dependency structures from a buffer that is about to
1869 * be reallocated to a new vnode. The buffer must be locked, thus,
1870 * no I/O completion operations can occur while we are manipulating
1871 * its associated dependencies. The mutex is held so that other I/O's
1872 * associated with related dependencies do not occur.
1875 deallocate_dependencies(struct buf *bp, struct inodedep *inodedep)
1877 struct worklist *wk;
1878 struct indirdep *indirdep;
1879 struct allocindir *aip;
1880 struct pagedep *pagedep;
1881 struct dirrem *dirrem;
1885 while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
1886 switch (wk->wk_type) {
1889 indirdep = WK_INDIRDEP(wk);
1891 * None of the indirect pointers will ever be visible,
1892 * so they can simply be tossed. GOINGAWAY ensures
1893 * that allocated pointers will be saved in the buffer
1894 * cache until they are freed. Note that they will
1895 * only be able to be found by their physical address
1896 * since the inode mapping the logical address will
1897 * be gone. The save buffer used for the safe copy
1898 * was allocated in setup_allocindir_phase2 using
1899 * the physical address so it could be used for this
1900 * purpose. Hence we swap the safe copy with the real
1901 * copy, allowing the safe copy to be freed and holding
1902 * on to the real copy for later use in indir_trunc.
1904 * NOTE: ir_savebp is relative to the block device
1905 * so b_bio1 contains the device block number.
1907 if (indirdep->ir_state & GOINGAWAY) {
1909 panic("deallocate_dependencies: already gone");
1911 indirdep->ir_state |= GOINGAWAY;
1912 while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
1913 free_allocindir(aip, inodedep);
1914 if (bp->b_bio1.bio_offset >= 0 ||
1915 bp->b_bio2.bio_offset != indirdep->ir_savebp->b_bio1.bio_offset) {
1917 panic("deallocate_dependencies: not indir");
1919 bcopy(bp->b_data, indirdep->ir_savebp->b_data,
1921 WORKLIST_REMOVE(wk);
1922 WORKLIST_INSERT_BP(indirdep->ir_savebp, wk);
1926 pagedep = WK_PAGEDEP(wk);
1928 * None of the directory additions will ever be
1929 * visible, so they can simply be tossed.
1931 for (i = 0; i < DAHASHSZ; i++)
1933 LIST_FIRST(&pagedep->pd_diraddhd[i])))
1935 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
1938 * Copy any directory remove dependencies to the list
1939 * to be processed after the zero'ed inode is written.
1940 * If the inode has already been written, then they
1941 * can be dumped directly onto the work list.
1943 LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
1944 LIST_REMOVE(dirrem, dm_next);
1945 dirrem->dm_dirinum = pagedep->pd_ino;
1946 if (inodedep == NULL ||
1947 (inodedep->id_state & ALLCOMPLETE) ==
1949 add_to_worklist(&dirrem->dm_list);
1951 WORKLIST_INSERT(&inodedep->id_bufwait,
1954 WORKLIST_REMOVE(&pagedep->pd_list);
1955 LIST_REMOVE(pagedep, pd_hash);
1956 WORKITEM_FREE(pagedep, D_PAGEDEP);
1960 free_allocindir(WK_ALLOCINDIR(wk), inodedep);
1966 panic("deallocate_dependencies: Unexpected type %s",
1967 TYPENAME(wk->wk_type));
1972 panic("deallocate_dependencies: Unknown type %s",
1973 TYPENAME(wk->wk_type));
1980 * Free an allocdirect. Generate a new freefrag work request if appropriate.
1981 * This routine must be called with splbio interrupts blocked.
1984 free_allocdirect(struct allocdirectlst *adphead,
1985 struct allocdirect *adp, int delay)
1987 KKASSERT(lock_held(&lk) > 0);
1989 if ((adp->ad_state & DEPCOMPLETE) == 0)
1990 LIST_REMOVE(adp, ad_deps);
1991 TAILQ_REMOVE(adphead, adp, ad_next);
1992 if ((adp->ad_state & COMPLETE) == 0)
1993 WORKLIST_REMOVE(&adp->ad_list);
1994 if (adp->ad_freefrag != NULL) {
1996 WORKLIST_INSERT(&adp->ad_inodedep->id_bufwait,
1997 &adp->ad_freefrag->ff_list);
1999 add_to_worklist(&adp->ad_freefrag->ff_list);
2001 WORKITEM_FREE(adp, D_ALLOCDIRECT);
2005 * Prepare an inode to be freed. The actual free operation is not
2006 * done until the zero'ed inode has been written to disk.
2009 softdep_freefile(struct vnode *pvp, ino_t ino, int mode)
2011 struct inode *ip = VTOI(pvp);
2012 struct inodedep *inodedep;
2013 struct freefile *freefile;
2016 * This sets up the inode de-allocation dependency.
2018 freefile = kmalloc(sizeof(struct freefile), M_FREEFILE,
2020 freefile->fx_list.wk_type = D_FREEFILE;
2021 freefile->fx_list.wk_state = 0;
2022 freefile->fx_mode = mode;
2023 freefile->fx_oldinum = ino;
2024 freefile->fx_devvp = ip->i_devvp;
2025 freefile->fx_fs = ip->i_fs;
2028 * If the inodedep does not exist, then the zero'ed inode has
2029 * been written to disk. If the allocated inode has never been
2030 * written to disk, then the on-disk inode is zero'ed. In either
2031 * case we can free the file immediately.
2034 if (inodedep_lookup(ip->i_fs, ino, 0, &inodedep) == 0 ||
2035 check_inode_unwritten(inodedep)) {
2037 handle_workitem_freefile(freefile);
2040 WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
2045 * Check to see if an inode has never been written to disk. If
2046 * so free the inodedep and return success, otherwise return failure.
2047 * This routine must be called with splbio interrupts blocked.
2049 * If we still have a bitmap dependency, then the inode has never
2050 * been written to disk. Drop the dependency as it is no longer
2051 * necessary since the inode is being deallocated. We set the
2052 * ALLCOMPLETE flags since the bitmap now properly shows that the
2053 * inode is not allocated. Even if the inode is actively being
2054 * written, it has been rolled back to its zero'ed state, so we
2055 * are ensured that a zero inode is what is on the disk. For short
2056 * lived files, this change will usually result in removing all the
2057 * dependencies from the inode so that it can be freed immediately.
2060 check_inode_unwritten(struct inodedep *inodedep)
2063 if ((inodedep->id_state & DEPCOMPLETE) != 0 ||
2064 LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2065 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2066 LIST_FIRST(&inodedep->id_inowait) != NULL ||
2067 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2068 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2069 inodedep->id_nlinkdelta != 0)
2073 * Another process might be in initiate_write_inodeblock
2074 * trying to allocate memory without holding "Softdep Lock".
2076 if ((inodedep->id_state & IOSTARTED) != 0 &&
2077 inodedep->id_savedino == NULL)
2080 inodedep->id_state |= ALLCOMPLETE;
2081 LIST_REMOVE(inodedep, id_deps);
2082 inodedep->id_buf = NULL;
2083 if (inodedep->id_state & ONWORKLIST)
2084 WORKLIST_REMOVE(&inodedep->id_list);
2085 if (inodedep->id_savedino != NULL) {
2086 kfree(inodedep->id_savedino, M_INODEDEP);
2087 inodedep->id_savedino = NULL;
2089 if (free_inodedep(inodedep) == 0) {
2091 panic("check_inode_unwritten: busy inode");
2097 * Try to free an inodedep structure. Return 1 if it could be freed.
2100 free_inodedep(struct inodedep *inodedep)
2103 if ((inodedep->id_state & ONWORKLIST) != 0 ||
2104 (inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
2105 LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2106 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2107 LIST_FIRST(&inodedep->id_inowait) != NULL ||
2108 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2109 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2110 inodedep->id_nlinkdelta != 0 || inodedep->id_savedino != NULL)
2112 LIST_REMOVE(inodedep, id_hash);
2113 WORKITEM_FREE(inodedep, D_INODEDEP);
2119 * This workitem routine performs the block de-allocation.
2120 * The workitem is added to the pending list after the updated
2121 * inode block has been written to disk. As mentioned above,
2122 * checks regarding the number of blocks de-allocated (compared
2123 * to the number of blocks allocated for the file) are also
2124 * performed in this function.
2127 handle_workitem_freeblocks(struct freeblks *freeblks)
2132 int i, level, bsize;
2133 long nblocks, blocksreleased = 0;
2134 int error, allerror = 0;
2135 ufs_lbn_t baselbns[NIADDR], tmpval;
2137 tip.i_number = freeblks->fb_previousinum;
2138 tip.i_devvp = freeblks->fb_devvp;
2139 tip.i_dev = freeblks->fb_devvp->v_rdev;
2140 tip.i_fs = freeblks->fb_fs;
2141 tip.i_size = freeblks->fb_oldsize;
2142 tip.i_uid = freeblks->fb_uid;
2143 fs = freeblks->fb_fs;
2145 baselbns[0] = NDADDR;
2146 for (i = 1; i < NIADDR; i++) {
2147 tmpval *= NINDIR(fs);
2148 baselbns[i] = baselbns[i - 1] + tmpval;
2150 nblocks = btodb(fs->fs_bsize);
2153 * Indirect blocks first.
2155 for (level = (NIADDR - 1); level >= 0; level--) {
2156 if ((bn = freeblks->fb_iblks[level]) == 0)
2158 if ((error = indir_trunc(&tip, fsbtodoff(fs, bn), level,
2159 baselbns[level], &blocksreleased)) == 0)
2161 ffs_blkfree(&tip, bn, fs->fs_bsize);
2162 blocksreleased += nblocks;
2165 * All direct blocks or frags.
2167 for (i = (NDADDR - 1); i >= 0; i--) {
2168 if ((bn = freeblks->fb_dblks[i]) == 0)
2170 bsize = blksize(fs, &tip, i);
2171 ffs_blkfree(&tip, bn, bsize);
2172 blocksreleased += btodb(bsize);
2176 if (freeblks->fb_chkcnt != blocksreleased)
2177 kprintf("handle_workitem_freeblocks: block count\n");
2179 softdep_error("handle_workitem_freeblks", allerror);
2180 #endif /* DIAGNOSTIC */
2181 WORKITEM_FREE(freeblks, D_FREEBLKS);
2185 * Release blocks associated with the inode ip and stored in the indirect
2186 * block at doffset. If level is greater than SINGLE, the block is an
2187 * indirect block and recursive calls to indirtrunc must be used to
2188 * cleanse other indirect blocks.
2191 indir_trunc(struct inode *ip, off_t doffset, int level, ufs_lbn_t lbn,
2198 struct worklist *wk;
2199 struct indirdep *indirdep;
2200 int i, lbnadd, nblocks;
2201 int error, allerror = 0;
2205 for (i = level; i > 0; i--)
2206 lbnadd *= NINDIR(fs);
2208 * Get buffer of block pointers to be freed. This routine is not
2209 * called until the zero'ed inode has been written, so it is safe
2210 * to free blocks as they are encountered. Because the inode has
2211 * been zero'ed, calls to bmap on these blocks will fail. So, we
2212 * have to use the on-disk address and the block device for the
2213 * filesystem to look them up. If the file was deleted before its
2214 * indirect blocks were all written to disk, the routine that set
2215 * us up (deallocate_dependencies) will have arranged to leave
2216 * a complete copy of the indirect block in memory for our use.
2217 * Otherwise we have to read the blocks in from the disk.
2220 if ((bp = findblk(ip->i_devvp, doffset, FINDBLK_TEST)) != NULL &&
2221 (wk = LIST_FIRST(&bp->b_dep)) != NULL) {
2223 * bp must be ir_savebp, which is held locked for our use.
2225 if (wk->wk_type != D_INDIRDEP ||
2226 (indirdep = WK_INDIRDEP(wk))->ir_savebp != bp ||
2227 (indirdep->ir_state & GOINGAWAY) == 0) {
2229 panic("indir_trunc: lost indirdep");
2231 WORKLIST_REMOVE(wk);
2232 WORKITEM_FREE(indirdep, D_INDIRDEP);
2233 if (LIST_FIRST(&bp->b_dep) != NULL) {
2235 panic("indir_trunc: dangling dep");
2240 error = bread(ip->i_devvp, doffset, (int)fs->fs_bsize, &bp);
2245 * Recursively free indirect blocks.
2247 bap = (ufs_daddr_t *)bp->b_data;
2248 nblocks = btodb(fs->fs_bsize);
2249 for (i = NINDIR(fs) - 1; i >= 0; i--) {
2250 if ((nb = bap[i]) == 0)
2253 if ((error = indir_trunc(ip, fsbtodoff(fs, nb),
2254 level - 1, lbn + (i * lbnadd), countp)) != 0)
2257 ffs_blkfree(ip, nb, fs->fs_bsize);
2260 bp->b_flags |= B_INVAL | B_NOCACHE;
2266 * Free an allocindir.
2267 * This routine must be called with splbio interrupts blocked.
2270 free_allocindir(struct allocindir *aip, struct inodedep *inodedep)
2272 struct freefrag *freefrag;
2274 KKASSERT(lock_held(&lk) > 0);
2276 if ((aip->ai_state & DEPCOMPLETE) == 0)
2277 LIST_REMOVE(aip, ai_deps);
2278 if (aip->ai_state & ONWORKLIST)
2279 WORKLIST_REMOVE(&aip->ai_list);
2280 LIST_REMOVE(aip, ai_next);
2281 if ((freefrag = aip->ai_freefrag) != NULL) {
2282 if (inodedep == NULL)
2283 add_to_worklist(&freefrag->ff_list);
2285 WORKLIST_INSERT(&inodedep->id_bufwait,
2286 &freefrag->ff_list);
2288 WORKITEM_FREE(aip, D_ALLOCINDIR);
2292 * Directory entry addition dependencies.
2294 * When adding a new directory entry, the inode (with its incremented link
2295 * count) must be written to disk before the directory entry's pointer to it.
2296 * Also, if the inode is newly allocated, the corresponding freemap must be
2297 * updated (on disk) before the directory entry's pointer. These requirements
2298 * are met via undo/redo on the directory entry's pointer, which consists
2299 * simply of the inode number.
2301 * As directory entries are added and deleted, the free space within a
2302 * directory block can become fragmented. The ufs filesystem will compact
2303 * a fragmented directory block to make space for a new entry. When this
2304 * occurs, the offsets of previously added entries change. Any "diradd"
2305 * dependency structures corresponding to these entries must be updated with
2310 * This routine is called after the in-memory inode's link
2311 * count has been incremented, but before the directory entry's
2312 * pointer to the inode has been set.
2315 * bp: buffer containing directory block
2316 * dp: inode for directory
2317 * diroffset: offset of new entry in directory
2318 * newinum: inode referenced by new directory entry
2319 * newdirbp: non-NULL => contents of new mkdir
2322 softdep_setup_directory_add(struct buf *bp, struct inode *dp, off_t diroffset,
2323 ino_t newinum, struct buf *newdirbp)
2325 int offset; /* offset of new entry within directory block */
2326 ufs_lbn_t lbn; /* block in directory containing new entry */
2329 struct pagedep *pagedep;
2330 struct inodedep *inodedep;
2331 struct mkdir *mkdir1, *mkdir2;
2334 * Whiteouts have no dependencies.
2336 if (newinum == WINO) {
2337 if (newdirbp != NULL)
2343 lbn = lblkno(fs, diroffset);
2344 offset = blkoff(fs, diroffset);
2345 dap = kmalloc(sizeof(struct diradd), M_DIRADD,
2346 M_SOFTDEP_FLAGS | M_ZERO);
2347 dap->da_list.wk_type = D_DIRADD;
2348 dap->da_offset = offset;
2349 dap->da_newinum = newinum;
2350 dap->da_state = ATTACHED;
2351 if (newdirbp == NULL) {
2352 dap->da_state |= DEPCOMPLETE;
2355 dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
2356 mkdir1 = kmalloc(sizeof(struct mkdir), M_MKDIR,
2358 mkdir1->md_list.wk_type = D_MKDIR;
2359 mkdir1->md_state = MKDIR_BODY;
2360 mkdir1->md_diradd = dap;
2361 mkdir2 = kmalloc(sizeof(struct mkdir), M_MKDIR,
2363 mkdir2->md_list.wk_type = D_MKDIR;
2364 mkdir2->md_state = MKDIR_PARENT;
2365 mkdir2->md_diradd = dap;
2367 * Dependency on "." and ".." being written to disk.
2369 mkdir1->md_buf = newdirbp;
2371 LIST_INSERT_HEAD(&mkdirlisthd, mkdir1, md_mkdirs);
2372 WORKLIST_INSERT_BP(newdirbp, &mkdir1->md_list);
2376 * Dependency on link count increase for parent directory
2379 if (inodedep_lookup(dp->i_fs, dp->i_number, 0, &inodedep) == 0
2380 || (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2381 dap->da_state &= ~MKDIR_PARENT;
2382 WORKITEM_FREE(mkdir2, D_MKDIR);
2384 LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
2385 WORKLIST_INSERT(&inodedep->id_bufwait,&mkdir2->md_list);
2389 * Link into parent directory pagedep to await its being written.
2391 if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2392 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
2393 dap->da_pagedep = pagedep;
2394 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
2397 * Link into its inodedep. Put it on the id_bufwait list if the inode
2398 * is not yet written. If it is written, do the post-inode write
2399 * processing to put it on the id_pendinghd list.
2401 (void) inodedep_lookup(fs, newinum, DEPALLOC, &inodedep);
2402 if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
2403 diradd_inode_written(dap, inodedep);
2405 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2410 * This procedure is called to change the offset of a directory
2411 * entry when compacting a directory block which must be owned
2412 * exclusively by the caller. Note that the actual entry movement
2413 * must be done in this procedure to ensure that no I/O completions
2414 * occur while the move is in progress.
2417 * dp: inode for directory
2418 * base: address of dp->i_offset
2419 * oldloc: address of old directory location
2420 * newloc: address of new directory location
2421 * entrysize: size of directory entry
2424 softdep_change_directoryentry_offset(struct inode *dp, caddr_t base,
2425 caddr_t oldloc, caddr_t newloc,
2428 int offset, oldoffset, newoffset;
2429 struct pagedep *pagedep;
2434 lbn = lblkno(dp->i_fs, dp->i_offset);
2435 offset = blkoff(dp->i_fs, dp->i_offset);
2436 if (pagedep_lookup(dp, lbn, 0, &pagedep) == 0)
2438 oldoffset = offset + (oldloc - base);
2439 newoffset = offset + (newloc - base);
2441 LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(oldoffset)], da_pdlist) {
2442 if (dap->da_offset != oldoffset)
2444 dap->da_offset = newoffset;
2445 if (DIRADDHASH(newoffset) == DIRADDHASH(oldoffset))
2447 LIST_REMOVE(dap, da_pdlist);
2448 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(newoffset)],
2454 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist) {
2455 if (dap->da_offset == oldoffset) {
2456 dap->da_offset = newoffset;
2462 bcopy(oldloc, newloc, entrysize);
2467 * Free a diradd dependency structure. This routine must be called
2468 * with splbio interrupts blocked.
2471 free_diradd(struct diradd *dap)
2473 struct dirrem *dirrem;
2474 struct pagedep *pagedep;
2475 struct inodedep *inodedep;
2476 struct mkdir *mkdir, *nextmd;
2478 KKASSERT(lock_held(&lk) > 0);
2480 WORKLIST_REMOVE(&dap->da_list);
2481 LIST_REMOVE(dap, da_pdlist);
2482 if ((dap->da_state & DIRCHG) == 0) {
2483 pagedep = dap->da_pagedep;
2485 dirrem = dap->da_previous;
2486 pagedep = dirrem->dm_pagedep;
2487 dirrem->dm_dirinum = pagedep->pd_ino;
2488 add_to_worklist(&dirrem->dm_list);
2490 if (inodedep_lookup(VFSTOUFS(pagedep->pd_mnt)->um_fs, dap->da_newinum,
2492 (void) free_inodedep(inodedep);
2493 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
2494 for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
2495 nextmd = LIST_NEXT(mkdir, md_mkdirs);
2496 if (mkdir->md_diradd != dap)
2498 dap->da_state &= ~mkdir->md_state;
2499 WORKLIST_REMOVE(&mkdir->md_list);
2500 LIST_REMOVE(mkdir, md_mkdirs);
2501 WORKITEM_FREE(mkdir, D_MKDIR);
2503 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
2505 panic("free_diradd: unfound ref");
2508 WORKITEM_FREE(dap, D_DIRADD);
2512 * Directory entry removal dependencies.
2514 * When removing a directory entry, the entry's inode pointer must be
2515 * zero'ed on disk before the corresponding inode's link count is decremented
2516 * (possibly freeing the inode for re-use). This dependency is handled by
2517 * updating the directory entry but delaying the inode count reduction until
2518 * after the directory block has been written to disk. After this point, the
2519 * inode count can be decremented whenever it is convenient.
2523 * This routine should be called immediately after removing
2524 * a directory entry. The inode's link count should not be
2525 * decremented by the calling procedure -- the soft updates
2526 * code will do this task when it is safe.
2529 * bp: buffer containing directory block
2530 * dp: inode for the directory being modified
2531 * ip: inode for directory entry being removed
2532 * isrmdir: indicates if doing RMDIR
2535 softdep_setup_remove(struct buf *bp, struct inode *dp, struct inode *ip,
2538 struct dirrem *dirrem, *prevdirrem;
2541 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.
2543 dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
2546 * If the COMPLETE flag is clear, then there were no active
2547 * entries and we want to roll back to a zeroed entry until
2548 * the new inode is committed to disk. If the COMPLETE flag is
2549 * set then we have deleted an entry that never made it to
2550 * disk. If the entry we deleted resulted from a name change,
2551 * then the old name still resides on disk. We cannot delete
2552 * its inode (returned to us in prevdirrem) until the zeroed
2553 * directory entry gets to disk. The new inode has never been
2554 * referenced on the disk, so can be deleted immediately.
2556 if ((dirrem->dm_state & COMPLETE) == 0) {
2557 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
2561 if (prevdirrem != NULL)
2562 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
2563 prevdirrem, dm_next);
2564 dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
2566 handle_workitem_remove(dirrem);
2571 * Allocate a new dirrem if appropriate and return it along with
2572 * its associated pagedep. Called without a lock, returns with lock.
2574 static long num_dirrem; /* number of dirrem allocated */
2578 * bp: buffer containing directory block
2579 * dp: inode for the directory being modified
2580 * ip: inode for directory entry being removed
2581 * isrmdir: indicates if doing RMDIR
2582 * prevdirremp: previously referenced inode, if any
2584 static struct dirrem *
2585 newdirrem(struct buf *bp, struct inode *dp, struct inode *ip,
2586 int isrmdir, struct dirrem **prevdirremp)
2591 struct dirrem *dirrem;
2592 struct pagedep *pagedep;
2595 * Whiteouts have no deletion dependencies.
2598 panic("newdirrem: whiteout");
2600 * If we are over our limit, try to improve the situation.
2601 * Limiting the number of dirrem structures will also limit
2602 * the number of freefile and freeblks structures.
2604 if (num_dirrem > max_softdeps / 2 && speedup_syncer() == 0)
2605 (void) request_cleanup(FLUSH_REMOVE, 0);
2607 dirrem = kmalloc(sizeof(struct dirrem), M_DIRREM,
2608 M_SOFTDEP_FLAGS | M_ZERO);
2609 dirrem->dm_list.wk_type = D_DIRREM;
2610 dirrem->dm_state = isrmdir ? RMDIR : 0;
2611 dirrem->dm_mnt = ITOV(ip)->v_mount;
2612 dirrem->dm_oldinum = ip->i_number;
2613 *prevdirremp = NULL;
2616 lbn = lblkno(dp->i_fs, dp->i_offset);
2617 offset = blkoff(dp->i_fs, dp->i_offset);
2618 if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2619 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
2620 dirrem->dm_pagedep = pagedep;
2622 * Check for a diradd dependency for the same directory entry.
2623 * If present, then both dependencies become obsolete and can
2624 * be de-allocated. Check for an entry on both the pd_dirraddhd
2625 * list and the pd_pendinghd list.
2628 LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
2629 if (dap->da_offset == offset)
2633 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
2634 if (dap->da_offset == offset)
2640 * Must be ATTACHED at this point.
2642 if ((dap->da_state & ATTACHED) == 0) {
2644 panic("newdirrem: not ATTACHED");
2646 if (dap->da_newinum != ip->i_number) {
2648 panic("newdirrem: inum %"PRId64" should be %"PRId64,
2649 ip->i_number, dap->da_newinum);
2652 * If we are deleting a changed name that never made it to disk,
2653 * then return the dirrem describing the previous inode (which
2654 * represents the inode currently referenced from this entry on disk).
2656 if ((dap->da_state & DIRCHG) != 0) {
2657 *prevdirremp = dap->da_previous;
2658 dap->da_state &= ~DIRCHG;
2659 dap->da_pagedep = pagedep;
2662 * We are deleting an entry that never made it to disk.
2663 * Mark it COMPLETE so we can delete its inode immediately.
2665 dirrem->dm_state |= COMPLETE;
2671 * Directory entry change dependencies.
2673 * Changing an existing directory entry requires that an add operation
2674 * be completed first followed by a deletion. The semantics for the addition
2675 * are identical to the description of adding a new entry above except
2676 * that the rollback is to the old inode number rather than zero. Once
2677 * the addition dependency is completed, the removal is done as described
2678 * in the removal routine above.
2682 * This routine should be called immediately after changing
2683 * a directory entry. The inode's link count should not be
2684 * decremented by the calling procedure -- the soft updates
2685 * code will perform this task when it is safe.
2688 * bp: buffer containing directory block
2689 * dp: inode for the directory being modified
2690 * ip: inode for directory entry being removed
2691 * newinum: new inode number for changed entry
2692 * isrmdir: indicates if doing RMDIR
2695 softdep_setup_directory_change(struct buf *bp, struct inode *dp,
2696 struct inode *ip, ino_t newinum,
2700 struct diradd *dap = NULL;
2701 struct dirrem *dirrem, *prevdirrem;
2702 struct pagedep *pagedep;
2703 struct inodedep *inodedep;
2705 offset = blkoff(dp->i_fs, dp->i_offset);
2708 * Whiteouts do not need diradd dependencies.
2710 if (newinum != WINO) {
2711 dap = kmalloc(sizeof(struct diradd), M_DIRADD,
2712 M_SOFTDEP_FLAGS | M_ZERO);
2713 dap->da_list.wk_type = D_DIRADD;
2714 dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
2715 dap->da_offset = offset;
2716 dap->da_newinum = newinum;
2720 * Allocate a new dirrem and ACQUIRE_LOCK.
2722 dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
2723 pagedep = dirrem->dm_pagedep;
2725 * The possible values for isrmdir:
2726 * 0 - non-directory file rename
2727 * 1 - directory rename within same directory
2728 * inum - directory rename to new directory of given inode number
2729 * When renaming to a new directory, we are both deleting and
2730 * creating a new directory entry, so the link count on the new
2731 * directory should not change. Thus we do not need the followup
2732 * dirrem which is usually done in handle_workitem_remove. We set
2733 * the DIRCHG flag to tell handle_workitem_remove to skip the
2737 dirrem->dm_state |= DIRCHG;
2740 * Whiteouts have no additional dependencies,
2741 * so just put the dirrem on the correct list.
2743 if (newinum == WINO) {
2744 if ((dirrem->dm_state & COMPLETE) == 0) {
2745 LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
2748 dirrem->dm_dirinum = pagedep->pd_ino;
2749 add_to_worklist(&dirrem->dm_list);
2756 * If the COMPLETE flag is clear, then there were no active
2757 * entries and we want to roll back to the previous inode until
2758 * the new inode is committed to disk. If the COMPLETE flag is
2759 * set, then we have deleted an entry that never made it to disk.
2760 * If the entry we deleted resulted from a name change, then the old
2761 * inode reference still resides on disk. Any rollback that we do
2762 * needs to be to that old inode (returned to us in prevdirrem). If
2763 * the entry we deleted resulted from a create, then there is
2764 * no entry on the disk, so we want to roll back to zero rather
2765 * than the uncommitted inode. In either of the COMPLETE cases we
2766 * want to immediately free the unwritten and unreferenced inode.
2768 if ((dirrem->dm_state & COMPLETE) == 0) {
2769 dap->da_previous = dirrem;
2771 if (prevdirrem != NULL) {
2772 dap->da_previous = prevdirrem;
2774 dap->da_state &= ~DIRCHG;
2775 dap->da_pagedep = pagedep;
2777 dirrem->dm_dirinum = pagedep->pd_ino;
2778 add_to_worklist(&dirrem->dm_list);
2781 * Link into its inodedep. Put it on the id_bufwait list if the inode
2782 * is not yet written. If it is written, do the post-inode write
2783 * processing to put it on the id_pendinghd list.
2785 if (inodedep_lookup(dp->i_fs, newinum, DEPALLOC, &inodedep) == 0 ||
2786 (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2787 dap->da_state |= COMPLETE;
2788 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
2789 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
2791 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
2793 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2799 * Called whenever the link count on an inode is changed.
2800 * It creates an inode dependency so that the new reference(s)
2801 * to the inode cannot be committed to disk until the updated
2802 * inode has been written.
2805 * ip: the inode with the increased link count
2808 softdep_change_linkcnt(struct inode *ip)
2810 struct inodedep *inodedep;
2813 (void) inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC, &inodedep);
2814 if (ip->i_nlink < ip->i_effnlink) {
2816 panic("softdep_change_linkcnt: bad delta");
2818 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2823 * This workitem decrements the inode's link count.
2824 * If the link count reaches zero, the file is removed.
2827 handle_workitem_remove(struct dirrem *dirrem)
2829 struct inodedep *inodedep;
2835 error = VFS_VGET(dirrem->dm_mnt, NULL, dirrem->dm_oldinum, &vp);
2837 softdep_error("handle_workitem_remove: vget", error);
2842 if ((inodedep_lookup(ip->i_fs, dirrem->dm_oldinum, 0, &inodedep)) == 0){
2844 panic("handle_workitem_remove: lost inodedep");
2847 * Normal file deletion.
2849 if ((dirrem->dm_state & RMDIR) == 0) {
2851 ip->i_flag |= IN_CHANGE;
2852 if (ip->i_nlink < ip->i_effnlink) {
2854 panic("handle_workitem_remove: bad file delta");
2856 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2860 WORKITEM_FREE(dirrem, D_DIRREM);
2864 * Directory deletion. Decrement reference count for both the
2865 * just deleted parent directory entry and the reference for ".".
2866 * Next truncate the directory to length zero. When the
2867 * truncation completes, arrange to have the reference count on
2868 * the parent decremented to account for the loss of "..".
2871 ip->i_flag |= IN_CHANGE;
2872 if (ip->i_nlink < ip->i_effnlink) {
2874 panic("handle_workitem_remove: bad dir delta");
2876 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2878 if ((error = ffs_truncate(vp, (off_t)0, 0, proc0.p_ucred)) != 0)
2879 softdep_error("handle_workitem_remove: truncate", error);
2881 * Rename a directory to a new parent. Since, we are both deleting
2882 * and creating a new directory entry, the link count on the new
2883 * directory should not change. Thus we skip the followup dirrem.
2885 if (dirrem->dm_state & DIRCHG) {
2888 WORKITEM_FREE(dirrem, D_DIRREM);
2892 * If the inodedep does not exist, then the zero'ed inode has
2893 * been written to disk. If the allocated inode has never been
2894 * written to disk, then the on-disk inode is zero'ed. In either
2895 * case we can remove the file immediately.
2898 dirrem->dm_state = 0;
2899 oldinum = dirrem->dm_oldinum;
2900 dirrem->dm_oldinum = dirrem->dm_dirinum;
2901 if (inodedep_lookup(ip->i_fs, oldinum, 0, &inodedep) == 0 ||
2902 check_inode_unwritten(inodedep)) {
2905 handle_workitem_remove(dirrem);
2908 WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
2910 ip->i_flag |= IN_CHANGE;
2916 * Inode de-allocation dependencies.
2918 * When an inode's link count is reduced to zero, it can be de-allocated. We
2919 * found it convenient to postpone de-allocation until after the inode is
2920 * written to disk with its new link count (zero). At this point, all of the
2921 * on-disk inode's block pointers are nullified and, with careful dependency
2922 * list ordering, all dependencies related to the inode will be satisfied and
2923 * the corresponding dependency structures de-allocated. So, if/when the
2924 * inode is reused, there will be no mixing of old dependencies with new
2925 * ones. This artificial dependency is set up by the block de-allocation
2926 * procedure above (softdep_setup_freeblocks) and completed by the
2927 * following procedure.
2930 handle_workitem_freefile(struct freefile *freefile)
2934 struct inodedep *idp;
2939 error = inodedep_lookup(freefile->fx_fs, freefile->fx_oldinum, 0, &idp);
2942 panic("handle_workitem_freefile: inodedep survived");
2944 tip.i_devvp = freefile->fx_devvp;
2945 tip.i_dev = freefile->fx_devvp->v_rdev;
2946 tip.i_fs = freefile->fx_fs;
2948 if ((error = ffs_freefile(&vp, freefile->fx_oldinum, freefile->fx_mode)) != 0)
2949 softdep_error("handle_workitem_freefile", error);
2950 WORKITEM_FREE(freefile, D_FREEFILE);
2954 * Helper function which unlinks marker element from work list and returns
2955 * the next element on the list.
2957 static __inline struct worklist *
2958 markernext(struct worklist *marker)
2960 struct worklist *next;
2962 next = LIST_NEXT(marker, wk_list);
2963 LIST_REMOVE(marker, wk_list);
2968 * checkread, checkwrite
2970 * bioops callback - hold io_token
2973 softdep_checkread(struct buf *bp)
2975 /* nothing to do, mp lock not needed */
2980 * bioops callback - hold io_token
2983 softdep_checkwrite(struct buf *bp)
2985 /* nothing to do, mp lock not needed */
2992 * The dependency structures constructed above are most actively used when file
2993 * system blocks are written to disk. No constraints are placed on when a
2994 * block can be written, but unsatisfied update dependencies are made safe by
2995 * modifying (or replacing) the source memory for the duration of the disk
2996 * write. When the disk write completes, the memory block is again brought
2999 * In-core inode structure reclamation.
3001 * Because there are a finite number of "in-core" inode structures, they are
3002 * reused regularly. By transferring all inode-related dependencies to the
3003 * in-memory inode block and indexing them separately (via "inodedep"s), we
3004 * can allow "in-core" inode structures to be reused at any time and avoid
3005 * any increase in contention.
3007 * Called just before entering the device driver to initiate a new disk I/O.
3008 * The buffer must be locked, thus, no I/O completion operations can occur
3009 * while we are manipulating its associated dependencies.
3011 * bioops callback - hold io_token
3014 * bp: structure describing disk write to occur
3017 softdep_disk_io_initiation(struct buf *bp)
3019 struct worklist *wk;
3020 struct worklist marker;
3021 struct indirdep *indirdep;
3024 * We only care about write operations. There should never
3025 * be dependencies for reads.
3027 if (bp->b_cmd == BUF_CMD_READ)
3028 panic("softdep_disk_io_initiation: read");
3031 marker.wk_type = D_LAST + 1; /* Not a normal workitem */
3034 * Do any necessary pre-I/O processing.
3036 for (wk = LIST_FIRST(&bp->b_dep); wk; wk = markernext(&marker)) {
3037 LIST_INSERT_AFTER(wk, &marker, wk_list);
3039 switch (wk->wk_type) {
3041 initiate_write_filepage(WK_PAGEDEP(wk), bp);
3045 initiate_write_inodeblock(WK_INODEDEP(wk), bp);
3049 indirdep = WK_INDIRDEP(wk);
3050 if (indirdep->ir_state & GOINGAWAY)
3051 panic("disk_io_initiation: indirdep gone");
3053 * If there are no remaining dependencies, this
3054 * will be writing the real pointers, so the
3055 * dependency can be freed.
3057 if (LIST_FIRST(&indirdep->ir_deplisthd) == NULL) {
3058 indirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
3059 brelse(indirdep->ir_savebp);
3060 /* inline expand WORKLIST_REMOVE(wk); */
3061 wk->wk_state &= ~ONWORKLIST;
3062 LIST_REMOVE(wk, wk_list);
3063 WORKITEM_FREE(indirdep, D_INDIRDEP);
3067 * Replace up-to-date version with safe version.
3069 indirdep->ir_saveddata = kmalloc(bp->b_bcount,
3073 indirdep->ir_state &= ~ATTACHED;
3074 indirdep->ir_state |= UNDONE;
3075 bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
3076 bcopy(indirdep->ir_savebp->b_data, bp->b_data,
3088 panic("handle_disk_io_initiation: Unexpected type %s",
3089 TYPENAME(wk->wk_type));
3097 * Called from within the procedure above to deal with unsatisfied
3098 * allocation dependencies in a directory. The buffer must be locked,
3099 * thus, no I/O completion operations can occur while we are
3100 * manipulating its associated dependencies.
3103 initiate_write_filepage(struct pagedep *pagedep, struct buf *bp)
3109 if (pagedep->pd_state & IOSTARTED) {
3111 * This can only happen if there is a driver that does not
3112 * understand chaining. Here biodone will reissue the call
3113 * to strategy for the incomplete buffers.
3115 kprintf("initiate_write_filepage: already started\n");
3118 pagedep->pd_state |= IOSTARTED;
3120 for (i = 0; i < DAHASHSZ; i++) {
3121 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
3122 ep = (struct direct *)
3123 ((char *)bp->b_data + dap->da_offset);
3124 if (ep->d_ino != dap->da_newinum) {
3126 panic("%s: dir inum %d != new %"PRId64,
3127 "initiate_write_filepage",
3128 ep->d_ino, dap->da_newinum);
3130 if (dap->da_state & DIRCHG)
3131 ep->d_ino = dap->da_previous->dm_oldinum;
3134 dap->da_state &= ~ATTACHED;
3135 dap->da_state |= UNDONE;
3142 * Called from within the procedure above to deal with unsatisfied
3143 * allocation dependencies in an inodeblock. The buffer must be
3144 * locked, thus, no I/O completion operations can occur while we
3145 * are manipulating its associated dependencies.
3148 * bp: The inode block
3151 initiate_write_inodeblock(struct inodedep *inodedep, struct buf *bp)
3153 struct allocdirect *adp, *lastadp;
3154 struct ufs1_dinode *dp;
3155 struct ufs1_dinode *sip;
3157 ufs_lbn_t prevlbn = 0;
3160 if (inodedep->id_state & IOSTARTED)
3161 panic("initiate_write_inodeblock: already started");
3162 inodedep->id_state |= IOSTARTED;
3163 fs = inodedep->id_fs;
3164 dp = (struct ufs1_dinode *)bp->b_data +
3165 ino_to_fsbo(fs, inodedep->id_ino);
3167 * If the bitmap is not yet written, then the allocated
3168 * inode cannot be written to disk.
3170 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
3171 if (inodedep->id_savedino != NULL)
3172 panic("initiate_write_inodeblock: already doing I/O");
3173 sip = kmalloc(sizeof(struct ufs1_dinode), M_INODEDEP,
3175 inodedep->id_savedino = sip;
3176 *inodedep->id_savedino = *dp;
3177 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
3178 dp->di_gen = inodedep->id_savedino->di_gen;
3182 * If no dependencies, then there is nothing to roll back.
3184 inodedep->id_savedsize = dp->di_size;
3185 if (TAILQ_FIRST(&inodedep->id_inoupdt) == NULL)
3188 * Set the dependencies to busy.
3191 for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3192 adp = TAILQ_NEXT(adp, ad_next)) {
3194 if (deplist != 0 && prevlbn >= adp->ad_lbn) {
3196 panic("softdep_write_inodeblock: lbn order");
3198 prevlbn = adp->ad_lbn;
3199 if (adp->ad_lbn < NDADDR &&
3200 dp->di_db[adp->ad_lbn] != adp->ad_newblkno) {
3202 panic("%s: direct pointer #%ld mismatch %d != %d",
3203 "softdep_write_inodeblock", adp->ad_lbn,
3204 dp->di_db[adp->ad_lbn], adp->ad_newblkno);
3206 if (adp->ad_lbn >= NDADDR &&
3207 dp->di_ib[adp->ad_lbn - NDADDR] != adp->ad_newblkno) {
3209 panic("%s: indirect pointer #%ld mismatch %d != %d",
3210 "softdep_write_inodeblock", adp->ad_lbn - NDADDR,
3211 dp->di_ib[adp->ad_lbn - NDADDR], adp->ad_newblkno);
3213 deplist |= 1 << adp->ad_lbn;
3214 if ((adp->ad_state & ATTACHED) == 0) {
3216 panic("softdep_write_inodeblock: Unknown state 0x%x",
3219 #endif /* DIAGNOSTIC */
3220 adp->ad_state &= ~ATTACHED;
3221 adp->ad_state |= UNDONE;
3224 * The on-disk inode cannot claim to be any larger than the last
3225 * fragment that has been written. Otherwise, the on-disk inode
3226 * might have fragments that were not the last block in the file
3227 * which would corrupt the filesystem.
3229 for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3230 lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
3231 if (adp->ad_lbn >= NDADDR)
3233 dp->di_db[adp->ad_lbn] = adp->ad_oldblkno;
3234 /* keep going until hitting a rollback to a frag */
3235 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
3237 dp->di_size = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
3238 for (i = adp->ad_lbn + 1; i < NDADDR; i++) {
3240 if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0) {
3242 panic("softdep_write_inodeblock: lost dep1");
3244 #endif /* DIAGNOSTIC */
3247 for (i = 0; i < NIADDR; i++) {
3249 if (dp->di_ib[i] != 0 &&
3250 (deplist & ((1 << NDADDR) << i)) == 0) {
3252 panic("softdep_write_inodeblock: lost dep2");
3254 #endif /* DIAGNOSTIC */
3261 * If we have zero'ed out the last allocated block of the file,
3262 * roll back the size to the last currently allocated block.
3263 * We know that this last allocated block is a full-sized as
3264 * we already checked for fragments in the loop above.
3266 if (lastadp != NULL &&
3267 dp->di_size <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
3268 for (i = lastadp->ad_lbn; i >= 0; i--)
3269 if (dp->di_db[i] != 0)
3271 dp->di_size = (i + 1) * fs->fs_bsize;
3274 * The only dependencies are for indirect blocks.
3276 * The file size for indirect block additions is not guaranteed.
3277 * Such a guarantee would be non-trivial to achieve. The conventional
3278 * synchronous write implementation also does not make this guarantee.
3279 * Fsck should catch and fix discrepancies. Arguably, the file size
3280 * can be over-estimated without destroying integrity when the file
3281 * moves into the indirect blocks (i.e., is large). If we want to
3282 * postpone fsck, we are stuck with this argument.
3284 for (; adp; adp = TAILQ_NEXT(adp, ad_next))
3285 dp->di_ib[adp->ad_lbn - NDADDR] = 0;
3290 * This routine is called during the completion interrupt
3291 * service routine for a disk write (from the procedure called
3292 * by the device driver to inform the filesystem caches of
3293 * a request completion). It should be called early in this
3294 * procedure, before the block is made available to other
3295 * processes or other routines are called.
3297 * bioops callback - hold io_token
3300 * bp: describes the completed disk write
3303 softdep_disk_write_complete(struct buf *bp)
3305 struct worklist *wk;
3306 struct workhead reattach;
3307 struct newblk *newblk;
3308 struct allocindir *aip;
3309 struct allocdirect *adp;
3310 struct indirdep *indirdep;
3311 struct inodedep *inodedep;
3312 struct bmsafemap *bmsafemap;
3316 LIST_INIT(&reattach);
3317 while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
3318 WORKLIST_REMOVE(wk);
3319 switch (wk->wk_type) {
3322 if (handle_written_filepage(WK_PAGEDEP(wk), bp))
3323 WORKLIST_INSERT(&reattach, wk);
3327 if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
3328 WORKLIST_INSERT(&reattach, wk);
3332 bmsafemap = WK_BMSAFEMAP(wk);
3333 while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkhd))) {
3334 newblk->nb_state |= DEPCOMPLETE;
3335 newblk->nb_bmsafemap = NULL;
3336 LIST_REMOVE(newblk, nb_deps);
3339 LIST_FIRST(&bmsafemap->sm_allocdirecthd))) {
3340 adp->ad_state |= DEPCOMPLETE;
3342 LIST_REMOVE(adp, ad_deps);
3343 handle_allocdirect_partdone(adp);
3346 LIST_FIRST(&bmsafemap->sm_allocindirhd))) {
3347 aip->ai_state |= DEPCOMPLETE;
3349 LIST_REMOVE(aip, ai_deps);
3350 handle_allocindir_partdone(aip);
3353 LIST_FIRST(&bmsafemap->sm_inodedephd)) != NULL) {
3354 inodedep->id_state |= DEPCOMPLETE;
3355 LIST_REMOVE(inodedep, id_deps);
3356 inodedep->id_buf = NULL;
3358 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
3362 handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
3366 adp = WK_ALLOCDIRECT(wk);
3367 adp->ad_state |= COMPLETE;
3368 handle_allocdirect_partdone(adp);
3372 aip = WK_ALLOCINDIR(wk);
3373 aip->ai_state |= COMPLETE;
3374 handle_allocindir_partdone(aip);
3378 indirdep = WK_INDIRDEP(wk);
3379 if (indirdep->ir_state & GOINGAWAY) {
3380 panic("disk_write_complete: indirdep gone");
3382 bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
3383 kfree(indirdep->ir_saveddata, M_INDIRDEP);
3384 indirdep->ir_saveddata = 0;
3385 indirdep->ir_state &= ~UNDONE;
3386 indirdep->ir_state |= ATTACHED;
3387 while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
3388 handle_allocindir_partdone(aip);
3389 if (aip == LIST_FIRST(&indirdep->ir_donehd)) {
3390 panic("disk_write_complete: not gone");
3393 WORKLIST_INSERT(&reattach, wk);
3394 if ((bp->b_flags & B_DELWRI) == 0)
3395 stat_indir_blk_ptrs++;
3400 panic("handle_disk_write_complete: Unknown type %s",
3401 TYPENAME(wk->wk_type));
3406 * Reattach any requests that must be redone.
3408 while ((wk = LIST_FIRST(&reattach)) != NULL) {
3409 WORKLIST_REMOVE(wk);
3410 WORKLIST_INSERT_BP(bp, wk);
3417 * Called from within softdep_disk_write_complete above. Note that
3418 * this routine is always called from interrupt level with further
3419 * splbio interrupts blocked.
3422 * adp: the completed allocdirect
3425 handle_allocdirect_partdone(struct allocdirect *adp)
3427 struct allocdirect *listadp;
3428 struct inodedep *inodedep;
3431 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3433 if (adp->ad_buf != NULL)
3434 panic("handle_allocdirect_partdone: dangling dep");
3437 * The on-disk inode cannot claim to be any larger than the last
3438 * fragment that has been written. Otherwise, the on-disk inode
3439 * might have fragments that were not the last block in the file
3440 * which would corrupt the filesystem. Thus, we cannot free any
3441 * allocdirects after one whose ad_oldblkno claims a fragment as
3442 * these blocks must be rolled back to zero before writing the inode.
3443 * We check the currently active set of allocdirects in id_inoupdt.
3445 inodedep = adp->ad_inodedep;
3446 bsize = inodedep->id_fs->fs_bsize;
3447 TAILQ_FOREACH(listadp, &inodedep->id_inoupdt, ad_next) {
3448 /* found our block */
3451 /* continue if ad_oldlbn is not a fragment */
3452 if (listadp->ad_oldsize == 0 ||
3453 listadp->ad_oldsize == bsize)
3455 /* hit a fragment */
3459 * If we have reached the end of the current list without
3460 * finding the just finished dependency, then it must be
3461 * on the future dependency list. Future dependencies cannot
3462 * be freed until they are moved to the current list.
3464 if (listadp == NULL) {
3466 TAILQ_FOREACH(listadp, &inodedep->id_newinoupdt, ad_next)
3467 /* found our block */
3470 if (listadp == NULL)
3471 panic("handle_allocdirect_partdone: lost dep");
3476 * If we have found the just finished dependency, then free
3477 * it along with anything that follows it that is complete.
3479 for (; adp; adp = listadp) {
3480 listadp = TAILQ_NEXT(adp, ad_next);
3481 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3483 free_allocdirect(&inodedep->id_inoupdt, adp, 1);
3488 * Called from within softdep_disk_write_complete above. Note that
3489 * this routine is always called from interrupt level with further
3490 * splbio interrupts blocked.
3493 * aip: the completed allocindir
3496 handle_allocindir_partdone(struct allocindir *aip)
3498 struct indirdep *indirdep;
3500 if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
3502 if (aip->ai_buf != NULL)
3503 panic("handle_allocindir_partdone: dangling dependency");
3505 indirdep = aip->ai_indirdep;
3506 if (indirdep->ir_state & UNDONE) {
3507 LIST_REMOVE(aip, ai_next);
3508 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
3511 ((ufs_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
3513 LIST_REMOVE(aip, ai_next);
3514 if (aip->ai_freefrag != NULL)
3515 add_to_worklist(&aip->ai_freefrag->ff_list);
3516 WORKITEM_FREE(aip, D_ALLOCINDIR);
3520 * Called from within softdep_disk_write_complete above to restore
3521 * in-memory inode block contents to their most up-to-date state. Note
3522 * that this routine is always called from interrupt level with further
3523 * splbio interrupts blocked.
3526 * bp: buffer containing the inode block
3529 handle_written_inodeblock(struct inodedep *inodedep, struct buf *bp)
3531 struct worklist *wk, *filefree;
3532 struct allocdirect *adp, *nextadp;
3533 struct ufs1_dinode *dp;
3536 if ((inodedep->id_state & IOSTARTED) == 0)
3537 panic("handle_written_inodeblock: not started");
3539 inodedep->id_state &= ~IOSTARTED;
3540 dp = (struct ufs1_dinode *)bp->b_data +
3541 ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
3543 * If we had to rollback the inode allocation because of
3544 * bitmaps being incomplete, then simply restore it.
3545 * Keep the block dirty so that it will not be reclaimed until
3546 * all associated dependencies have been cleared and the
3547 * corresponding updates written to disk.
3549 if (inodedep->id_savedino != NULL) {
3550 *dp = *inodedep->id_savedino;
3551 kfree(inodedep->id_savedino, M_INODEDEP);
3552 inodedep->id_savedino = NULL;
3553 if ((bp->b_flags & B_DELWRI) == 0)
3554 stat_inode_bitmap++;
3558 inodedep->id_state |= COMPLETE;
3560 * Roll forward anything that had to be rolled back before
3561 * the inode could be updated.
3564 for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
3565 nextadp = TAILQ_NEXT(adp, ad_next);
3566 if (adp->ad_state & ATTACHED)
3567 panic("handle_written_inodeblock: new entry");
3569 if (adp->ad_lbn < NDADDR) {
3570 if (dp->di_db[adp->ad_lbn] != adp->ad_oldblkno) {
3571 panic("%s: %s #%ld mismatch %d != %d",
3572 "handle_written_inodeblock",
3573 "direct pointer", adp->ad_lbn,
3574 dp->di_db[adp->ad_lbn], adp->ad_oldblkno);
3576 dp->di_db[adp->ad_lbn] = adp->ad_newblkno;
3578 if (dp->di_ib[adp->ad_lbn - NDADDR] != 0) {
3579 panic("%s: %s #%ld allocated as %d",
3580 "handle_written_inodeblock",
3581 "indirect pointer", adp->ad_lbn - NDADDR,
3582 dp->di_ib[adp->ad_lbn - NDADDR]);
3584 dp->di_ib[adp->ad_lbn - NDADDR] = adp->ad_newblkno;
3586 adp->ad_state &= ~UNDONE;
3587 adp->ad_state |= ATTACHED;
3590 if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
3591 stat_direct_blk_ptrs++;
3593 * Reset the file size to its most up-to-date value.
3595 if (inodedep->id_savedsize == -1) {
3596 panic("handle_written_inodeblock: bad size");
3598 if (dp->di_size != inodedep->id_savedsize) {
3599 dp->di_size = inodedep->id_savedsize;
3602 inodedep->id_savedsize = -1;
3604 * If there were any rollbacks in the inode block, then it must be
3605 * marked dirty so that its will eventually get written back in
3611 * Process any allocdirects that completed during the update.
3613 if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
3614 handle_allocdirect_partdone(adp);
3616 * Process deallocations that were held pending until the
3617 * inode had been written to disk. Freeing of the inode
3618 * is delayed until after all blocks have been freed to
3619 * avoid creation of new <vfsid, inum, lbn> triples
3620 * before the old ones have been deleted.
3623 while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
3624 WORKLIST_REMOVE(wk);
3625 switch (wk->wk_type) {
3629 * We defer adding filefree to the worklist until
3630 * all other additions have been made to ensure
3631 * that it will be done after all the old blocks
3634 if (filefree != NULL) {
3635 panic("handle_written_inodeblock: filefree");
3641 handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
3645 diradd_inode_written(WK_DIRADD(wk), inodedep);
3649 wk->wk_state |= COMPLETE;
3650 if ((wk->wk_state & ALLCOMPLETE) != ALLCOMPLETE)
3652 /* -- fall through -- */
3655 add_to_worklist(wk);
3659 panic("handle_written_inodeblock: Unknown type %s",
3660 TYPENAME(wk->wk_type));
3664 if (filefree != NULL) {
3665 if (free_inodedep(inodedep) == 0) {
3666 panic("handle_written_inodeblock: live inodedep");
3668 add_to_worklist(filefree);
3673 * If no outstanding dependencies, free it.
3675 if (free_inodedep(inodedep) || TAILQ_FIRST(&inodedep->id_inoupdt) == 0)
3677 return (hadchanges);
3681 * Process a diradd entry after its dependent inode has been written.
3682 * This routine must be called with splbio interrupts blocked.
3685 diradd_inode_written(struct diradd *dap, struct inodedep *inodedep)
3687 struct pagedep *pagedep;
3689 dap->da_state |= COMPLETE;
3690 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3691 if (dap->da_state & DIRCHG)
3692 pagedep = dap->da_previous->dm_pagedep;
3694 pagedep = dap->da_pagedep;
3695 LIST_REMOVE(dap, da_pdlist);
3696 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3698 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
3702 * Handle the completion of a mkdir dependency.
3705 handle_written_mkdir(struct mkdir *mkdir, int type)
3708 struct pagedep *pagedep;
3710 if (mkdir->md_state != type) {
3711 panic("handle_written_mkdir: bad type");
3713 dap = mkdir->md_diradd;
3714 dap->da_state &= ~type;
3715 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
3716 dap->da_state |= DEPCOMPLETE;
3717 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3718 if (dap->da_state & DIRCHG)
3719 pagedep = dap->da_previous->dm_pagedep;
3721 pagedep = dap->da_pagedep;
3722 LIST_REMOVE(dap, da_pdlist);
3723 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3725 LIST_REMOVE(mkdir, md_mkdirs);
3726 WORKITEM_FREE(mkdir, D_MKDIR);
3730 * Called from within softdep_disk_write_complete above.
3731 * A write operation was just completed. Removed inodes can
3732 * now be freed and associated block pointers may be committed.
3733 * Note that this routine is always called from interrupt level
3734 * with further splbio interrupts blocked.
3737 * bp: buffer containing the written page
3740 handle_written_filepage(struct pagedep *pagedep, struct buf *bp)
3742 struct dirrem *dirrem;
3743 struct diradd *dap, *nextdap;
3747 if ((pagedep->pd_state & IOSTARTED) == 0) {
3748 panic("handle_written_filepage: not started");
3750 pagedep->pd_state &= ~IOSTARTED;
3752 * Process any directory removals that have been committed.
3754 while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
3755 LIST_REMOVE(dirrem, dm_next);
3756 dirrem->dm_dirinum = pagedep->pd_ino;
3757 add_to_worklist(&dirrem->dm_list);
3760 * Free any directory additions that have been committed.
3762 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
3765 * Uncommitted directory entries must be restored.
3767 for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
3768 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
3770 nextdap = LIST_NEXT(dap, da_pdlist);
3771 if (dap->da_state & ATTACHED) {
3772 panic("handle_written_filepage: attached");
3774 ep = (struct direct *)
3775 ((char *)bp->b_data + dap->da_offset);
3776 ep->d_ino = dap->da_newinum;
3777 dap->da_state &= ~UNDONE;
3778 dap->da_state |= ATTACHED;
3781 * If the inode referenced by the directory has
3782 * been written out, then the dependency can be
3783 * moved to the pending list.
3785 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3786 LIST_REMOVE(dap, da_pdlist);
3787 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
3793 * If there were any rollbacks in the directory, then it must be
3794 * marked dirty so that its will eventually get written back in
3798 if ((bp->b_flags & B_DELWRI) == 0)
3803 * If no dependencies remain, the pagedep will be freed.
3804 * Otherwise it will remain to update the page before it
3805 * is written back to disk.
3807 if (LIST_FIRST(&pagedep->pd_pendinghd) == 0) {
3808 for (i = 0; i < DAHASHSZ; i++)
3809 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) != NULL)
3811 if (i == DAHASHSZ) {
3812 LIST_REMOVE(pagedep, pd_hash);
3813 WORKITEM_FREE(pagedep, D_PAGEDEP);
3821 * Writing back in-core inode structures.
3823 * The filesystem only accesses an inode's contents when it occupies an
3824 * "in-core" inode structure. These "in-core" structures are separate from
3825 * the page frames used to cache inode blocks. Only the latter are
3826 * transferred to/from the disk. So, when the updated contents of the
3827 * "in-core" inode structure are copied to the corresponding in-memory inode
3828 * block, the dependencies are also transferred. The following procedure is
3829 * called when copying a dirty "in-core" inode to a cached inode block.
3833 * Called when an inode is loaded from disk. If the effective link count
3834 * differed from the actual link count when it was last flushed, then we
3835 * need to ensure that the correct effective link count is put back.
3838 * ip: the "in_core" copy of the inode
3841 softdep_load_inodeblock(struct inode *ip)
3843 struct inodedep *inodedep;
3846 * Check for alternate nlink count.
3848 ip->i_effnlink = ip->i_nlink;
3850 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3854 ip->i_effnlink -= inodedep->id_nlinkdelta;
3859 * This routine is called just before the "in-core" inode
3860 * information is to be copied to the in-memory inode block.
3861 * Recall that an inode block contains several inodes. If
3862 * the force flag is set, then the dependencies will be
3863 * cleared so that the update can always be made. Note that
3864 * the buffer is locked when this routine is called, so we
3865 * will never be in the middle of writing the inode block
3869 * ip: the "in_core" copy of the inode
3870 * bp: the buffer containing the inode block
3871 * waitfor: nonzero => update must be allowed
3874 softdep_update_inodeblock(struct inode *ip, struct buf *bp,
3877 struct inodedep *inodedep;
3878 struct worklist *wk;
3882 * If the effective link count is not equal to the actual link
3883 * count, then we must track the difference in an inodedep while
3884 * the inode is (potentially) tossed out of the cache. Otherwise,
3885 * if there is no existing inodedep, then there are no dependencies
3889 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3891 if (ip->i_effnlink != ip->i_nlink)
3892 panic("softdep_update_inodeblock: bad link count");
3895 if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink) {
3897 panic("softdep_update_inodeblock: bad delta");
3900 * Changes have been initiated. Anything depending on these
3901 * changes cannot occur until this inode has been written.
3903 inodedep->id_state &= ~COMPLETE;
3904 if ((inodedep->id_state & ONWORKLIST) == 0)
3905 WORKLIST_INSERT_BP(bp, &inodedep->id_list);
3907 * Any new dependencies associated with the incore inode must
3908 * now be moved to the list associated with the buffer holding
3909 * the in-memory copy of the inode. Once merged process any
3910 * allocdirects that are completed by the merger.
3912 merge_inode_lists(inodedep);
3913 if (TAILQ_FIRST(&inodedep->id_inoupdt) != NULL)
3914 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt));
3916 * Now that the inode has been pushed into the buffer, the
3917 * operations dependent on the inode being written to disk
3918 * can be moved to the id_bufwait so that they will be
3919 * processed when the buffer I/O completes.
3921 while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
3922 WORKLIST_REMOVE(wk);
3923 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
3926 * Newly allocated inodes cannot be written until the bitmap
3927 * that allocates them have been written (indicated by
3928 * DEPCOMPLETE being set in id_state). If we are doing a
3929 * forced sync (e.g., an fsync on a file), we force the bitmap
3930 * to be written so that the update can be done.
3937 if ((inodedep->id_state & DEPCOMPLETE) != 0) {
3941 gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
3943 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) != 0)
3949 if ((error = bwrite(inodedep->id_buf)) != 0)
3950 softdep_error("softdep_update_inodeblock: bwrite", error);
3954 * Merge the new inode dependency list (id_newinoupdt) into the old
3955 * inode dependency list (id_inoupdt). This routine must be called
3956 * with splbio interrupts blocked.
3959 merge_inode_lists(struct inodedep *inodedep)
3961 struct allocdirect *listadp, *newadp;
3963 newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3964 for (listadp = TAILQ_FIRST(&inodedep->id_inoupdt); listadp && newadp;) {
3965 if (listadp->ad_lbn < newadp->ad_lbn) {
3966 listadp = TAILQ_NEXT(listadp, ad_next);
3969 TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3970 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
3971 if (listadp->ad_lbn == newadp->ad_lbn) {
3972 allocdirect_merge(&inodedep->id_inoupdt, newadp,
3976 newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3978 while ((newadp = TAILQ_FIRST(&inodedep->id_newinoupdt)) != NULL) {
3979 TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3980 TAILQ_INSERT_TAIL(&inodedep->id_inoupdt, newadp, ad_next);
3985 * If we are doing an fsync, then we must ensure that any directory
3986 * entries for the inode have been written after the inode gets to disk.
3988 * bioops callback - hold io_token
3991 * vp: the "in_core" copy of the inode
3994 softdep_fsync(struct vnode *vp)
3996 struct inodedep *inodedep;
3997 struct pagedep *pagedep;
3998 struct worklist *wk;
4005 int error, flushparent;
4010 * Move check from original kernel code, possibly not needed any
4011 * more with the per-mount bioops.
4013 if ((vp->v_mount->mnt_flag & MNT_SOFTDEP) == 0)
4019 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0) {
4023 if (LIST_FIRST(&inodedep->id_inowait) != NULL ||
4024 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
4025 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
4026 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL) {
4028 panic("softdep_fsync: pending ops");
4030 for (error = 0, flushparent = 0; ; ) {
4031 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
4033 if (wk->wk_type != D_DIRADD) {
4035 panic("softdep_fsync: Unexpected type %s",
4036 TYPENAME(wk->wk_type));
4038 dap = WK_DIRADD(wk);
4040 * Flush our parent if this directory entry
4041 * has a MKDIR_PARENT dependency.
4043 if (dap->da_state & DIRCHG)
4044 pagedep = dap->da_previous->dm_pagedep;
4046 pagedep = dap->da_pagedep;
4047 mnt = pagedep->pd_mnt;
4048 parentino = pagedep->pd_ino;
4049 lbn = pagedep->pd_lbn;
4050 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE) {
4052 panic("softdep_fsync: dirty");
4054 flushparent = dap->da_state & MKDIR_PARENT;
4056 * If we are being fsync'ed as part of vgone'ing this vnode,
4057 * then we will not be able to release and recover the
4058 * vnode below, so we just have to give up on writing its
4059 * directory entry out. It will eventually be written, just
4060 * not now, but then the user was not asking to have it
4061 * written, so we are not breaking any promises.
4063 if (vp->v_flag & VRECLAIMED)
4066 * We prevent deadlock by always fetching inodes from the
4067 * root, moving down the directory tree. Thus, when fetching
4068 * our parent directory, we must unlock ourselves before
4069 * requesting the lock on our parent. See the comment in
4070 * ufs_lookup for details on possible races.
4074 error = VFS_VGET(mnt, NULL, parentino, &pvp);
4075 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4080 if ((error = ffs_update(pvp, 1)) != 0) {
4086 * Flush directory page containing the inode's name.
4088 error = bread(pvp, lblktodoff(fs, lbn), blksize(fs, VTOI(pvp), lbn), &bp);
4096 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0)
4104 * Flush all the dirty bitmaps associated with the block device
4105 * before flushing the rest of the dirty blocks so as to reduce
4106 * the number of dependencies that will have to be rolled back.
4108 static int softdep_fsync_mountdev_bp(struct buf *bp, void *data);
4111 softdep_fsync_mountdev(struct vnode *vp)
4113 if (!vn_isdisk(vp, NULL))
4114 panic("softdep_fsync_mountdev: vnode not a disk");
4116 lwkt_gettoken(&vp->v_token);
4117 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
4118 softdep_fsync_mountdev_bp, vp);
4119 lwkt_reltoken(&vp->v_token);
4120 drain_output(vp, 1);
4125 softdep_fsync_mountdev_bp(struct buf *bp, void *data)
4127 struct worklist *wk;
4128 struct vnode *vp = data;
4131 * If it is already scheduled, skip to the next buffer.
4133 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT))
4135 if (bp->b_vp != vp || (bp->b_flags & B_DELWRI) == 0) {
4137 kprintf("softdep_fsync_mountdev_bp: warning, buffer %p ripped out from under vnode %p\n", bp, vp);
4141 * We are only interested in bitmaps with outstanding
4144 if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
4145 wk->wk_type != D_BMSAFEMAP) {
4157 * This routine is called when we are trying to synchronously flush a
4158 * file. This routine must eliminate any filesystem metadata dependencies
4159 * so that the syncing routine can succeed by pushing the dirty blocks
4160 * associated with the file. If any I/O errors occur, they are returned.
4162 struct softdep_sync_metadata_info {
4167 static int softdep_sync_metadata_bp(struct buf *bp, void *data);
4170 softdep_sync_metadata(struct vnode *vp, struct thread *td)
4172 struct softdep_sync_metadata_info info;
4176 * Check whether this vnode is involved in a filesystem
4177 * that is doing soft dependency processing.
4179 if (!vn_isdisk(vp, NULL)) {
4180 if (!DOINGSOFTDEP(vp))
4183 if (vp->v_rdev->si_mountpoint == NULL ||
4184 (vp->v_rdev->si_mountpoint->mnt_flag & MNT_SOFTDEP) == 0)
4187 * Ensure that any direct block dependencies have been cleared.
4190 if ((error = flush_inodedep_deps(VTOI(vp)->i_fs, VTOI(vp)->i_number))) {
4195 * For most files, the only metadata dependencies are the
4196 * cylinder group maps that allocate their inode or blocks.
4197 * The block allocation dependencies can be found by traversing
4198 * the dependency lists for any buffers that remain on their
4199 * dirty buffer list. The inode allocation dependency will
4200 * be resolved when the inode is updated with MNT_WAIT.
4201 * This work is done in two passes. The first pass grabs most
4202 * of the buffers and begins asynchronously writing them. The
4203 * only way to wait for these asynchronous writes is to sleep
4204 * on the filesystem vnode which may stay busy for a long time
4205 * if the filesystem is active. So, instead, we make a second
4206 * pass over the dependencies blocking on each write. In the
4207 * usual case we will be blocking against a write that we
4208 * initiated, so when it is done the dependency will have been
4209 * resolved. Thus the second pass is expected to end quickly.
4211 waitfor = MNT_NOWAIT;
4214 * We must wait for any I/O in progress to finish so that
4215 * all potential buffers on the dirty list will be visible.
4217 drain_output(vp, 1);
4220 info.waitfor = waitfor;
4221 lwkt_gettoken(&vp->v_token);
4222 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
4223 softdep_sync_metadata_bp, &info);
4224 lwkt_reltoken(&vp->v_token);
4227 return(-error); /* error code */
4231 * The brief unlock is to allow any pent up dependency
4232 * processing to be done. Then proceed with the second pass.
4234 if (waitfor & MNT_NOWAIT) {
4242 * If we have managed to get rid of all the dirty buffers,
4243 * then we are done. For certain directories and block
4244 * devices, we may need to do further work.
4246 * We must wait for any I/O in progress to finish so that
4247 * all potential buffers on the dirty list will be visible.
4249 drain_output(vp, 1);
4250 if (RB_EMPTY(&vp->v_rbdirty_tree)) {
4257 * If we are trying to sync a block device, some of its buffers may
4258 * contain metadata that cannot be written until the contents of some
4259 * partially written files have been written to disk. The only easy
4260 * way to accomplish this is to sync the entire filesystem (luckily
4261 * this happens rarely).
4263 if (vn_isdisk(vp, NULL) &&
4265 vp->v_rdev->si_mountpoint && !vn_islocked(vp) &&
4266 (error = VFS_SYNC(vp->v_rdev->si_mountpoint, MNT_WAIT)) != 0)
4272 softdep_sync_metadata_bp(struct buf *bp, void *data)
4274 struct softdep_sync_metadata_info *info = data;
4275 struct pagedep *pagedep;
4276 struct allocdirect *adp;
4277 struct allocindir *aip;
4278 struct worklist *wk;
4283 if (getdirtybuf(&bp, MNT_WAIT) == 0) {
4284 kprintf("softdep_sync_metadata_bp(1): caught buf %p going away\n", bp);
4287 if (bp->b_vp != info->vp || (bp->b_flags & B_DELWRI) == 0) {
4288 kprintf("softdep_sync_metadata_bp(2): caught buf %p going away vp %p\n", bp, info->vp);
4294 * As we hold the buffer locked, none of its dependencies
4297 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4298 switch (wk->wk_type) {
4301 adp = WK_ALLOCDIRECT(wk);
4302 if (adp->ad_state & DEPCOMPLETE)
4305 if (getdirtybuf(&nbp, info->waitfor) == 0)
4308 if (info->waitfor & MNT_NOWAIT) {
4310 } else if ((error = bwrite(nbp)) != 0) {
4319 aip = WK_ALLOCINDIR(wk);
4320 if (aip->ai_state & DEPCOMPLETE)
4323 if (getdirtybuf(&nbp, info->waitfor) == 0)
4326 if (info->waitfor & MNT_NOWAIT) {
4328 } else if ((error = bwrite(nbp)) != 0) {
4339 LIST_FOREACH(aip, &WK_INDIRDEP(wk)->ir_deplisthd, ai_next) {
4340 if (aip->ai_state & DEPCOMPLETE)
4343 if (getdirtybuf(&nbp, MNT_WAIT) == 0)
4346 if ((error = bwrite(nbp)) != 0) {
4357 if ((error = flush_inodedep_deps(WK_INODEDEP(wk)->id_fs,
4358 WK_INODEDEP(wk)->id_ino)) != 0) {
4368 * We are trying to sync a directory that may
4369 * have dependencies on both its own metadata
4370 * and/or dependencies on the inodes of any
4371 * recently allocated files. We walk its diradd
4372 * lists pushing out the associated inode.
4374 pagedep = WK_PAGEDEP(wk);
4375 for (i = 0; i < DAHASHSZ; i++) {
4376 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
4379 flush_pagedep_deps(info->vp,
4381 &pagedep->pd_diraddhd[i]))) {
4392 * This case should never happen if the vnode has
4393 * been properly sync'ed. However, if this function
4394 * is used at a place where the vnode has not yet
4395 * been sync'ed, this dependency can show up. So,
4396 * rather than panic, just flush it.
4398 nbp = WK_MKDIR(wk)->md_buf;
4399 if (getdirtybuf(&nbp, info->waitfor) == 0)
4402 if (info->waitfor & MNT_NOWAIT) {
4404 } else if ((error = bwrite(nbp)) != 0) {
4414 * This case should never happen if the vnode has
4415 * been properly sync'ed. However, if this function
4416 * is used at a place where the vnode has not yet
4417 * been sync'ed, this dependency can show up. So,
4418 * rather than panic, just flush it.
4420 * nbp can wind up == bp if a device node for the
4421 * same filesystem is being fsynced at the same time,
4422 * leading to a panic if we don't catch the case.
4424 nbp = WK_BMSAFEMAP(wk)->sm_buf;
4427 if (getdirtybuf(&nbp, info->waitfor) == 0)
4430 if (info->waitfor & MNT_NOWAIT) {
4432 } else if ((error = bwrite(nbp)) != 0) {
4442 panic("softdep_sync_metadata: Unknown type %s",
4443 TYPENAME(wk->wk_type));
4454 * Flush the dependencies associated with an inodedep.
4455 * Called with splbio blocked.
4458 flush_inodedep_deps(struct fs *fs, ino_t ino)
4460 struct inodedep *inodedep;
4461 struct allocdirect *adp;
4466 * This work is done in two passes. The first pass grabs most
4467 * of the buffers and begins asynchronously writing them. The
4468 * only way to wait for these asynchronous writes is to sleep
4469 * on the filesystem vnode which may stay busy for a long time
4470 * if the filesystem is active. So, instead, we make a second
4471 * pass over the dependencies blocking on each write. In the
4472 * usual case we will be blocking against a write that we
4473 * initiated, so when it is done the dependency will have been
4474 * resolved. Thus the second pass is expected to end quickly.
4475 * We give a brief window at the top of the loop to allow
4476 * any pending I/O to complete.
4478 for (waitfor = MNT_NOWAIT; ; ) {
4481 if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4483 TAILQ_FOREACH(adp, &inodedep->id_inoupdt, ad_next) {
4484 if (adp->ad_state & DEPCOMPLETE)
4487 if (getdirtybuf(&bp, waitfor) == 0) {
4488 if (waitfor & MNT_NOWAIT)
4493 if (waitfor & MNT_NOWAIT) {
4495 } else if ((error = bwrite(bp)) != 0) {
4504 TAILQ_FOREACH(adp, &inodedep->id_newinoupdt, ad_next) {
4505 if (adp->ad_state & DEPCOMPLETE)
4508 if (getdirtybuf(&bp, waitfor) == 0) {
4509 if (waitfor & MNT_NOWAIT)
4514 if (waitfor & MNT_NOWAIT) {
4516 } else if ((error = bwrite(bp)) != 0) {
4526 * If pass2, we are done, otherwise do pass 2.
4528 if (waitfor == MNT_WAIT)
4533 * Try freeing inodedep in case all dependencies have been removed.
4535 if (inodedep_lookup(fs, ino, 0, &inodedep) != 0)
4536 (void) free_inodedep(inodedep);
4541 * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
4542 * Called with splbio blocked.
4545 flush_pagedep_deps(struct vnode *pvp, struct mount *mp,
4546 struct diraddhd *diraddhdp)
4548 struct inodedep *inodedep;
4549 struct ufsmount *ump;
4552 int gotit, error = 0;
4557 while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
4559 * Flush ourselves if this directory entry
4560 * has a MKDIR_PARENT dependency.
4562 if (dap->da_state & MKDIR_PARENT) {
4564 if ((error = ffs_update(pvp, 1)) != 0)
4568 * If that cleared dependencies, go on to next.
4570 if (dap != LIST_FIRST(diraddhdp))
4572 if (dap->da_state & MKDIR_PARENT) {
4574 panic("flush_pagedep_deps: MKDIR_PARENT");
4578 * A newly allocated directory must have its "." and
4579 * ".." entries written out before its name can be
4580 * committed in its parent. We do not want or need
4581 * the full semantics of a synchronous VOP_FSYNC as
4582 * that may end up here again, once for each directory
4583 * level in the filesystem. Instead, we push the blocks
4584 * and wait for them to clear. We have to fsync twice
4585 * because the first call may choose to defer blocks
4586 * that still have dependencies, but deferral will
4587 * happen at most once.
4589 inum = dap->da_newinum;
4590 if (dap->da_state & MKDIR_BODY) {
4592 if ((error = VFS_VGET(mp, NULL, inum, &vp)) != 0)
4594 if ((error=VOP_FSYNC(vp, MNT_NOWAIT, 0)) ||
4595 (error=VOP_FSYNC(vp, MNT_NOWAIT, 0))) {
4599 drain_output(vp, 0);
4603 * If that cleared dependencies, go on to next.
4605 if (dap != LIST_FIRST(diraddhdp))
4607 if (dap->da_state & MKDIR_BODY) {
4609 panic("flush_pagedep_deps: MKDIR_BODY");
4613 * Flush the inode on which the directory entry depends.
4614 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
4615 * the only remaining dependency is that the updated inode
4616 * count must get pushed to disk. The inode has already
4617 * been pushed into its inode buffer (via VOP_UPDATE) at
4618 * the time of the reference count change. So we need only
4619 * locate that buffer, ensure that there will be no rollback
4620 * caused by a bitmap dependency, then write the inode buffer.
4622 if (inodedep_lookup(ump->um_fs, inum, 0, &inodedep) == 0) {
4624 panic("flush_pagedep_deps: lost inode");
4627 * If the inode still has bitmap dependencies,
4628 * push them to disk.
4630 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4631 gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
4633 if (gotit && (error = bwrite(inodedep->id_buf)) != 0)
4636 if (dap != LIST_FIRST(diraddhdp))
4640 * If the inode is still sitting in a buffer waiting
4641 * to be written, push it to disk.
4644 if ((error = bread(ump->um_devvp,
4645 fsbtodoff(ump->um_fs, ino_to_fsba(ump->um_fs, inum)),
4646 (int)ump->um_fs->fs_bsize, &bp)) != 0)
4648 if ((error = bwrite(bp)) != 0)
4652 * If we have failed to get rid of all the dependencies
4653 * then something is seriously wrong.
4655 if (dap == LIST_FIRST(diraddhdp)) {
4657 panic("flush_pagedep_deps: flush failed");
4666 * A large burst of file addition or deletion activity can drive the
4667 * memory load excessively high. First attempt to slow things down
4668 * using the techniques below. If that fails, this routine requests
4669 * the offending operations to fall back to running synchronously
4670 * until the memory load returns to a reasonable level.
4673 softdep_slowdown(struct vnode *vp)
4675 int max_softdeps_hard;
4677 max_softdeps_hard = max_softdeps * 11 / 10;
4678 if (num_dirrem < max_softdeps_hard / 2 &&
4679 num_inodedep < max_softdeps_hard)
4681 stat_sync_limit_hit += 1;
4686 * If memory utilization has gotten too high, deliberately slow things
4687 * down and speed up the I/O processing.
4690 request_cleanup(int resource, int islocked)
4692 struct thread *td = curthread; /* XXX */
4695 * We never hold up the filesystem syncer process.
4697 if (td == filesys_syncer)
4700 * First check to see if the work list has gotten backlogged.
4701 * If it has, co-opt this process to help clean up two entries.
4702 * Because this process may hold inodes locked, we cannot
4703 * handle any remove requests that might block on a locked
4704 * inode as that could lead to deadlock.
4706 if (num_on_worklist > max_softdeps / 10) {
4707 process_worklist_item(NULL, LK_NOWAIT);
4708 process_worklist_item(NULL, LK_NOWAIT);
4709 stat_worklist_push += 2;
4714 * If we are resource constrained on inode dependencies, try
4715 * flushing some dirty inodes. Otherwise, we are constrained
4716 * by file deletions, so try accelerating flushes of directories
4717 * with removal dependencies. We would like to do the cleanup
4718 * here, but we probably hold an inode locked at this point and
4719 * that might deadlock against one that we try to clean. So,
4720 * the best that we can do is request the syncer daemon to do
4721 * the cleanup for us.
4726 stat_ino_limit_push += 1;
4727 req_clear_inodedeps += 1;
4728 stat_countp = &stat_ino_limit_hit;
4732 stat_blk_limit_push += 1;
4733 req_clear_remove += 1;
4734 stat_countp = &stat_blk_limit_hit;
4740 panic("request_cleanup: unknown type");
4743 * Hopefully the syncer daemon will catch up and awaken us.
4744 * We wait at most tickdelay before proceeding in any case.
4749 if (!callout_active(&handle))
4750 callout_reset(&handle, tickdelay > 2 ? tickdelay : 2,
4752 interlocked_sleep(&lk, (caddr_t)&proc_waiting, 0,
4761 * Awaken processes pausing in request_cleanup and clear proc_waiting
4762 * to indicate that there is no longer a timer running.
4765 pause_timer(void *arg)
4768 wakeup_one(&proc_waiting);
4769 if (proc_waiting > 0)
4770 callout_reset(&handle, tickdelay > 2 ? tickdelay : 2,
4773 callout_deactivate(&handle);
4777 * Flush out a directory with at least one removal dependency in an effort to
4778 * reduce the number of dirrem, freefile, and freeblks dependency structures.
4781 clear_remove(struct thread *td)
4783 struct pagedep_hashhead *pagedephd;
4784 struct pagedep *pagedep;
4785 static int next = 0;
4792 for (cnt = 0; cnt < pagedep_hash; cnt++) {
4793 pagedephd = &pagedep_hashtbl[next++];
4794 if (next >= pagedep_hash)
4796 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
4797 if (LIST_FIRST(&pagedep->pd_dirremhd) == NULL)
4799 mp = pagedep->pd_mnt;
4800 ino = pagedep->pd_ino;
4802 if ((error = VFS_VGET(mp, NULL, ino, &vp)) != 0) {
4803 softdep_error("clear_remove: vget", error);
4806 if ((error = VOP_FSYNC(vp, MNT_NOWAIT, 0)))
4807 softdep_error("clear_remove: fsync", error);
4808 drain_output(vp, 0);
4817 * Clear out a block of dirty inodes in an effort to reduce
4818 * the number of inodedep dependency structures.
4820 struct clear_inodedeps_info {
4826 clear_inodedeps_mountlist_callback(struct mount *mp, void *data)
4828 struct clear_inodedeps_info *info = data;
4830 if ((mp->mnt_flag & MNT_SOFTDEP) && info->fs == VFSTOUFS(mp)->um_fs) {
4838 clear_inodedeps(struct thread *td)
4840 struct clear_inodedeps_info info;
4841 struct inodedep_hashhead *inodedephd;
4842 struct inodedep *inodedep;
4843 static int next = 0;
4847 ino_t firstino, lastino, ino;
4851 * Pick a random inode dependency to be cleared.
4852 * We will then gather up all the inodes in its block
4853 * that have dependencies and flush them out.
4855 for (cnt = 0; cnt < inodedep_hash; cnt++) {
4856 inodedephd = &inodedep_hashtbl[next++];
4857 if (next >= inodedep_hash)
4859 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
4862 if (inodedep == NULL) {
4867 * Ugly code to find mount point given pointer to superblock.
4869 fs = inodedep->id_fs;
4872 mountlist_scan(clear_inodedeps_mountlist_callback,
4873 &info, MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
4875 * Find the last inode in the block with dependencies.
4877 firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
4878 for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
4879 if (inodedep_lookup(fs, lastino, 0, &inodedep) != 0)
4882 * Asynchronously push all but the last inode with dependencies.
4883 * Synchronously push the last inode with dependencies to ensure
4884 * that the inode block gets written to free up the inodedeps.
4886 for (ino = firstino; ino <= lastino; ino++) {
4887 if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4890 if ((error = VFS_VGET(info.mp, NULL, ino, &vp)) != 0) {
4891 softdep_error("clear_inodedeps: vget", error);
4894 if (ino == lastino) {
4895 if ((error = VOP_FSYNC(vp, MNT_WAIT, 0)))
4896 softdep_error("clear_inodedeps: fsync1", error);
4898 if ((error = VOP_FSYNC(vp, MNT_NOWAIT, 0)))
4899 softdep_error("clear_inodedeps: fsync2", error);
4900 drain_output(vp, 0);
4909 * Function to determine if the buffer has outstanding dependencies
4910 * that will cause a roll-back if the buffer is written. If wantcount
4911 * is set, return number of dependencies, otherwise just yes or no.
4913 * bioops callback - hold io_token
4916 softdep_count_dependencies(struct buf *bp, int wantcount)
4918 struct worklist *wk;
4919 struct inodedep *inodedep;
4920 struct indirdep *indirdep;
4921 struct allocindir *aip;
4922 struct pagedep *pagedep;
4929 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4930 switch (wk->wk_type) {
4933 inodedep = WK_INODEDEP(wk);
4934 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4935 /* bitmap allocation dependency */
4940 if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
4941 /* direct block pointer dependency */
4949 indirdep = WK_INDIRDEP(wk);
4951 LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
4952 /* indirect block pointer dependency */
4960 pagedep = WK_PAGEDEP(wk);
4961 for (i = 0; i < DAHASHSZ; i++) {
4963 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
4964 /* directory entry dependency */
4976 /* never a dependency on these blocks */
4981 panic("softdep_check_for_rollback: Unexpected type %s",
4982 TYPENAME(wk->wk_type));
4995 * Acquire exclusive access to a buffer. Requires softdep lock
4996 * to be held on entry. If waitfor is MNT_WAIT, may release/reacquire
4999 * Returns 1 if the buffer was locked, 0 otherwise.
5002 getdirtybuf(struct buf **bpp, int waitfor)
5012 /* Must acquire buffer lock with ffs_softdep lock held */
5013 KKASSERT(lock_held(&lk) > 0);
5014 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT);
5018 if (waitfor != MNT_WAIT)
5022 * Release ffs_softdep lock around sleep/wait for buffer lock.
5024 * We must acquire buffer lock with softdep lock held, so
5025 * we must retry locking the buffer after we wake.
5028 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL);
5032 else if (error == ENOLCK)
5035 panic("getdirtybuf: Inconsistent lock");
5038 /* Buffer wasn't dirty */
5039 if ((bp->b_flags & B_DELWRI) == 0) {
5048 * Wait for pending output on a vnode to complete.
5049 * Must be called with vnode locked.
5052 drain_output(struct vnode *vp, int islocked)
5057 while (bio_track_active(&vp->v_track_write)) {
5059 bio_track_wait(&vp->v_track_write, 0, 0);
5067 * Called whenever a buffer that is being invalidated or reallocated
5068 * contains dependencies. This should only happen if an I/O error has
5069 * occurred. The routine is called with the buffer locked.
5071 * bioops callback - hold io_token
5074 softdep_deallocate_dependencies(struct buf *bp)
5076 /* nothing to do, mp lock not needed */
5077 if ((bp->b_flags & B_ERROR) == 0)
5078 panic("softdep_deallocate_dependencies: dangling deps");
5079 softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntfromname, bp->b_error);
5080 panic("softdep_deallocate_dependencies: unrecovered I/O error");
5084 * Function to handle asynchronous write errors in the filesystem.
5087 softdep_error(char *func, int error)
5090 /* XXX should do something better! */
5091 kprintf("%s: got error %d while accessing filesystem\n", func, error);