kernel - Rename desiredvnodes to maxvnodes, fix deadlock
[dragonfly.git] / sys / vfs / ufs / ffs_softdep.c
blobe459c8a69a9fc3e64c42685dc987affd49533f73
1 /*
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
14 * USA
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
18 * are met:
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
36 * SUCH DAMAGE.
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.
45 #ifndef DIAGNOSTIC
46 #define DIAGNOSTIC
47 #endif
48 #ifndef DEBUG
49 #define DEBUG
50 #endif
52 #include <sys/param.h>
53 #include <sys/kernel.h>
54 #include <sys/systm.h>
55 #include <sys/buf.h>
56 #include <sys/malloc.h>
57 #include <sys/mount.h>
58 #include <sys/proc.h>
59 #include <sys/syslog.h>
60 #include <sys/vnode.h>
61 #include <sys/conf.h>
62 #include <machine/inttypes.h>
63 #include "dir.h"
64 #include "quota.h"
65 #include "inode.h"
66 #include "ufsmount.h"
67 #include "fs.h"
68 #include "softdep.h"
69 #include "ffs_extern.h"
70 #include "ufs_extern.h"
72 #include <sys/buf2.h>
73 #include <sys/thread2.h>
74 #include <sys/lock.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)
99 #define D_PAGEDEP 0
100 #define D_INODEDEP 1
101 #define D_NEWBLK 2
102 #define D_BMSAFEMAP 3
103 #define D_ALLOCDIRECT 4
104 #define D_INDIRDEP 5
105 #define D_ALLOCINDIR 6
106 #define D_FREEFRAG 7
107 #define D_FREEBLKS 8
108 #define D_FREEFILE 9
109 #define D_DIRADD 10
110 #define D_MKDIR 11
111 #define D_DIRREM 12
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[] = {
119 M_PAGEDEP,
120 M_INODEDEP,
121 M_NEWBLK,
122 M_BMSAFEMAP,
123 M_ALLOCDIRECT,
124 M_INDIRDEP,
125 M_ALLOCINDIR,
126 M_FREEFRAG,
127 M_FREEBLKS,
128 M_FREEFILE,
129 M_DIRADD,
130 M_MKDIR,
131 M_DIRREM
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 *,
154 struct diraddhd *);
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,
181 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,
188 struct newblk **);
189 static int inodedep_lookup(struct fs *, ino_t, int, struct inodedep **);
190 static int pagedep_lookup(struct inode *, ufs_lbn_t, int,
191 struct pagedep **);
192 static int request_cleanup(int);
193 static int process_worklist_item(struct mount *, int);
194 static void add_to_worklist(struct worklist *);
197 * Exported softdep operations.
199 static void softdep_disk_io_initiation(struct buf *);
200 static void softdep_disk_write_complete(struct buf *);
201 static void softdep_deallocate_dependencies(struct buf *);
202 static int softdep_fsync(struct vnode *);
203 static int softdep_process_worklist(struct mount *);
204 static void softdep_move_dependencies(struct buf *, struct buf *);
205 static int softdep_count_dependencies(struct buf *bp, int);
206 static int softdep_checkread(struct buf *bp);
207 static int softdep_checkwrite(struct buf *bp);
209 static struct bio_ops softdep_bioops = {
210 .io_start = softdep_disk_io_initiation,
211 .io_complete = softdep_disk_write_complete,
212 .io_deallocate = softdep_deallocate_dependencies,
213 .io_fsync = softdep_fsync,
214 .io_sync = softdep_process_worklist,
215 .io_movedeps = softdep_move_dependencies,
216 .io_countdeps = softdep_count_dependencies,
217 .io_checkread = softdep_checkread,
218 .io_checkwrite = softdep_checkwrite
222 * Locking primitives.
224 static void acquire_lock(struct lock *);
225 static void free_lock(struct lock *);
226 #ifdef INVARIANTS
227 static int lock_held(struct lock *);
228 #endif
230 static struct lock lk;
232 #define ACQUIRE_LOCK(lkp) acquire_lock(lkp)
233 #define FREE_LOCK(lkp) free_lock(lkp)
235 static void
236 acquire_lock(struct lock *lkp)
238 lockmgr(lkp, LK_EXCLUSIVE);
241 static void
242 free_lock(struct lock *lkp)
244 lockmgr(lkp, LK_RELEASE);
247 #ifdef INVARIANTS
248 static int
249 lock_held(struct lock *lkp)
251 return lockcountnb(lkp);
253 #endif
256 * Place holder for real semaphores.
258 struct sema {
259 int value;
260 thread_t holder;
261 char *name;
262 int timo;
263 struct spinlock spin;
265 static void sema_init(struct sema *, char *, int);
266 static int sema_get(struct sema *, struct lock *);
267 static void sema_release(struct sema *, struct lock *);
269 #define NOHOLDER ((struct thread *) -1)
271 static void
272 sema_init(struct sema *semap, char *name, int timo)
274 semap->holder = NOHOLDER;
275 semap->value = 0;
276 semap->name = name;
277 semap->timo = timo;
278 spin_init(&semap->spin, "ufssema");
282 * Obtain exclusive access, semaphore is protected by the interlock.
283 * If interlock is NULL we must protect the semaphore ourselves.
285 static int
286 sema_get(struct sema *semap, struct lock *interlock)
288 int rv;
290 if (interlock) {
291 if (semap->value > 0) {
292 ++semap->value; /* serves as wakeup flag */
293 lksleep(semap, interlock, 0,
294 semap->name, semap->timo);
295 rv = 0;
296 } else {
297 semap->value = 1; /* serves as owned flag */
298 semap->holder = curthread;
299 rv = 1;
301 } else {
302 spin_lock(&semap->spin);
303 if (semap->value > 0) {
304 ++semap->value; /* serves as wakeup flag */
305 ssleep(semap, &semap->spin, 0,
306 semap->name, semap->timo);
307 spin_unlock(&semap->spin);
308 rv = 0;
309 } else {
310 semap->value = 1; /* serves as owned flag */
311 semap->holder = curthread;
312 spin_unlock(&semap->spin);
313 rv = 1;
316 return (rv);
319 static void
320 sema_release(struct sema *semap, struct lock *lk)
322 if (semap->value <= 0 || semap->holder != curthread)
323 panic("sema_release: not held");
324 if (lk) {
325 semap->holder = NOHOLDER;
326 if (--semap->value > 0) {
327 semap->value = 0;
328 wakeup(semap);
330 } else {
331 spin_lock(&semap->spin);
332 semap->holder = NOHOLDER;
333 if (--semap->value > 0) {
334 semap->value = 0;
335 spin_unlock(&semap->spin);
336 wakeup(semap);
337 } else {
338 spin_unlock(&semap->spin);
344 * Worklist queue management.
345 * These routines require that the lock be held.
347 static void worklist_insert(struct workhead *, struct worklist *);
348 static void worklist_remove(struct worklist *);
349 static void workitem_free(struct worklist *, int);
351 #define WORKLIST_INSERT_BP(bp, item) do { \
352 (bp)->b_ops = &softdep_bioops; \
353 worklist_insert(&(bp)->b_dep, item); \
354 } while (0)
356 #define WORKLIST_INSERT(head, item) worklist_insert(head, item)
357 #define WORKLIST_REMOVE(item) worklist_remove(item)
358 #define WORKITEM_FREE(item, type) workitem_free((struct worklist *)item, type)
360 static void
361 worklist_insert(struct workhead *head, struct worklist *item)
363 KKASSERT(lock_held(&lk) > 0);
365 if (item->wk_state & ONWORKLIST) {
366 panic("worklist_insert: already on list");
368 item->wk_state |= ONWORKLIST;
369 LIST_INSERT_HEAD(head, item, wk_list);
372 static void
373 worklist_remove(struct worklist *item)
376 KKASSERT(lock_held(&lk));
377 if ((item->wk_state & ONWORKLIST) == 0)
378 panic("worklist_remove: not on list");
380 item->wk_state &= ~ONWORKLIST;
381 LIST_REMOVE(item, wk_list);
384 static void
385 workitem_free(struct worklist *item, int type)
388 if (item->wk_state & ONWORKLIST)
389 panic("workitem_free: still on list");
390 if (item->wk_type != type)
391 panic("workitem_free: type mismatch");
393 kfree(item, DtoM(type));
397 * Workitem queue management
399 static struct workhead softdep_workitem_pending;
400 static int num_on_worklist; /* number of worklist items to be processed */
401 static int softdep_worklist_busy; /* 1 => trying to do unmount */
402 static int softdep_worklist_req; /* serialized waiters */
403 static int max_softdeps; /* maximum number of structs before slowdown */
404 static int tickdelay = 2; /* number of ticks to pause during slowdown */
405 static int *stat_countp; /* statistic to count in proc_waiting timeout */
406 static int proc_waiting; /* tracks whether we have a timeout posted */
407 static struct thread *filesys_syncer; /* proc of filesystem syncer process */
408 static int req_clear_inodedeps; /* syncer process flush some inodedeps */
409 #define FLUSH_INODES 1
410 static int req_clear_remove; /* syncer process flush some freeblks */
411 #define FLUSH_REMOVE 2
413 * runtime statistics
415 static int stat_worklist_push; /* number of worklist cleanups */
416 static int stat_blk_limit_push; /* number of times block limit neared */
417 static int stat_ino_limit_push; /* number of times inode limit neared */
418 static int stat_blk_limit_hit; /* number of times block slowdown imposed */
419 static int stat_ino_limit_hit; /* number of times inode slowdown imposed */
420 static int stat_sync_limit_hit; /* number of synchronous slowdowns imposed */
421 static int stat_indir_blk_ptrs; /* bufs redirtied as indir ptrs not written */
422 static int stat_inode_bitmap; /* bufs redirtied as inode bitmap not written */
423 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
424 static int stat_dir_entry; /* bufs redirtied as dir entry cannot write */
425 #ifdef DEBUG
426 #include <vm/vm.h>
427 #include <sys/sysctl.h>
428 SYSCTL_INT(_debug, OID_AUTO, max_softdeps, CTLFLAG_RW, &max_softdeps, 0,
429 "Maximum soft dependencies before slowdown occurs");
430 SYSCTL_INT(_debug, OID_AUTO, tickdelay, CTLFLAG_RW, &tickdelay, 0,
431 "Ticks to delay before allocating during slowdown");
432 SYSCTL_INT(_debug, OID_AUTO, worklist_push, CTLFLAG_RW, &stat_worklist_push, 0,
433 "Number of worklist cleanups");
434 SYSCTL_INT(_debug, OID_AUTO, blk_limit_push, CTLFLAG_RW, &stat_blk_limit_push, 0,
435 "Number of times block limit neared");
436 SYSCTL_INT(_debug, OID_AUTO, ino_limit_push, CTLFLAG_RW, &stat_ino_limit_push, 0,
437 "Number of times inode limit neared");
438 SYSCTL_INT(_debug, OID_AUTO, blk_limit_hit, CTLFLAG_RW, &stat_blk_limit_hit, 0,
439 "Number of times block slowdown imposed");
440 SYSCTL_INT(_debug, OID_AUTO, ino_limit_hit, CTLFLAG_RW, &stat_ino_limit_hit, 0,
441 "Number of times inode slowdown imposed ");
442 SYSCTL_INT(_debug, OID_AUTO, sync_limit_hit, CTLFLAG_RW, &stat_sync_limit_hit, 0,
443 "Number of synchronous slowdowns imposed");
444 SYSCTL_INT(_debug, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW, &stat_indir_blk_ptrs, 0,
445 "Bufs redirtied as indir ptrs not written");
446 SYSCTL_INT(_debug, OID_AUTO, inode_bitmap, CTLFLAG_RW, &stat_inode_bitmap, 0,
447 "Bufs redirtied as inode bitmap not written");
448 SYSCTL_INT(_debug, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW, &stat_direct_blk_ptrs, 0,
449 "Bufs redirtied as direct ptrs not written");
450 SYSCTL_INT(_debug, OID_AUTO, dir_entry, CTLFLAG_RW, &stat_dir_entry, 0,
451 "Bufs redirtied as dir entry cannot write");
452 #endif /* DEBUG */
455 * Add an item to the end of the work queue.
456 * This routine requires that the lock be held.
457 * This is the only routine that adds items to the list.
458 * The following routine is the only one that removes items
459 * and does so in order from first to last.
461 static void
462 add_to_worklist(struct worklist *wk)
464 static struct worklist *worklist_tail;
466 if (wk->wk_state & ONWORKLIST) {
467 panic("add_to_worklist: already on list");
469 wk->wk_state |= ONWORKLIST;
470 if (LIST_FIRST(&softdep_workitem_pending) == NULL)
471 LIST_INSERT_HEAD(&softdep_workitem_pending, wk, wk_list);
472 else
473 LIST_INSERT_AFTER(worklist_tail, wk, wk_list);
474 worklist_tail = wk;
475 num_on_worklist += 1;
479 * Process that runs once per second to handle items in the background queue.
481 * Note that we ensure that everything is done in the order in which they
482 * appear in the queue. The code below depends on this property to ensure
483 * that blocks of a file are freed before the inode itself is freed. This
484 * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
485 * until all the old ones have been purged from the dependency lists.
487 * bioops callback - hold io_token
489 static int
490 softdep_process_worklist(struct mount *matchmnt)
492 thread_t td = curthread;
493 int matchcnt, loopcount;
494 int starttime;
496 ACQUIRE_LOCK(&lk);
499 * Record the process identifier of our caller so that we can give
500 * this process preferential treatment in request_cleanup below.
502 filesys_syncer = td;
503 matchcnt = 0;
506 * There is no danger of having multiple processes run this
507 * code, but we have to single-thread it when softdep_flushfiles()
508 * is in operation to get an accurate count of the number of items
509 * related to its mount point that are in the list.
511 if (matchmnt == NULL) {
512 if (softdep_worklist_busy < 0) {
513 matchcnt = -1;
514 goto done;
516 softdep_worklist_busy += 1;
520 * If requested, try removing inode or removal dependencies.
522 if (req_clear_inodedeps) {
523 clear_inodedeps(td);
524 req_clear_inodedeps -= 1;
525 wakeup_one(&proc_waiting);
527 if (req_clear_remove) {
528 clear_remove(td);
529 req_clear_remove -= 1;
530 wakeup_one(&proc_waiting);
532 loopcount = 1;
533 starttime = ticks;
534 while (num_on_worklist > 0) {
535 matchcnt += process_worklist_item(matchmnt, 0);
538 * If a umount operation wants to run the worklist
539 * accurately, abort.
541 if (softdep_worklist_req && matchmnt == NULL) {
542 matchcnt = -1;
543 break;
547 * If requested, try removing inode or removal dependencies.
549 if (req_clear_inodedeps) {
550 clear_inodedeps(td);
551 req_clear_inodedeps -= 1;
552 wakeup_one(&proc_waiting);
554 if (req_clear_remove) {
555 clear_remove(td);
556 req_clear_remove -= 1;
557 wakeup_one(&proc_waiting);
560 * We do not generally want to stop for buffer space, but if
561 * we are really being a buffer hog, we will stop and wait.
563 if (loopcount++ % 128 == 0) {
564 FREE_LOCK(&lk);
565 bwillinode(1);
566 ACQUIRE_LOCK(&lk);
570 * Never allow processing to run for more than one
571 * second. Otherwise the other syncer tasks may get
572 * excessively backlogged.
574 * Use ticks to avoid boundary condition w/time_second or
575 * time_uptime.
577 if ((ticks - starttime) > hz && matchmnt == NULL) {
578 matchcnt = -1;
579 break;
582 if (matchmnt == NULL) {
583 --softdep_worklist_busy;
584 if (softdep_worklist_req && softdep_worklist_busy == 0)
585 wakeup(&softdep_worklist_req);
587 done:
588 FREE_LOCK(&lk);
589 return (matchcnt);
593 * Process one item on the worklist.
595 static int
596 process_worklist_item(struct mount *matchmnt, int flags)
598 struct ufsmount *ump;
599 struct worklist *wk;
600 struct dirrem *dirrem;
601 struct fs *matchfs;
602 struct vnode *vp;
603 int matchcnt = 0;
605 KKASSERT(lock_held(&lk) > 0);
607 matchfs = NULL;
608 if (matchmnt != NULL)
609 matchfs = VFSTOUFS(matchmnt)->um_fs;
612 * Normally we just process each item on the worklist in order.
613 * However, if we are in a situation where we cannot lock any
614 * inodes, we have to skip over any dirrem requests whose
615 * vnodes are resident and locked.
617 LIST_FOREACH(wk, &softdep_workitem_pending, wk_list) {
618 if ((flags & LK_NOWAIT) == 0 || wk->wk_type != D_DIRREM)
619 break;
620 dirrem = WK_DIRREM(wk);
621 ump = VFSTOUFS(dirrem->dm_mnt);
622 lwkt_gettoken(&ump->um_mountp->mnt_token);
623 vp = ufs_ihashlookup(ump, ump->um_dev, dirrem->dm_oldinum);
624 lwkt_reltoken(&ump->um_mountp->mnt_token);
625 if (vp == NULL || !vn_islocked(vp))
626 break;
628 if (wk == NULL) {
629 return (0);
631 WORKLIST_REMOVE(wk);
632 num_on_worklist -= 1;
633 FREE_LOCK(&lk);
634 switch (wk->wk_type) {
635 case D_DIRREM:
636 /* removal of a directory entry */
637 if (WK_DIRREM(wk)->dm_mnt == matchmnt)
638 matchcnt += 1;
639 handle_workitem_remove(WK_DIRREM(wk));
640 break;
642 case D_FREEBLKS:
643 /* releasing blocks and/or fragments from a file */
644 if (WK_FREEBLKS(wk)->fb_fs == matchfs)
645 matchcnt += 1;
646 handle_workitem_freeblocks(WK_FREEBLKS(wk));
647 break;
649 case D_FREEFRAG:
650 /* releasing a fragment when replaced as a file grows */
651 if (WK_FREEFRAG(wk)->ff_fs == matchfs)
652 matchcnt += 1;
653 handle_workitem_freefrag(WK_FREEFRAG(wk));
654 break;
656 case D_FREEFILE:
657 /* releasing an inode when its link count drops to 0 */
658 if (WK_FREEFILE(wk)->fx_fs == matchfs)
659 matchcnt += 1;
660 handle_workitem_freefile(WK_FREEFILE(wk));
661 break;
663 default:
664 panic("%s_process_worklist: Unknown type %s",
665 "softdep", TYPENAME(wk->wk_type));
666 /* NOTREACHED */
668 ACQUIRE_LOCK(&lk);
669 return (matchcnt);
673 * Move dependencies from one buffer to another.
675 * bioops callback - hold io_token
677 static void
678 softdep_move_dependencies(struct buf *oldbp, struct buf *newbp)
680 struct worklist *wk, *wktail;
682 if (LIST_FIRST(&newbp->b_dep) != NULL)
683 panic("softdep_move_dependencies: need merge code");
684 wktail = NULL;
685 ACQUIRE_LOCK(&lk);
686 while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
687 LIST_REMOVE(wk, wk_list);
688 if (wktail == NULL)
689 LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
690 else
691 LIST_INSERT_AFTER(wktail, wk, wk_list);
692 wktail = wk;
693 newbp->b_ops = &softdep_bioops;
695 FREE_LOCK(&lk);
699 * Purge the work list of all items associated with a particular mount point.
702 softdep_flushfiles(struct mount *oldmnt, int flags)
704 struct vnode *devvp;
705 int error, loopcnt;
708 * Await our turn to clear out the queue, then serialize access.
710 ACQUIRE_LOCK(&lk);
711 while (softdep_worklist_busy != 0) {
712 softdep_worklist_req += 1;
713 lksleep(&softdep_worklist_req, &lk, 0, "softflush", 0);
714 softdep_worklist_req -= 1;
716 softdep_worklist_busy = -1;
717 FREE_LOCK(&lk);
719 if ((error = ffs_flushfiles(oldmnt, flags)) != 0) {
720 softdep_worklist_busy = 0;
721 if (softdep_worklist_req)
722 wakeup(&softdep_worklist_req);
723 return (error);
726 * Alternately flush the block device associated with the mount
727 * point and process any dependencies that the flushing
728 * creates. In theory, this loop can happen at most twice,
729 * but we give it a few extra just to be sure.
731 devvp = VFSTOUFS(oldmnt)->um_devvp;
732 for (loopcnt = 10; loopcnt > 0; ) {
733 if (softdep_process_worklist(oldmnt) == 0) {
734 loopcnt--;
736 * Do another flush in case any vnodes were brought in
737 * as part of the cleanup operations.
739 if ((error = ffs_flushfiles(oldmnt, flags)) != 0)
740 break;
742 * If we still found nothing to do, we are really done.
744 if (softdep_process_worklist(oldmnt) == 0)
745 break;
747 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
748 error = VOP_FSYNC(devvp, MNT_WAIT, 0);
749 vn_unlock(devvp);
750 if (error)
751 break;
753 ACQUIRE_LOCK(&lk);
754 softdep_worklist_busy = 0;
755 if (softdep_worklist_req)
756 wakeup(&softdep_worklist_req);
757 FREE_LOCK(&lk);
760 * If we are unmounting then it is an error to fail. If we
761 * are simply trying to downgrade to read-only, then filesystem
762 * activity can keep us busy forever, so we just fail with EBUSY.
764 if (loopcnt == 0) {
765 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
766 panic("softdep_flushfiles: looping");
767 error = EBUSY;
769 return (error);
773 * Structure hashing.
775 * There are three types of structures that can be looked up:
776 * 1) pagedep structures identified by mount point, inode number,
777 * and logical block.
778 * 2) inodedep structures identified by mount point and inode number.
779 * 3) newblk structures identified by mount point and
780 * physical block number.
782 * The "pagedep" and "inodedep" dependency structures are hashed
783 * separately from the file blocks and inodes to which they correspond.
784 * This separation helps when the in-memory copy of an inode or
785 * file block must be replaced. It also obviates the need to access
786 * an inode or file page when simply updating (or de-allocating)
787 * dependency structures. Lookup of newblk structures is needed to
788 * find newly allocated blocks when trying to associate them with
789 * their allocdirect or allocindir structure.
791 * The lookup routines optionally create and hash a new instance when
792 * an existing entry is not found.
794 #define DEPALLOC 0x0001 /* allocate structure if lookup fails */
795 #define NODELAY 0x0002 /* cannot do background work */
798 * Structures and routines associated with pagedep caching.
800 LIST_HEAD(pagedep_hashhead, pagedep) *pagedep_hashtbl;
801 u_long pagedep_hash; /* size of hash table - 1 */
802 #define PAGEDEP_HASH(mp, inum, lbn) \
803 (&pagedep_hashtbl[((((register_t)(mp)) >> 13) + (inum) + (lbn)) & \
804 pagedep_hash])
805 static struct sema pagedep_in_progress;
808 * Helper routine for pagedep_lookup()
810 static __inline
811 struct pagedep *
812 pagedep_find(struct pagedep_hashhead *pagedephd, ino_t ino, ufs_lbn_t lbn,
813 struct mount *mp)
815 struct pagedep *pagedep;
817 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
818 if (ino == pagedep->pd_ino &&
819 lbn == pagedep->pd_lbn &&
820 mp == pagedep->pd_mnt) {
821 return (pagedep);
824 return(NULL);
828 * Look up a pagedep. Return 1 if found, 0 if not found.
829 * If not found, allocate if DEPALLOC flag is passed.
830 * Found or allocated entry is returned in pagedeppp.
831 * This routine must be called with splbio interrupts blocked.
833 static int
834 pagedep_lookup(struct inode *ip, ufs_lbn_t lbn, int flags,
835 struct pagedep **pagedeppp)
837 struct pagedep *pagedep;
838 struct pagedep_hashhead *pagedephd;
839 struct mount *mp;
840 int i;
842 KKASSERT(lock_held(&lk) > 0);
844 mp = ITOV(ip)->v_mount;
845 pagedephd = PAGEDEP_HASH(mp, ip->i_number, lbn);
846 top:
847 *pagedeppp = pagedep_find(pagedephd, ip->i_number, lbn, mp);
848 if (*pagedeppp)
849 return(1);
850 if ((flags & DEPALLOC) == 0)
851 return (0);
852 if (sema_get(&pagedep_in_progress, &lk) == 0)
853 goto top;
855 FREE_LOCK(&lk);
856 pagedep = kmalloc(sizeof(struct pagedep), M_PAGEDEP,
857 M_SOFTDEP_FLAGS | M_ZERO);
858 ACQUIRE_LOCK(&lk);
859 if (pagedep_find(pagedephd, ip->i_number, lbn, mp)) {
860 kprintf("pagedep_lookup: blocking race avoided\n");
861 sema_release(&pagedep_in_progress, &lk);
862 kfree(pagedep, M_PAGEDEP);
863 goto top;
866 pagedep->pd_list.wk_type = D_PAGEDEP;
867 pagedep->pd_mnt = mp;
868 pagedep->pd_ino = ip->i_number;
869 pagedep->pd_lbn = lbn;
870 LIST_INIT(&pagedep->pd_dirremhd);
871 LIST_INIT(&pagedep->pd_pendinghd);
872 for (i = 0; i < DAHASHSZ; i++)
873 LIST_INIT(&pagedep->pd_diraddhd[i]);
874 LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
875 sema_release(&pagedep_in_progress, &lk);
876 *pagedeppp = pagedep;
877 return (0);
881 * Structures and routines associated with inodedep caching.
883 LIST_HEAD(inodedep_hashhead, inodedep) *inodedep_hashtbl;
884 static u_long inodedep_hash; /* size of hash table - 1 */
885 static long num_inodedep; /* number of inodedep allocated */
886 #define INODEDEP_HASH(fs, inum) \
887 (&inodedep_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & inodedep_hash])
888 static struct sema inodedep_in_progress;
891 * Helper routine for inodedep_lookup()
893 static __inline
894 struct inodedep *
895 inodedep_find(struct inodedep_hashhead *inodedephd, struct fs *fs, ino_t inum)
897 struct inodedep *inodedep;
899 LIST_FOREACH(inodedep, inodedephd, id_hash) {
900 if (inum == inodedep->id_ino && fs == inodedep->id_fs)
901 return(inodedep);
903 return (NULL);
907 * Look up a inodedep. Return 1 if found, 0 if not found.
908 * If not found, allocate if DEPALLOC flag is passed.
909 * Found or allocated entry is returned in inodedeppp.
910 * This routine must be called with splbio interrupts blocked.
912 static int
913 inodedep_lookup(struct fs *fs, ino_t inum, int flags,
914 struct inodedep **inodedeppp)
916 struct inodedep *inodedep;
917 struct inodedep_hashhead *inodedephd;
919 KKASSERT(lock_held(&lk) > 0);
921 inodedephd = INODEDEP_HASH(fs, inum);
922 top:
923 *inodedeppp = inodedep_find(inodedephd, fs, inum);
924 if (*inodedeppp)
925 return (1);
926 if ((flags & DEPALLOC) == 0)
927 return (0);
930 * If we are over our limit, try to improve the situation.
932 if (num_inodedep > max_softdeps / 2)
933 speedup_syncer(NULL);
934 if (num_inodedep > max_softdeps &&
935 (flags & NODELAY) == 0 &&
936 request_cleanup(FLUSH_INODES)) {
937 goto top;
939 if (sema_get(&inodedep_in_progress, &lk) == 0)
940 goto top;
942 FREE_LOCK(&lk);
943 inodedep = kmalloc(sizeof(struct inodedep), M_INODEDEP,
944 M_SOFTDEP_FLAGS | M_ZERO);
945 ACQUIRE_LOCK(&lk);
946 if (inodedep_find(inodedephd, fs, inum)) {
947 kprintf("inodedep_lookup: blocking race avoided\n");
948 sema_release(&inodedep_in_progress, &lk);
949 kfree(inodedep, M_INODEDEP);
950 goto top;
952 inodedep->id_list.wk_type = D_INODEDEP;
953 inodedep->id_fs = fs;
954 inodedep->id_ino = inum;
955 inodedep->id_state = ALLCOMPLETE;
956 inodedep->id_nlinkdelta = 0;
957 inodedep->id_savedino = NULL;
958 inodedep->id_savedsize = -1;
959 inodedep->id_buf = NULL;
960 LIST_INIT(&inodedep->id_pendinghd);
961 LIST_INIT(&inodedep->id_inowait);
962 LIST_INIT(&inodedep->id_bufwait);
963 TAILQ_INIT(&inodedep->id_inoupdt);
964 TAILQ_INIT(&inodedep->id_newinoupdt);
965 num_inodedep += 1;
966 LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
967 sema_release(&inodedep_in_progress, &lk);
968 *inodedeppp = inodedep;
969 return (0);
973 * Structures and routines associated with newblk caching.
975 LIST_HEAD(newblk_hashhead, newblk) *newblk_hashtbl;
976 u_long newblk_hash; /* size of hash table - 1 */
977 #define NEWBLK_HASH(fs, inum) \
978 (&newblk_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & newblk_hash])
979 static struct sema newblk_in_progress;
982 * Helper routine for newblk_lookup()
984 static __inline
985 struct newblk *
986 newblk_find(struct newblk_hashhead *newblkhd, struct fs *fs,
987 ufs_daddr_t newblkno)
989 struct newblk *newblk;
991 LIST_FOREACH(newblk, newblkhd, nb_hash) {
992 if (newblkno == newblk->nb_newblkno && fs == newblk->nb_fs)
993 return (newblk);
995 return(NULL);
999 * Look up a newblk. Return 1 if found, 0 if not found.
1000 * If not found, allocate if DEPALLOC flag is passed.
1001 * Found or allocated entry is returned in newblkpp.
1003 static int
1004 newblk_lookup(struct fs *fs, ufs_daddr_t newblkno, int flags,
1005 struct newblk **newblkpp)
1007 struct newblk *newblk;
1008 struct newblk_hashhead *newblkhd;
1010 newblkhd = NEWBLK_HASH(fs, newblkno);
1011 top:
1012 *newblkpp = newblk_find(newblkhd, fs, newblkno);
1013 if (*newblkpp)
1014 return(1);
1015 if ((flags & DEPALLOC) == 0)
1016 return (0);
1017 if (sema_get(&newblk_in_progress, NULL) == 0)
1018 goto top;
1020 newblk = kmalloc(sizeof(struct newblk), M_NEWBLK,
1021 M_SOFTDEP_FLAGS | M_ZERO);
1023 if (newblk_find(newblkhd, fs, newblkno)) {
1024 kprintf("newblk_lookup: blocking race avoided\n");
1025 sema_release(&pagedep_in_progress, NULL);
1026 kfree(newblk, M_NEWBLK);
1027 goto top;
1029 newblk->nb_state = 0;
1030 newblk->nb_fs = fs;
1031 newblk->nb_newblkno = newblkno;
1032 LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
1033 sema_release(&newblk_in_progress, NULL);
1034 *newblkpp = newblk;
1035 return (0);
1039 * Executed during filesystem system initialization before
1040 * mounting any filesystems.
1042 void
1043 softdep_initialize(void)
1045 LIST_INIT(&mkdirlisthd);
1046 LIST_INIT(&softdep_workitem_pending);
1047 max_softdeps = min(maxvnodes * 8,
1048 M_INODEDEP->ks_limit / (2 * sizeof(struct inodedep)));
1049 pagedep_hashtbl = hashinit(maxvnodes / 5, M_PAGEDEP, &pagedep_hash);
1050 lockinit(&lk, "ffs_softdep", 0, LK_CANRECURSE);
1051 sema_init(&pagedep_in_progress, "pagedep", 0);
1052 inodedep_hashtbl = hashinit(maxvnodes, M_INODEDEP, &inodedep_hash);
1053 sema_init(&inodedep_in_progress, "inodedep", 0);
1054 newblk_hashtbl = hashinit(64, M_NEWBLK, &newblk_hash);
1055 sema_init(&newblk_in_progress, "newblk", 0);
1056 add_bio_ops(&softdep_bioops);
1060 * Called at mount time to notify the dependency code that a
1061 * filesystem wishes to use it.
1064 softdep_mount(struct vnode *devvp, struct mount *mp, struct fs *fs)
1066 struct csum cstotal;
1067 struct cg *cgp;
1068 struct buf *bp;
1069 int error, cyl;
1071 mp->mnt_flag &= ~MNT_ASYNC;
1072 mp->mnt_flag |= MNT_SOFTDEP;
1073 mp->mnt_bioops = &softdep_bioops;
1075 * When doing soft updates, the counters in the
1076 * superblock may have gotten out of sync, so we have
1077 * to scan the cylinder groups and recalculate them.
1079 if (fs->fs_clean != 0)
1080 return (0);
1081 bzero(&cstotal, sizeof cstotal);
1082 for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
1083 if ((error = bread(devvp, fsbtodoff(fs, cgtod(fs, cyl)),
1084 fs->fs_cgsize, &bp)) != 0) {
1085 brelse(bp);
1086 return (error);
1088 cgp = (struct cg *)bp->b_data;
1089 cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
1090 cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
1091 cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
1092 cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
1093 fs->fs_cs(fs, cyl) = cgp->cg_cs;
1094 brelse(bp);
1096 #ifdef DEBUG
1097 if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
1098 kprintf("ffs_mountfs: superblock updated for soft updates\n");
1099 #endif
1100 bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
1101 return (0);
1105 * Protecting the freemaps (or bitmaps).
1107 * To eliminate the need to execute fsck before mounting a filesystem
1108 * after a power failure, one must (conservatively) guarantee that the
1109 * on-disk copy of the bitmaps never indicate that a live inode or block is
1110 * free. So, when a block or inode is allocated, the bitmap should be
1111 * updated (on disk) before any new pointers. When a block or inode is
1112 * freed, the bitmap should not be updated until all pointers have been
1113 * reset. The latter dependency is handled by the delayed de-allocation
1114 * approach described below for block and inode de-allocation. The former
1115 * dependency is handled by calling the following procedure when a block or
1116 * inode is allocated. When an inode is allocated an "inodedep" is created
1117 * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
1118 * Each "inodedep" is also inserted into the hash indexing structure so
1119 * that any additional link additions can be made dependent on the inode
1120 * allocation.
1122 * The ufs filesystem maintains a number of free block counts (e.g., per
1123 * cylinder group, per cylinder and per <cylinder, rotational position> pair)
1124 * in addition to the bitmaps. These counts are used to improve efficiency
1125 * during allocation and therefore must be consistent with the bitmaps.
1126 * There is no convenient way to guarantee post-crash consistency of these
1127 * counts with simple update ordering, for two main reasons: (1) The counts
1128 * and bitmaps for a single cylinder group block are not in the same disk
1129 * sector. If a disk write is interrupted (e.g., by power failure), one may
1130 * be written and the other not. (2) Some of the counts are located in the
1131 * superblock rather than the cylinder group block. So, we focus our soft
1132 * updates implementation on protecting the bitmaps. When mounting a
1133 * filesystem, we recompute the auxiliary counts from the bitmaps.
1137 * Called just after updating the cylinder group block to allocate an inode.
1139 * Parameters:
1140 * bp: buffer for cylgroup block with inode map
1141 * ip: inode related to allocation
1142 * newinum: new inode number being allocated
1144 void
1145 softdep_setup_inomapdep(struct buf *bp, struct inode *ip, ino_t newinum)
1147 struct inodedep *inodedep;
1148 struct bmsafemap *bmsafemap;
1151 * Create a dependency for the newly allocated inode.
1152 * Panic if it already exists as something is seriously wrong.
1153 * Otherwise add it to the dependency list for the buffer holding
1154 * the cylinder group map from which it was allocated.
1156 ACQUIRE_LOCK(&lk);
1157 if ((inodedep_lookup(ip->i_fs, newinum, DEPALLOC|NODELAY, &inodedep))) {
1158 panic("softdep_setup_inomapdep: found inode");
1160 inodedep->id_buf = bp;
1161 inodedep->id_state &= ~DEPCOMPLETE;
1162 bmsafemap = bmsafemap_lookup(bp);
1163 LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
1164 FREE_LOCK(&lk);
1168 * Called just after updating the cylinder group block to
1169 * allocate block or fragment.
1171 * Parameters:
1172 * bp: buffer for cylgroup block with block map
1173 * fs: filesystem doing allocation
1174 * newblkno: number of newly allocated block
1176 void
1177 softdep_setup_blkmapdep(struct buf *bp, struct fs *fs,
1178 ufs_daddr_t newblkno)
1180 struct newblk *newblk;
1181 struct bmsafemap *bmsafemap;
1184 * Create a dependency for the newly allocated block.
1185 * Add it to the dependency list for the buffer holding
1186 * the cylinder group map from which it was allocated.
1188 if (newblk_lookup(fs, newblkno, DEPALLOC, &newblk) != 0)
1189 panic("softdep_setup_blkmapdep: found block");
1190 ACQUIRE_LOCK(&lk);
1191 newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(bp);
1192 LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
1193 FREE_LOCK(&lk);
1197 * Find the bmsafemap associated with a cylinder group buffer.
1198 * If none exists, create one. The buffer must be locked when
1199 * this routine is called and this routine must be called with
1200 * splbio interrupts blocked.
1202 static struct bmsafemap *
1203 bmsafemap_lookup(struct buf *bp)
1205 struct bmsafemap *bmsafemap;
1206 struct worklist *wk;
1208 KKASSERT(lock_held(&lk) > 0);
1210 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
1211 if (wk->wk_type == D_BMSAFEMAP)
1212 return (WK_BMSAFEMAP(wk));
1214 FREE_LOCK(&lk);
1215 bmsafemap = kmalloc(sizeof(struct bmsafemap), M_BMSAFEMAP,
1216 M_SOFTDEP_FLAGS);
1217 bmsafemap->sm_list.wk_type = D_BMSAFEMAP;
1218 bmsafemap->sm_list.wk_state = 0;
1219 bmsafemap->sm_buf = bp;
1220 LIST_INIT(&bmsafemap->sm_allocdirecthd);
1221 LIST_INIT(&bmsafemap->sm_allocindirhd);
1222 LIST_INIT(&bmsafemap->sm_inodedephd);
1223 LIST_INIT(&bmsafemap->sm_newblkhd);
1224 ACQUIRE_LOCK(&lk);
1225 WORKLIST_INSERT_BP(bp, &bmsafemap->sm_list);
1226 return (bmsafemap);
1230 * Direct block allocation dependencies.
1232 * When a new block is allocated, the corresponding disk locations must be
1233 * initialized (with zeros or new data) before the on-disk inode points to
1234 * them. Also, the freemap from which the block was allocated must be
1235 * updated (on disk) before the inode's pointer. These two dependencies are
1236 * independent of each other and are needed for all file blocks and indirect
1237 * blocks that are pointed to directly by the inode. Just before the
1238 * "in-core" version of the inode is updated with a newly allocated block
1239 * number, a procedure (below) is called to setup allocation dependency
1240 * structures. These structures are removed when the corresponding
1241 * dependencies are satisfied or when the block allocation becomes obsolete
1242 * (i.e., the file is deleted, the block is de-allocated, or the block is a
1243 * fragment that gets upgraded). All of these cases are handled in
1244 * procedures described later.
1246 * When a file extension causes a fragment to be upgraded, either to a larger
1247 * fragment or to a full block, the on-disk location may change (if the
1248 * previous fragment could not simply be extended). In this case, the old
1249 * fragment must be de-allocated, but not until after the inode's pointer has
1250 * been updated. In most cases, this is handled by later procedures, which
1251 * will construct a "freefrag" structure to be added to the workitem queue
1252 * when the inode update is complete (or obsolete). The main exception to
1253 * this is when an allocation occurs while a pending allocation dependency
1254 * (for the same block pointer) remains. This case is handled in the main
1255 * allocation dependency setup procedure by immediately freeing the
1256 * unreferenced fragments.
1258 * Parameters:
1259 * ip: inode to which block is being added
1260 * lbn: block pointer within inode
1261 * newblkno: disk block number being added
1262 * oldblkno: previous block number, 0 unless frag
1263 * newsize: size of new block
1264 * oldsize: size of new block
1265 * bp: bp for allocated block
1267 void
1268 softdep_setup_allocdirect(struct inode *ip, ufs_lbn_t lbn, ufs_daddr_t newblkno,
1269 ufs_daddr_t oldblkno, long newsize, long oldsize,
1270 struct buf *bp)
1272 struct allocdirect *adp, *oldadp;
1273 struct allocdirectlst *adphead;
1274 struct bmsafemap *bmsafemap;
1275 struct inodedep *inodedep;
1276 struct pagedep *pagedep;
1277 struct newblk *newblk;
1279 adp = kmalloc(sizeof(struct allocdirect), M_ALLOCDIRECT,
1280 M_SOFTDEP_FLAGS | M_ZERO);
1281 adp->ad_list.wk_type = D_ALLOCDIRECT;
1282 adp->ad_lbn = lbn;
1283 adp->ad_newblkno = newblkno;
1284 adp->ad_oldblkno = oldblkno;
1285 adp->ad_newsize = newsize;
1286 adp->ad_oldsize = oldsize;
1287 adp->ad_state = ATTACHED;
1288 if (newblkno == oldblkno)
1289 adp->ad_freefrag = NULL;
1290 else
1291 adp->ad_freefrag = newfreefrag(ip, oldblkno, oldsize);
1293 if (newblk_lookup(ip->i_fs, newblkno, 0, &newblk) == 0)
1294 panic("softdep_setup_allocdirect: lost block");
1296 ACQUIRE_LOCK(&lk);
1297 inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC | NODELAY, &inodedep);
1298 adp->ad_inodedep = inodedep;
1300 if (newblk->nb_state == DEPCOMPLETE) {
1301 adp->ad_state |= DEPCOMPLETE;
1302 adp->ad_buf = NULL;
1303 } else {
1304 bmsafemap = newblk->nb_bmsafemap;
1305 adp->ad_buf = bmsafemap->sm_buf;
1306 LIST_REMOVE(newblk, nb_deps);
1307 LIST_INSERT_HEAD(&bmsafemap->sm_allocdirecthd, adp, ad_deps);
1309 LIST_REMOVE(newblk, nb_hash);
1310 kfree(newblk, M_NEWBLK);
1312 WORKLIST_INSERT_BP(bp, &adp->ad_list);
1313 if (lbn >= NDADDR) {
1314 /* allocating an indirect block */
1315 if (oldblkno != 0) {
1316 panic("softdep_setup_allocdirect: non-zero indir");
1318 } else {
1320 * Allocating a direct block.
1322 * If we are allocating a directory block, then we must
1323 * allocate an associated pagedep to track additions and
1324 * deletions.
1326 if ((ip->i_mode & IFMT) == IFDIR &&
1327 pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0) {
1328 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
1332 * The list of allocdirects must be kept in sorted and ascending
1333 * order so that the rollback routines can quickly determine the
1334 * first uncommitted block (the size of the file stored on disk
1335 * ends at the end of the lowest committed fragment, or if there
1336 * are no fragments, at the end of the highest committed block).
1337 * Since files generally grow, the typical case is that the new
1338 * block is to be added at the end of the list. We speed this
1339 * special case by checking against the last allocdirect in the
1340 * list before laboriously traversing the list looking for the
1341 * insertion point.
1343 adphead = &inodedep->id_newinoupdt;
1344 oldadp = TAILQ_LAST(adphead, allocdirectlst);
1345 if (oldadp == NULL || oldadp->ad_lbn <= lbn) {
1346 /* insert at end of list */
1347 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
1348 if (oldadp != NULL && oldadp->ad_lbn == lbn)
1349 allocdirect_merge(adphead, adp, oldadp);
1350 FREE_LOCK(&lk);
1351 return;
1353 TAILQ_FOREACH(oldadp, adphead, ad_next) {
1354 if (oldadp->ad_lbn >= lbn)
1355 break;
1357 if (oldadp == NULL) {
1358 panic("softdep_setup_allocdirect: lost entry");
1360 /* insert in middle of list */
1361 TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
1362 if (oldadp->ad_lbn == lbn)
1363 allocdirect_merge(adphead, adp, oldadp);
1364 FREE_LOCK(&lk);
1368 * Replace an old allocdirect dependency with a newer one.
1369 * This routine must be called with splbio interrupts blocked.
1371 * Parameters:
1372 * adphead: head of list holding allocdirects
1373 * newadp: allocdirect being added
1374 * oldadp: existing allocdirect being checked
1376 static void
1377 allocdirect_merge(struct allocdirectlst *adphead,
1378 struct allocdirect *newadp,
1379 struct allocdirect *oldadp)
1381 struct freefrag *freefrag;
1383 KKASSERT(lock_held(&lk) > 0);
1385 if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
1386 newadp->ad_oldsize != oldadp->ad_newsize ||
1387 newadp->ad_lbn >= NDADDR) {
1388 panic("allocdirect_check: old %d != new %d || lbn %ld >= %d",
1389 newadp->ad_oldblkno, oldadp->ad_newblkno, newadp->ad_lbn,
1390 NDADDR);
1392 newadp->ad_oldblkno = oldadp->ad_oldblkno;
1393 newadp->ad_oldsize = oldadp->ad_oldsize;
1395 * If the old dependency had a fragment to free or had never
1396 * previously had a block allocated, then the new dependency
1397 * can immediately post its freefrag and adopt the old freefrag.
1398 * This action is done by swapping the freefrag dependencies.
1399 * The new dependency gains the old one's freefrag, and the
1400 * old one gets the new one and then immediately puts it on
1401 * the worklist when it is freed by free_allocdirect. It is
1402 * not possible to do this swap when the old dependency had a
1403 * non-zero size but no previous fragment to free. This condition
1404 * arises when the new block is an extension of the old block.
1405 * Here, the first part of the fragment allocated to the new
1406 * dependency is part of the block currently claimed on disk by
1407 * the old dependency, so cannot legitimately be freed until the
1408 * conditions for the new dependency are fulfilled.
1410 if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
1411 freefrag = newadp->ad_freefrag;
1412 newadp->ad_freefrag = oldadp->ad_freefrag;
1413 oldadp->ad_freefrag = freefrag;
1415 free_allocdirect(adphead, oldadp, 0);
1419 * Allocate a new freefrag structure if needed.
1421 static struct freefrag *
1422 newfreefrag(struct inode *ip, ufs_daddr_t blkno, long size)
1424 struct freefrag *freefrag;
1425 struct fs *fs;
1427 if (blkno == 0)
1428 return (NULL);
1429 fs = ip->i_fs;
1430 if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
1431 panic("newfreefrag: frag size");
1432 freefrag = kmalloc(sizeof(struct freefrag), M_FREEFRAG,
1433 M_SOFTDEP_FLAGS);
1434 freefrag->ff_list.wk_type = D_FREEFRAG;
1435 freefrag->ff_state = ip->i_uid & ~ONWORKLIST; /* XXX - used below */
1436 freefrag->ff_inum = ip->i_number;
1437 freefrag->ff_fs = fs;
1438 freefrag->ff_devvp = ip->i_devvp;
1439 freefrag->ff_blkno = blkno;
1440 freefrag->ff_fragsize = size;
1441 return (freefrag);
1445 * This workitem de-allocates fragments that were replaced during
1446 * file block allocation.
1448 static void
1449 handle_workitem_freefrag(struct freefrag *freefrag)
1451 struct inode tip;
1453 tip.i_fs = freefrag->ff_fs;
1454 tip.i_devvp = freefrag->ff_devvp;
1455 tip.i_dev = freefrag->ff_devvp->v_rdev;
1456 tip.i_number = freefrag->ff_inum;
1457 tip.i_uid = freefrag->ff_state & ~ONWORKLIST; /* XXX - set above */
1458 ffs_blkfree(&tip, freefrag->ff_blkno, freefrag->ff_fragsize);
1459 kfree(freefrag, M_FREEFRAG);
1463 * Indirect block allocation dependencies.
1465 * The same dependencies that exist for a direct block also exist when
1466 * a new block is allocated and pointed to by an entry in a block of
1467 * indirect pointers. The undo/redo states described above are also
1468 * used here. Because an indirect block contains many pointers that
1469 * may have dependencies, a second copy of the entire in-memory indirect
1470 * block is kept. The buffer cache copy is always completely up-to-date.
1471 * The second copy, which is used only as a source for disk writes,
1472 * contains only the safe pointers (i.e., those that have no remaining
1473 * update dependencies). The second copy is freed when all pointers
1474 * are safe. The cache is not allowed to replace indirect blocks with
1475 * pending update dependencies. If a buffer containing an indirect
1476 * block with dependencies is written, these routines will mark it
1477 * dirty again. It can only be successfully written once all the
1478 * dependencies are removed. The ffs_fsync routine in conjunction with
1479 * softdep_sync_metadata work together to get all the dependencies
1480 * removed so that a file can be successfully written to disk. Three
1481 * procedures are used when setting up indirect block pointer
1482 * dependencies. The division is necessary because of the organization
1483 * of the "balloc" routine and because of the distinction between file
1484 * pages and file metadata blocks.
1488 * Allocate a new allocindir structure.
1490 * Parameters:
1491 * ip: inode for file being extended
1492 * ptrno: offset of pointer in indirect block
1493 * newblkno: disk block number being added
1494 * oldblkno: previous block number, 0 if none
1496 static struct allocindir *
1497 newallocindir(struct inode *ip, int ptrno, ufs_daddr_t newblkno,
1498 ufs_daddr_t oldblkno)
1500 struct allocindir *aip;
1502 aip = kmalloc(sizeof(struct allocindir), M_ALLOCINDIR,
1503 M_SOFTDEP_FLAGS | M_ZERO);
1504 aip->ai_list.wk_type = D_ALLOCINDIR;
1505 aip->ai_state = ATTACHED;
1506 aip->ai_offset = ptrno;
1507 aip->ai_newblkno = newblkno;
1508 aip->ai_oldblkno = oldblkno;
1509 aip->ai_freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize);
1510 return (aip);
1514 * Called just before setting an indirect block pointer
1515 * to a newly allocated file page.
1517 * Parameters:
1518 * ip: inode for file being extended
1519 * lbn: allocated block number within file
1520 * bp: buffer with indirect blk referencing page
1521 * ptrno: offset of pointer in indirect block
1522 * newblkno: disk block number being added
1523 * oldblkno: previous block number, 0 if none
1524 * nbp: buffer holding allocated page
1526 void
1527 softdep_setup_allocindir_page(struct inode *ip, ufs_lbn_t lbn,
1528 struct buf *bp, int ptrno,
1529 ufs_daddr_t newblkno, ufs_daddr_t oldblkno,
1530 struct buf *nbp)
1532 struct allocindir *aip;
1533 struct pagedep *pagedep;
1535 aip = newallocindir(ip, ptrno, newblkno, oldblkno);
1536 ACQUIRE_LOCK(&lk);
1538 * If we are allocating a directory page, then we must
1539 * allocate an associated pagedep to track additions and
1540 * deletions.
1542 if ((ip->i_mode & IFMT) == IFDIR &&
1543 pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0)
1544 WORKLIST_INSERT_BP(nbp, &pagedep->pd_list);
1545 WORKLIST_INSERT_BP(nbp, &aip->ai_list);
1546 FREE_LOCK(&lk);
1547 setup_allocindir_phase2(bp, ip, aip);
1551 * Called just before setting an indirect block pointer to a
1552 * newly allocated indirect block.
1553 * Parameters:
1554 * nbp: newly allocated indirect block
1555 * ip: inode for file being extended
1556 * bp: indirect block referencing allocated block
1557 * ptrno: offset of pointer in indirect block
1558 * newblkno: disk block number being added
1560 void
1561 softdep_setup_allocindir_meta(struct buf *nbp, struct inode *ip,
1562 struct buf *bp, int ptrno,
1563 ufs_daddr_t newblkno)
1565 struct allocindir *aip;
1567 aip = newallocindir(ip, ptrno, newblkno, 0);
1568 ACQUIRE_LOCK(&lk);
1569 WORKLIST_INSERT_BP(nbp, &aip->ai_list);
1570 FREE_LOCK(&lk);
1571 setup_allocindir_phase2(bp, ip, aip);
1575 * Called to finish the allocation of the "aip" allocated
1576 * by one of the two routines above.
1578 * Parameters:
1579 * bp: in-memory copy of the indirect block
1580 * ip: inode for file being extended
1581 * aip: allocindir allocated by the above routines
1583 static void
1584 setup_allocindir_phase2(struct buf *bp, struct inode *ip,
1585 struct allocindir *aip)
1587 struct worklist *wk;
1588 struct indirdep *indirdep, *newindirdep;
1589 struct bmsafemap *bmsafemap;
1590 struct allocindir *oldaip;
1591 struct freefrag *freefrag;
1592 struct newblk *newblk;
1594 if (bp->b_loffset >= 0)
1595 panic("setup_allocindir_phase2: not indir blk");
1596 for (indirdep = NULL, newindirdep = NULL; ; ) {
1597 ACQUIRE_LOCK(&lk);
1598 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
1599 if (wk->wk_type != D_INDIRDEP)
1600 continue;
1601 indirdep = WK_INDIRDEP(wk);
1602 break;
1604 if (indirdep == NULL && newindirdep) {
1605 indirdep = newindirdep;
1606 WORKLIST_INSERT_BP(bp, &indirdep->ir_list);
1607 newindirdep = NULL;
1609 FREE_LOCK(&lk);
1610 if (indirdep) {
1611 if (newblk_lookup(ip->i_fs, aip->ai_newblkno, 0,
1612 &newblk) == 0)
1613 panic("setup_allocindir: lost block");
1614 ACQUIRE_LOCK(&lk);
1615 if (newblk->nb_state == DEPCOMPLETE) {
1616 aip->ai_state |= DEPCOMPLETE;
1617 aip->ai_buf = NULL;
1618 } else {
1619 bmsafemap = newblk->nb_bmsafemap;
1620 aip->ai_buf = bmsafemap->sm_buf;
1621 LIST_REMOVE(newblk, nb_deps);
1622 LIST_INSERT_HEAD(&bmsafemap->sm_allocindirhd,
1623 aip, ai_deps);
1625 LIST_REMOVE(newblk, nb_hash);
1626 kfree(newblk, M_NEWBLK);
1627 aip->ai_indirdep = indirdep;
1629 * Check to see if there is an existing dependency
1630 * for this block. If there is, merge the old
1631 * dependency into the new one.
1633 if (aip->ai_oldblkno == 0)
1634 oldaip = NULL;
1635 else
1637 LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next)
1638 if (oldaip->ai_offset == aip->ai_offset)
1639 break;
1640 if (oldaip != NULL) {
1641 if (oldaip->ai_newblkno != aip->ai_oldblkno) {
1642 panic("setup_allocindir_phase2: blkno");
1644 aip->ai_oldblkno = oldaip->ai_oldblkno;
1645 freefrag = oldaip->ai_freefrag;
1646 oldaip->ai_freefrag = aip->ai_freefrag;
1647 aip->ai_freefrag = freefrag;
1648 free_allocindir(oldaip, NULL);
1650 LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
1651 ((ufs_daddr_t *)indirdep->ir_savebp->b_data)
1652 [aip->ai_offset] = aip->ai_oldblkno;
1653 FREE_LOCK(&lk);
1655 if (newindirdep) {
1657 * Avoid any possibility of data corruption by
1658 * ensuring that our old version is thrown away.
1660 newindirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
1661 brelse(newindirdep->ir_savebp);
1662 WORKITEM_FREE((caddr_t)newindirdep, D_INDIRDEP);
1664 if (indirdep)
1665 break;
1666 newindirdep = kmalloc(sizeof(struct indirdep), M_INDIRDEP,
1667 M_SOFTDEP_FLAGS);
1668 newindirdep->ir_list.wk_type = D_INDIRDEP;
1669 newindirdep->ir_state = ATTACHED;
1670 LIST_INIT(&newindirdep->ir_deplisthd);
1671 LIST_INIT(&newindirdep->ir_donehd);
1672 if (bp->b_bio2.bio_offset == NOOFFSET) {
1673 VOP_BMAP(bp->b_vp, bp->b_bio1.bio_offset,
1674 &bp->b_bio2.bio_offset, NULL, NULL,
1675 BUF_CMD_WRITE);
1677 KKASSERT(bp->b_bio2.bio_offset != NOOFFSET);
1678 newindirdep->ir_savebp = getblk(ip->i_devvp,
1679 bp->b_bio2.bio_offset,
1680 bp->b_bcount, 0, 0);
1681 BUF_KERNPROC(newindirdep->ir_savebp);
1682 bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
1687 * Block de-allocation dependencies.
1689 * When blocks are de-allocated, the on-disk pointers must be nullified before
1690 * the blocks are made available for use by other files. (The true
1691 * requirement is that old pointers must be nullified before new on-disk
1692 * pointers are set. We chose this slightly more stringent requirement to
1693 * reduce complexity.) Our implementation handles this dependency by updating
1694 * the inode (or indirect block) appropriately but delaying the actual block
1695 * de-allocation (i.e., freemap and free space count manipulation) until
1696 * after the updated versions reach stable storage. After the disk is
1697 * updated, the blocks can be safely de-allocated whenever it is convenient.
1698 * This implementation handles only the common case of reducing a file's
1699 * length to zero. Other cases are handled by the conventional synchronous
1700 * write approach.
1702 * The ffs implementation with which we worked double-checks
1703 * the state of the block pointers and file size as it reduces
1704 * a file's length. Some of this code is replicated here in our
1705 * soft updates implementation. The freeblks->fb_chkcnt field is
1706 * used to transfer a part of this information to the procedure
1707 * that eventually de-allocates the blocks.
1709 * This routine should be called from the routine that shortens
1710 * a file's length, before the inode's size or block pointers
1711 * are modified. It will save the block pointer information for
1712 * later release and zero the inode so that the calling routine
1713 * can release it.
1715 struct softdep_setup_freeblocks_info {
1716 struct fs *fs;
1717 struct inode *ip;
1720 static int softdep_setup_freeblocks_bp(struct buf *bp, void *data);
1723 * Parameters:
1724 * ip: The inode whose length is to be reduced
1725 * length: The new length for the file
1727 void
1728 softdep_setup_freeblocks(struct inode *ip, off_t length)
1730 struct softdep_setup_freeblocks_info info;
1731 struct freeblks *freeblks;
1732 struct inodedep *inodedep;
1733 struct allocdirect *adp;
1734 struct vnode *vp;
1735 struct buf *bp;
1736 struct fs *fs;
1737 int i, error, delay;
1738 int count;
1740 fs = ip->i_fs;
1741 if (length != 0)
1742 panic("softde_setup_freeblocks: non-zero length");
1743 freeblks = kmalloc(sizeof(struct freeblks), M_FREEBLKS,
1744 M_SOFTDEP_FLAGS | M_ZERO);
1745 freeblks->fb_list.wk_type = D_FREEBLKS;
1746 freeblks->fb_state = ATTACHED;
1747 freeblks->fb_uid = ip->i_uid;
1748 freeblks->fb_previousinum = ip->i_number;
1749 freeblks->fb_devvp = ip->i_devvp;
1750 freeblks->fb_fs = fs;
1751 freeblks->fb_oldsize = ip->i_size;
1752 freeblks->fb_newsize = length;
1753 freeblks->fb_chkcnt = ip->i_blocks;
1754 for (i = 0; i < NDADDR; i++) {
1755 freeblks->fb_dblks[i] = ip->i_db[i];
1756 ip->i_db[i] = 0;
1758 for (i = 0; i < NIADDR; i++) {
1759 freeblks->fb_iblks[i] = ip->i_ib[i];
1760 ip->i_ib[i] = 0;
1762 ip->i_blocks = 0;
1763 ip->i_size = 0;
1765 * Push the zero'ed inode to to its disk buffer so that we are free
1766 * to delete its dependencies below. Once the dependencies are gone
1767 * the buffer can be safely released.
1769 if ((error = bread(ip->i_devvp,
1770 fsbtodoff(fs, ino_to_fsba(fs, ip->i_number)),
1771 (int)fs->fs_bsize, &bp)) != 0)
1772 softdep_error("softdep_setup_freeblocks", error);
1773 *((struct ufs1_dinode *)bp->b_data + ino_to_fsbo(fs, ip->i_number)) =
1774 ip->i_din;
1776 * Find and eliminate any inode dependencies.
1778 ACQUIRE_LOCK(&lk);
1779 (void) inodedep_lookup(fs, ip->i_number, DEPALLOC, &inodedep);
1780 if ((inodedep->id_state & IOSTARTED) != 0) {
1781 panic("softdep_setup_freeblocks: inode busy");
1784 * Add the freeblks structure to the list of operations that
1785 * must await the zero'ed inode being written to disk. If we
1786 * still have a bitmap dependency (delay == 0), then the inode
1787 * has never been written to disk, so we can process the
1788 * freeblks below once we have deleted the dependencies.
1790 delay = (inodedep->id_state & DEPCOMPLETE);
1791 if (delay)
1792 WORKLIST_INSERT(&inodedep->id_bufwait, &freeblks->fb_list);
1794 * Because the file length has been truncated to zero, any
1795 * pending block allocation dependency structures associated
1796 * with this inode are obsolete and can simply be de-allocated.
1797 * We must first merge the two dependency lists to get rid of
1798 * any duplicate freefrag structures, then purge the merged list.
1800 merge_inode_lists(inodedep);
1801 while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
1802 free_allocdirect(&inodedep->id_inoupdt, adp, 1);
1803 FREE_LOCK(&lk);
1804 bdwrite(bp);
1806 * We must wait for any I/O in progress to finish so that
1807 * all potential buffers on the dirty list will be visible.
1808 * Once they are all there, walk the list and get rid of
1809 * any dependencies.
1811 vp = ITOV(ip);
1812 ACQUIRE_LOCK(&lk);
1813 drain_output(vp, 1);
1815 info.fs = fs;
1816 info.ip = ip;
1817 lwkt_gettoken(&vp->v_token);
1818 do {
1819 count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
1820 softdep_setup_freeblocks_bp, &info);
1821 } while (count != 0);
1822 lwkt_reltoken(&vp->v_token);
1824 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) != 0)
1825 (void)free_inodedep(inodedep);
1827 if (delay) {
1828 freeblks->fb_state |= DEPCOMPLETE;
1830 * If the inode with zeroed block pointers is now on disk
1831 * we can start freeing blocks. Add freeblks to the worklist
1832 * instead of calling handle_workitem_freeblocks directly as
1833 * it is more likely that additional IO is needed to complete
1834 * the request here than in the !delay case.
1836 if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
1837 add_to_worklist(&freeblks->fb_list);
1840 FREE_LOCK(&lk);
1842 * If the inode has never been written to disk (delay == 0),
1843 * then we can process the freeblks now that we have deleted
1844 * the dependencies.
1846 if (!delay)
1847 handle_workitem_freeblocks(freeblks);
1850 static int
1851 softdep_setup_freeblocks_bp(struct buf *bp, void *data)
1853 struct softdep_setup_freeblocks_info *info = data;
1854 struct inodedep *inodedep;
1856 if (getdirtybuf(&bp, MNT_WAIT) == 0) {
1857 kprintf("softdep_setup_freeblocks_bp(1): caught bp %p going away\n", bp);
1858 return(-1);
1860 if (bp->b_vp != ITOV(info->ip) || (bp->b_flags & B_DELWRI) == 0) {
1861 kprintf("softdep_setup_freeblocks_bp(2): caught bp %p going away\n", bp);
1862 BUF_UNLOCK(bp);
1863 return(-1);
1865 (void) inodedep_lookup(info->fs, info->ip->i_number, 0, &inodedep);
1866 deallocate_dependencies(bp, inodedep);
1867 bp->b_flags |= B_INVAL | B_NOCACHE;
1868 FREE_LOCK(&lk);
1869 brelse(bp);
1870 ACQUIRE_LOCK(&lk);
1871 return(1);
1875 * Reclaim any dependency structures from a buffer that is about to
1876 * be reallocated to a new vnode. The buffer must be locked, thus,
1877 * no I/O completion operations can occur while we are manipulating
1878 * its associated dependencies. The mutex is held so that other I/O's
1879 * associated with related dependencies do not occur.
1881 static void
1882 deallocate_dependencies(struct buf *bp, struct inodedep *inodedep)
1884 struct worklist *wk;
1885 struct indirdep *indirdep;
1886 struct allocindir *aip;
1887 struct pagedep *pagedep;
1888 struct dirrem *dirrem;
1889 struct diradd *dap;
1890 int i;
1892 while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
1893 switch (wk->wk_type) {
1895 case D_INDIRDEP:
1896 indirdep = WK_INDIRDEP(wk);
1898 * None of the indirect pointers will ever be visible,
1899 * so they can simply be tossed. GOINGAWAY ensures
1900 * that allocated pointers will be saved in the buffer
1901 * cache until they are freed. Note that they will
1902 * only be able to be found by their physical address
1903 * since the inode mapping the logical address will
1904 * be gone. The save buffer used for the safe copy
1905 * was allocated in setup_allocindir_phase2 using
1906 * the physical address so it could be used for this
1907 * purpose. Hence we swap the safe copy with the real
1908 * copy, allowing the safe copy to be freed and holding
1909 * on to the real copy for later use in indir_trunc.
1911 * NOTE: ir_savebp is relative to the block device
1912 * so b_bio1 contains the device block number.
1914 if (indirdep->ir_state & GOINGAWAY) {
1915 panic("deallocate_dependencies: already gone");
1917 indirdep->ir_state |= GOINGAWAY;
1918 while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
1919 free_allocindir(aip, inodedep);
1920 if (bp->b_bio1.bio_offset >= 0 ||
1921 bp->b_bio2.bio_offset != indirdep->ir_savebp->b_bio1.bio_offset) {
1922 panic("deallocate_dependencies: not indir");
1924 bcopy(bp->b_data, indirdep->ir_savebp->b_data,
1925 bp->b_bcount);
1926 WORKLIST_REMOVE(wk);
1927 WORKLIST_INSERT_BP(indirdep->ir_savebp, wk);
1928 continue;
1930 case D_PAGEDEP:
1931 pagedep = WK_PAGEDEP(wk);
1933 * None of the directory additions will ever be
1934 * visible, so they can simply be tossed.
1936 for (i = 0; i < DAHASHSZ; i++)
1937 while ((dap =
1938 LIST_FIRST(&pagedep->pd_diraddhd[i])))
1939 free_diradd(dap);
1940 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
1941 free_diradd(dap);
1943 * Copy any directory remove dependencies to the list
1944 * to be processed after the zero'ed inode is written.
1945 * If the inode has already been written, then they
1946 * can be dumped directly onto the work list.
1948 LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
1949 LIST_REMOVE(dirrem, dm_next);
1950 dirrem->dm_dirinum = pagedep->pd_ino;
1951 if (inodedep == NULL ||
1952 (inodedep->id_state & ALLCOMPLETE) ==
1953 ALLCOMPLETE)
1954 add_to_worklist(&dirrem->dm_list);
1955 else
1956 WORKLIST_INSERT(&inodedep->id_bufwait,
1957 &dirrem->dm_list);
1959 WORKLIST_REMOVE(&pagedep->pd_list);
1960 LIST_REMOVE(pagedep, pd_hash);
1961 WORKITEM_FREE(pagedep, D_PAGEDEP);
1962 continue;
1964 case D_ALLOCINDIR:
1965 free_allocindir(WK_ALLOCINDIR(wk), inodedep);
1966 continue;
1968 case D_ALLOCDIRECT:
1969 case D_INODEDEP:
1970 panic("deallocate_dependencies: Unexpected type %s",
1971 TYPENAME(wk->wk_type));
1972 /* NOTREACHED */
1974 default:
1975 panic("deallocate_dependencies: Unknown type %s",
1976 TYPENAME(wk->wk_type));
1977 /* NOTREACHED */
1983 * Free an allocdirect. Generate a new freefrag work request if appropriate.
1984 * This routine must be called with splbio interrupts blocked.
1986 static void
1987 free_allocdirect(struct allocdirectlst *adphead,
1988 struct allocdirect *adp, int delay)
1990 KKASSERT(lock_held(&lk) > 0);
1992 if ((adp->ad_state & DEPCOMPLETE) == 0)
1993 LIST_REMOVE(adp, ad_deps);
1994 TAILQ_REMOVE(adphead, adp, ad_next);
1995 if ((adp->ad_state & COMPLETE) == 0)
1996 WORKLIST_REMOVE(&adp->ad_list);
1997 if (adp->ad_freefrag != NULL) {
1998 if (delay)
1999 WORKLIST_INSERT(&adp->ad_inodedep->id_bufwait,
2000 &adp->ad_freefrag->ff_list);
2001 else
2002 add_to_worklist(&adp->ad_freefrag->ff_list);
2004 WORKITEM_FREE(adp, D_ALLOCDIRECT);
2008 * Prepare an inode to be freed. The actual free operation is not
2009 * done until the zero'ed inode has been written to disk.
2011 void
2012 softdep_freefile(struct vnode *pvp, ino_t ino, int mode)
2014 struct inode *ip = VTOI(pvp);
2015 struct inodedep *inodedep;
2016 struct freefile *freefile;
2019 * This sets up the inode de-allocation dependency.
2021 freefile = kmalloc(sizeof(struct freefile), M_FREEFILE,
2022 M_SOFTDEP_FLAGS);
2023 freefile->fx_list.wk_type = D_FREEFILE;
2024 freefile->fx_list.wk_state = 0;
2025 freefile->fx_mode = mode;
2026 freefile->fx_oldinum = ino;
2027 freefile->fx_devvp = ip->i_devvp;
2028 freefile->fx_fs = ip->i_fs;
2031 * If the inodedep does not exist, then the zero'ed inode has
2032 * been written to disk. If the allocated inode has never been
2033 * written to disk, then the on-disk inode is zero'ed. In either
2034 * case we can free the file immediately.
2036 ACQUIRE_LOCK(&lk);
2037 if (inodedep_lookup(ip->i_fs, ino, 0, &inodedep) == 0 ||
2038 check_inode_unwritten(inodedep)) {
2039 FREE_LOCK(&lk);
2040 handle_workitem_freefile(freefile);
2041 return;
2043 WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
2044 FREE_LOCK(&lk);
2048 * Check to see if an inode has never been written to disk. If
2049 * so free the inodedep and return success, otherwise return failure.
2050 * This routine must be called with splbio interrupts blocked.
2052 * If we still have a bitmap dependency, then the inode has never
2053 * been written to disk. Drop the dependency as it is no longer
2054 * necessary since the inode is being deallocated. We set the
2055 * ALLCOMPLETE flags since the bitmap now properly shows that the
2056 * inode is not allocated. Even if the inode is actively being
2057 * written, it has been rolled back to its zero'ed state, so we
2058 * are ensured that a zero inode is what is on the disk. For short
2059 * lived files, this change will usually result in removing all the
2060 * dependencies from the inode so that it can be freed immediately.
2062 static int
2063 check_inode_unwritten(struct inodedep *inodedep)
2066 if ((inodedep->id_state & DEPCOMPLETE) != 0 ||
2067 LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2068 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2069 LIST_FIRST(&inodedep->id_inowait) != NULL ||
2070 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2071 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2072 inodedep->id_nlinkdelta != 0)
2073 return (0);
2076 * Another process might be in initiate_write_inodeblock
2077 * trying to allocate memory without holding "Softdep Lock".
2079 if ((inodedep->id_state & IOSTARTED) != 0 &&
2080 inodedep->id_savedino == NULL)
2081 return(0);
2083 inodedep->id_state |= ALLCOMPLETE;
2084 LIST_REMOVE(inodedep, id_deps);
2085 inodedep->id_buf = NULL;
2086 if (inodedep->id_state & ONWORKLIST)
2087 WORKLIST_REMOVE(&inodedep->id_list);
2088 if (inodedep->id_savedino != NULL) {
2089 kfree(inodedep->id_savedino, M_INODEDEP);
2090 inodedep->id_savedino = NULL;
2092 if (free_inodedep(inodedep) == 0) {
2093 panic("check_inode_unwritten: busy inode");
2095 return (1);
2099 * Try to free an inodedep structure. Return 1 if it could be freed.
2101 static int
2102 free_inodedep(struct inodedep *inodedep)
2105 if ((inodedep->id_state & ONWORKLIST) != 0 ||
2106 (inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
2107 LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2108 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2109 LIST_FIRST(&inodedep->id_inowait) != NULL ||
2110 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2111 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2112 inodedep->id_nlinkdelta != 0 || inodedep->id_savedino != NULL)
2113 return (0);
2114 LIST_REMOVE(inodedep, id_hash);
2115 WORKITEM_FREE(inodedep, D_INODEDEP);
2116 num_inodedep -= 1;
2117 return (1);
2121 * This workitem routine performs the block de-allocation.
2122 * The workitem is added to the pending list after the updated
2123 * inode block has been written to disk. As mentioned above,
2124 * checks regarding the number of blocks de-allocated (compared
2125 * to the number of blocks allocated for the file) are also
2126 * performed in this function.
2128 static void
2129 handle_workitem_freeblocks(struct freeblks *freeblks)
2131 struct inode tip;
2132 ufs_daddr_t bn;
2133 struct fs *fs;
2134 int i, level, bsize;
2135 long nblocks, blocksreleased = 0;
2136 int error, allerror = 0;
2137 ufs_lbn_t baselbns[NIADDR], tmpval;
2139 tip.i_number = freeblks->fb_previousinum;
2140 tip.i_devvp = freeblks->fb_devvp;
2141 tip.i_dev = freeblks->fb_devvp->v_rdev;
2142 tip.i_fs = freeblks->fb_fs;
2143 tip.i_size = freeblks->fb_oldsize;
2144 tip.i_uid = freeblks->fb_uid;
2145 fs = freeblks->fb_fs;
2146 tmpval = 1;
2147 baselbns[0] = NDADDR;
2148 for (i = 1; i < NIADDR; i++) {
2149 tmpval *= NINDIR(fs);
2150 baselbns[i] = baselbns[i - 1] + tmpval;
2152 nblocks = btodb(fs->fs_bsize);
2153 blocksreleased = 0;
2155 * Indirect blocks first.
2157 for (level = (NIADDR - 1); level >= 0; level--) {
2158 if ((bn = freeblks->fb_iblks[level]) == 0)
2159 continue;
2160 if ((error = indir_trunc(&tip, fsbtodoff(fs, bn), level,
2161 baselbns[level], &blocksreleased)) == 0)
2162 allerror = error;
2163 ffs_blkfree(&tip, bn, fs->fs_bsize);
2164 blocksreleased += nblocks;
2167 * All direct blocks or frags.
2169 for (i = (NDADDR - 1); i >= 0; i--) {
2170 if ((bn = freeblks->fb_dblks[i]) == 0)
2171 continue;
2172 bsize = blksize(fs, &tip, i);
2173 ffs_blkfree(&tip, bn, bsize);
2174 blocksreleased += btodb(bsize);
2177 #ifdef DIAGNOSTIC
2178 if (freeblks->fb_chkcnt != blocksreleased)
2179 kprintf("handle_workitem_freeblocks: block count\n");
2180 if (allerror)
2181 softdep_error("handle_workitem_freeblks", allerror);
2182 #endif /* DIAGNOSTIC */
2183 WORKITEM_FREE(freeblks, D_FREEBLKS);
2187 * Release blocks associated with the inode ip and stored in the indirect
2188 * block at doffset. If level is greater than SINGLE, the block is an
2189 * indirect block and recursive calls to indirtrunc must be used to
2190 * cleanse other indirect blocks.
2192 static int
2193 indir_trunc(struct inode *ip, off_t doffset, int level, ufs_lbn_t lbn,
2194 long *countp)
2196 struct buf *bp;
2197 ufs_daddr_t *bap;
2198 ufs_daddr_t nb;
2199 struct fs *fs;
2200 struct worklist *wk;
2201 struct indirdep *indirdep;
2202 int i, lbnadd, nblocks;
2203 int error, allerror = 0;
2205 fs = ip->i_fs;
2206 lbnadd = 1;
2207 for (i = level; i > 0; i--)
2208 lbnadd *= NINDIR(fs);
2210 * Get buffer of block pointers to be freed. This routine is not
2211 * called until the zero'ed inode has been written, so it is safe
2212 * to free blocks as they are encountered. Because the inode has
2213 * been zero'ed, calls to bmap on these blocks will fail. So, we
2214 * have to use the on-disk address and the block device for the
2215 * filesystem to look them up. If the file was deleted before its
2216 * indirect blocks were all written to disk, the routine that set
2217 * us up (deallocate_dependencies) will have arranged to leave
2218 * a complete copy of the indirect block in memory for our use.
2219 * Otherwise we have to read the blocks in from the disk.
2221 ACQUIRE_LOCK(&lk);
2222 if ((bp = findblk(ip->i_devvp, doffset, FINDBLK_TEST)) != NULL &&
2223 (wk = LIST_FIRST(&bp->b_dep)) != NULL) {
2225 * bp must be ir_savebp, which is held locked for our use.
2227 if (wk->wk_type != D_INDIRDEP ||
2228 (indirdep = WK_INDIRDEP(wk))->ir_savebp != bp ||
2229 (indirdep->ir_state & GOINGAWAY) == 0) {
2230 panic("indir_trunc: lost indirdep");
2232 WORKLIST_REMOVE(wk);
2233 WORKITEM_FREE(indirdep, D_INDIRDEP);
2234 if (LIST_FIRST(&bp->b_dep) != NULL) {
2235 panic("indir_trunc: dangling dep");
2237 FREE_LOCK(&lk);
2238 } else {
2239 FREE_LOCK(&lk);
2240 error = bread(ip->i_devvp, doffset, (int)fs->fs_bsize, &bp);
2241 if (error)
2242 return (error);
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)
2251 continue;
2252 if (level != 0) {
2253 if ((error = indir_trunc(ip, fsbtodoff(fs, nb),
2254 level - 1, lbn + (i * lbnadd), countp)) != 0)
2255 allerror = error;
2257 ffs_blkfree(ip, nb, fs->fs_bsize);
2258 *countp += nblocks;
2260 bp->b_flags |= B_INVAL | B_NOCACHE;
2261 brelse(bp);
2262 return (allerror);
2266 * Free an allocindir.
2267 * This routine must be called with splbio interrupts blocked.
2269 static void
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);
2284 else
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
2306 * the new offsets.
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.
2314 * Parameters:
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
2321 void
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 */
2327 struct fs *fs;
2328 struct diradd *dap;
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)
2338 bdwrite(newdirbp);
2339 return;
2342 fs = dp->i_fs;
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;
2353 ACQUIRE_LOCK(&lk);
2354 } else {
2355 dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
2356 mkdir1 = kmalloc(sizeof(struct mkdir), M_MKDIR,
2357 M_SOFTDEP_FLAGS);
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,
2362 M_SOFTDEP_FLAGS);
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;
2370 ACQUIRE_LOCK(&lk);
2371 LIST_INSERT_HEAD(&mkdirlisthd, mkdir1, md_mkdirs);
2372 WORKLIST_INSERT_BP(newdirbp, &mkdir1->md_list);
2373 FREE_LOCK(&lk);
2374 bdwrite(newdirbp);
2376 * Dependency on link count increase for parent directory
2378 ACQUIRE_LOCK(&lk);
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);
2383 } else {
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,
2395 da_pdlist);
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);
2404 else
2405 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2406 FREE_LOCK(&lk);
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.
2416 * Parameters:
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
2423 void
2424 softdep_change_directoryentry_offset(struct inode *dp, caddr_t base,
2425 caddr_t oldloc, caddr_t newloc,
2426 int entrysize)
2428 int offset, oldoffset, newoffset;
2429 struct pagedep *pagedep;
2430 struct diradd *dap;
2431 ufs_lbn_t lbn;
2433 ACQUIRE_LOCK(&lk);
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)
2437 goto done;
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)
2443 continue;
2444 dap->da_offset = newoffset;
2445 if (DIRADDHASH(newoffset) == DIRADDHASH(oldoffset))
2446 break;
2447 LIST_REMOVE(dap, da_pdlist);
2448 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(newoffset)],
2449 dap, da_pdlist);
2450 break;
2452 if (dap == NULL) {
2454 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist) {
2455 if (dap->da_offset == oldoffset) {
2456 dap->da_offset = newoffset;
2457 break;
2461 done:
2462 bcopy(oldloc, newloc, entrysize);
2463 FREE_LOCK(&lk);
2467 * Free a diradd dependency structure. This routine must be called
2468 * with splbio interrupts blocked.
2470 static void
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;
2484 } else {
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,
2491 0, &inodedep) != 0)
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)
2497 continue;
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) {
2504 panic("free_diradd: unfound ref");
2507 WORKITEM_FREE(dap, D_DIRADD);
2511 * Directory entry removal dependencies.
2513 * When removing a directory entry, the entry's inode pointer must be
2514 * zero'ed on disk before the corresponding inode's link count is decremented
2515 * (possibly freeing the inode for re-use). This dependency is handled by
2516 * updating the directory entry but delaying the inode count reduction until
2517 * after the directory block has been written to disk. After this point, the
2518 * inode count can be decremented whenever it is convenient.
2522 * This routine should be called immediately after removing
2523 * a directory entry. The inode's link count should not be
2524 * decremented by the calling procedure -- the soft updates
2525 * code will do this task when it is safe.
2527 * Parameters:
2528 * bp: buffer containing directory block
2529 * dp: inode for the directory being modified
2530 * ip: inode for directory entry being removed
2531 * isrmdir: indicates if doing RMDIR
2533 void
2534 softdep_setup_remove(struct buf *bp, struct inode *dp, struct inode *ip,
2535 int isrmdir)
2537 struct dirrem *dirrem, *prevdirrem;
2540 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.
2542 dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
2545 * If the COMPLETE flag is clear, then there were no active
2546 * entries and we want to roll back to a zeroed entry until
2547 * the new inode is committed to disk. If the COMPLETE flag is
2548 * set then we have deleted an entry that never made it to
2549 * disk. If the entry we deleted resulted from a name change,
2550 * then the old name still resides on disk. We cannot delete
2551 * its inode (returned to us in prevdirrem) until the zeroed
2552 * directory entry gets to disk. The new inode has never been
2553 * referenced on the disk, so can be deleted immediately.
2555 if ((dirrem->dm_state & COMPLETE) == 0) {
2556 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
2557 dm_next);
2558 FREE_LOCK(&lk);
2559 } else {
2560 if (prevdirrem != NULL)
2561 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
2562 prevdirrem, dm_next);
2563 dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
2564 FREE_LOCK(&lk);
2565 handle_workitem_remove(dirrem);
2570 * Allocate a new dirrem if appropriate and return it along with
2571 * its associated pagedep. Called without a lock, returns with lock.
2573 static long num_dirrem; /* number of dirrem allocated */
2576 * Parameters:
2577 * bp: buffer containing directory block
2578 * dp: inode for the directory being modified
2579 * ip: inode for directory entry being removed
2580 * isrmdir: indicates if doing RMDIR
2581 * prevdirremp: previously referenced inode, if any
2583 static struct dirrem *
2584 newdirrem(struct buf *bp, struct inode *dp, struct inode *ip,
2585 int isrmdir, struct dirrem **prevdirremp)
2587 int offset;
2588 ufs_lbn_t lbn;
2589 struct diradd *dap;
2590 struct dirrem *dirrem;
2591 struct pagedep *pagedep;
2594 * Whiteouts have no deletion dependencies.
2596 if (ip == NULL)
2597 panic("newdirrem: whiteout");
2599 * If we are over our limit, try to improve the situation.
2600 * Limiting the number of dirrem structures will also limit
2601 * the number of freefile and freeblks structures.
2603 if (num_dirrem > max_softdeps / 4)
2604 speedup_syncer(NULL);
2605 if (num_dirrem > max_softdeps / 2) {
2606 ACQUIRE_LOCK(&lk);
2607 request_cleanup(FLUSH_REMOVE);
2608 FREE_LOCK(&lk);
2611 num_dirrem += 1;
2612 dirrem = kmalloc(sizeof(struct dirrem), M_DIRREM,
2613 M_SOFTDEP_FLAGS | M_ZERO);
2614 dirrem->dm_list.wk_type = D_DIRREM;
2615 dirrem->dm_state = isrmdir ? RMDIR : 0;
2616 dirrem->dm_mnt = ITOV(ip)->v_mount;
2617 dirrem->dm_oldinum = ip->i_number;
2618 *prevdirremp = NULL;
2620 ACQUIRE_LOCK(&lk);
2621 lbn = lblkno(dp->i_fs, dp->i_offset);
2622 offset = blkoff(dp->i_fs, dp->i_offset);
2623 if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2624 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
2625 dirrem->dm_pagedep = pagedep;
2627 * Check for a diradd dependency for the same directory entry.
2628 * If present, then both dependencies become obsolete and can
2629 * be de-allocated. Check for an entry on both the pd_dirraddhd
2630 * list and the pd_pendinghd list.
2633 LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
2634 if (dap->da_offset == offset)
2635 break;
2636 if (dap == NULL) {
2638 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
2639 if (dap->da_offset == offset)
2640 break;
2641 if (dap == NULL)
2642 return (dirrem);
2645 * Must be ATTACHED at this point.
2647 if ((dap->da_state & ATTACHED) == 0) {
2648 panic("newdirrem: not ATTACHED");
2650 if (dap->da_newinum != ip->i_number) {
2651 panic("newdirrem: inum %"PRId64" should be %"PRId64,
2652 ip->i_number, dap->da_newinum);
2655 * If we are deleting a changed name that never made it to disk,
2656 * then return the dirrem describing the previous inode (which
2657 * represents the inode currently referenced from this entry on disk).
2659 if ((dap->da_state & DIRCHG) != 0) {
2660 *prevdirremp = dap->da_previous;
2661 dap->da_state &= ~DIRCHG;
2662 dap->da_pagedep = pagedep;
2665 * We are deleting an entry that never made it to disk.
2666 * Mark it COMPLETE so we can delete its inode immediately.
2668 dirrem->dm_state |= COMPLETE;
2669 free_diradd(dap);
2670 return (dirrem);
2674 * Directory entry change dependencies.
2676 * Changing an existing directory entry requires that an add operation
2677 * be completed first followed by a deletion. The semantics for the addition
2678 * are identical to the description of adding a new entry above except
2679 * that the rollback is to the old inode number rather than zero. Once
2680 * the addition dependency is completed, the removal is done as described
2681 * in the removal routine above.
2685 * This routine should be called immediately after changing
2686 * a directory entry. The inode's link count should not be
2687 * decremented by the calling procedure -- the soft updates
2688 * code will perform this task when it is safe.
2690 * Parameters:
2691 * bp: buffer containing directory block
2692 * dp: inode for the directory being modified
2693 * ip: inode for directory entry being removed
2694 * newinum: new inode number for changed entry
2695 * isrmdir: indicates if doing RMDIR
2697 void
2698 softdep_setup_directory_change(struct buf *bp, struct inode *dp,
2699 struct inode *ip, ino_t newinum,
2700 int isrmdir)
2702 int offset;
2703 struct diradd *dap = NULL;
2704 struct dirrem *dirrem, *prevdirrem;
2705 struct pagedep *pagedep;
2706 struct inodedep *inodedep;
2708 offset = blkoff(dp->i_fs, dp->i_offset);
2711 * Whiteouts do not need diradd dependencies.
2713 if (newinum != WINO) {
2714 dap = kmalloc(sizeof(struct diradd), M_DIRADD,
2715 M_SOFTDEP_FLAGS | M_ZERO);
2716 dap->da_list.wk_type = D_DIRADD;
2717 dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
2718 dap->da_offset = offset;
2719 dap->da_newinum = newinum;
2723 * Allocate a new dirrem and ACQUIRE_LOCK.
2725 dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
2726 pagedep = dirrem->dm_pagedep;
2728 * The possible values for isrmdir:
2729 * 0 - non-directory file rename
2730 * 1 - directory rename within same directory
2731 * inum - directory rename to new directory of given inode number
2732 * When renaming to a new directory, we are both deleting and
2733 * creating a new directory entry, so the link count on the new
2734 * directory should not change. Thus we do not need the followup
2735 * dirrem which is usually done in handle_workitem_remove. We set
2736 * the DIRCHG flag to tell handle_workitem_remove to skip the
2737 * followup dirrem.
2739 if (isrmdir > 1)
2740 dirrem->dm_state |= DIRCHG;
2743 * Whiteouts have no additional dependencies,
2744 * so just put the dirrem on the correct list.
2746 if (newinum == WINO) {
2747 if ((dirrem->dm_state & COMPLETE) == 0) {
2748 LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
2749 dm_next);
2750 } else {
2751 dirrem->dm_dirinum = pagedep->pd_ino;
2752 add_to_worklist(&dirrem->dm_list);
2754 FREE_LOCK(&lk);
2755 return;
2759 * If the COMPLETE flag is clear, then there were no active
2760 * entries and we want to roll back to the previous inode until
2761 * the new inode is committed to disk. If the COMPLETE flag is
2762 * set, then we have deleted an entry that never made it to disk.
2763 * If the entry we deleted resulted from a name change, then the old
2764 * inode reference still resides on disk. Any rollback that we do
2765 * needs to be to that old inode (returned to us in prevdirrem). If
2766 * the entry we deleted resulted from a create, then there is
2767 * no entry on the disk, so we want to roll back to zero rather
2768 * than the uncommitted inode. In either of the COMPLETE cases we
2769 * want to immediately free the unwritten and unreferenced inode.
2771 if ((dirrem->dm_state & COMPLETE) == 0) {
2772 dap->da_previous = dirrem;
2773 } else {
2774 if (prevdirrem != NULL) {
2775 dap->da_previous = prevdirrem;
2776 } else {
2777 dap->da_state &= ~DIRCHG;
2778 dap->da_pagedep = pagedep;
2780 dirrem->dm_dirinum = pagedep->pd_ino;
2781 add_to_worklist(&dirrem->dm_list);
2784 * Link into its inodedep. Put it on the id_bufwait list if the inode
2785 * is not yet written. If it is written, do the post-inode write
2786 * processing to put it on the id_pendinghd list.
2788 if (inodedep_lookup(dp->i_fs, newinum, DEPALLOC, &inodedep) == 0 ||
2789 (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2790 dap->da_state |= COMPLETE;
2791 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
2792 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
2793 } else {
2794 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
2795 dap, da_pdlist);
2796 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2798 FREE_LOCK(&lk);
2802 * Called whenever the link count on an inode is changed.
2803 * It creates an inode dependency so that the new reference(s)
2804 * to the inode cannot be committed to disk until the updated
2805 * inode has been written.
2807 * Parameters:
2808 * ip: the inode with the increased link count
2810 void
2811 softdep_change_linkcnt(struct inode *ip)
2813 struct inodedep *inodedep;
2815 ACQUIRE_LOCK(&lk);
2816 (void) inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC, &inodedep);
2817 if (ip->i_nlink < ip->i_effnlink) {
2818 panic("softdep_change_linkcnt: bad delta");
2820 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2821 FREE_LOCK(&lk);
2825 * This workitem decrements the inode's link count.
2826 * If the link count reaches zero, the file is removed.
2828 static void
2829 handle_workitem_remove(struct dirrem *dirrem)
2831 struct inodedep *inodedep;
2832 struct vnode *vp;
2833 struct inode *ip;
2834 ino_t oldinum;
2835 int error;
2837 error = VFS_VGET(dirrem->dm_mnt, NULL, dirrem->dm_oldinum, &vp);
2838 if (error) {
2839 softdep_error("handle_workitem_remove: vget", error);
2840 return;
2842 ip = VTOI(vp);
2843 ACQUIRE_LOCK(&lk);
2844 if ((inodedep_lookup(ip->i_fs, dirrem->dm_oldinum, 0, &inodedep)) == 0){
2845 panic("handle_workitem_remove: lost inodedep");
2848 * Normal file deletion.
2850 if ((dirrem->dm_state & RMDIR) == 0) {
2851 ip->i_nlink--;
2852 ip->i_flag |= IN_CHANGE;
2853 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;
2857 FREE_LOCK(&lk);
2858 vput(vp);
2859 num_dirrem -= 1;
2860 WORKITEM_FREE(dirrem, D_DIRREM);
2861 return;
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 "..".
2870 ip->i_nlink -= 2;
2871 ip->i_flag |= IN_CHANGE;
2872 if (ip->i_nlink < ip->i_effnlink) {
2873 panic("handle_workitem_remove: bad dir delta");
2875 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2876 FREE_LOCK(&lk);
2877 if ((error = ffs_truncate(vp, (off_t)0, 0, proc0.p_ucred)) != 0)
2878 softdep_error("handle_workitem_remove: truncate", error);
2880 * Rename a directory to a new parent. Since, we are both deleting
2881 * and creating a new directory entry, the link count on the new
2882 * directory should not change. Thus we skip the followup dirrem.
2884 if (dirrem->dm_state & DIRCHG) {
2885 vput(vp);
2886 num_dirrem -= 1;
2887 WORKITEM_FREE(dirrem, D_DIRREM);
2888 return;
2891 * If the inodedep does not exist, then the zero'ed inode has
2892 * been written to disk. If the allocated inode has never been
2893 * written to disk, then the on-disk inode is zero'ed. In either
2894 * case we can remove the file immediately.
2896 ACQUIRE_LOCK(&lk);
2897 dirrem->dm_state = 0;
2898 oldinum = dirrem->dm_oldinum;
2899 dirrem->dm_oldinum = dirrem->dm_dirinum;
2900 if (inodedep_lookup(ip->i_fs, oldinum, 0, &inodedep) == 0 ||
2901 check_inode_unwritten(inodedep)) {
2902 FREE_LOCK(&lk);
2903 vput(vp);
2904 handle_workitem_remove(dirrem);
2905 return;
2907 WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
2908 FREE_LOCK(&lk);
2909 ip->i_flag |= IN_CHANGE;
2910 ffs_update(vp, 0);
2911 vput(vp);
2915 * Inode de-allocation dependencies.
2917 * When an inode's link count is reduced to zero, it can be de-allocated. We
2918 * found it convenient to postpone de-allocation until after the inode is
2919 * written to disk with its new link count (zero). At this point, all of the
2920 * on-disk inode's block pointers are nullified and, with careful dependency
2921 * list ordering, all dependencies related to the inode will be satisfied and
2922 * the corresponding dependency structures de-allocated. So, if/when the
2923 * inode is reused, there will be no mixing of old dependencies with new
2924 * ones. This artificial dependency is set up by the block de-allocation
2925 * procedure above (softdep_setup_freeblocks) and completed by the
2926 * following procedure.
2928 static void
2929 handle_workitem_freefile(struct freefile *freefile)
2931 struct vnode vp;
2932 struct inode tip;
2933 struct inodedep *idp;
2934 int error;
2936 #ifdef DEBUG
2937 ACQUIRE_LOCK(&lk);
2938 error = inodedep_lookup(freefile->fx_fs, freefile->fx_oldinum, 0, &idp);
2939 FREE_LOCK(&lk);
2940 if (error)
2941 panic("handle_workitem_freefile: inodedep survived");
2942 #endif
2943 tip.i_devvp = freefile->fx_devvp;
2944 tip.i_dev = freefile->fx_devvp->v_rdev;
2945 tip.i_fs = freefile->fx_fs;
2946 vp.v_data = &tip;
2947 if ((error = ffs_freefile(&vp, freefile->fx_oldinum, freefile->fx_mode)) != 0)
2948 softdep_error("handle_workitem_freefile", error);
2949 WORKITEM_FREE(freefile, D_FREEFILE);
2953 * Helper function which unlinks marker element from work list and returns
2954 * the next element on the list.
2956 static __inline struct worklist *
2957 markernext(struct worklist *marker)
2959 struct worklist *next;
2961 next = LIST_NEXT(marker, wk_list);
2962 LIST_REMOVE(marker, wk_list);
2963 return next;
2967 * checkread, checkwrite
2969 * bioops callback - hold io_token
2971 static int
2972 softdep_checkread(struct buf *bp)
2974 /* nothing to do, mp lock not needed */
2975 return(0);
2979 * bioops callback - hold io_token
2981 static int
2982 softdep_checkwrite(struct buf *bp)
2984 /* nothing to do, mp lock not needed */
2985 return(0);
2989 * Disk writes.
2991 * The dependency structures constructed above are most actively used when file
2992 * system blocks are written to disk. No constraints are placed on when a
2993 * block can be written, but unsatisfied update dependencies are made safe by
2994 * modifying (or replacing) the source memory for the duration of the disk
2995 * write. When the disk write completes, the memory block is again brought
2996 * up-to-date.
2998 * In-core inode structure reclamation.
3000 * Because there are a finite number of "in-core" inode structures, they are
3001 * reused regularly. By transferring all inode-related dependencies to the
3002 * in-memory inode block and indexing them separately (via "inodedep"s), we
3003 * can allow "in-core" inode structures to be reused at any time and avoid
3004 * any increase in contention.
3006 * Called just before entering the device driver to initiate a new disk I/O.
3007 * The buffer must be locked, thus, no I/O completion operations can occur
3008 * while we are manipulating its associated dependencies.
3010 * bioops callback - hold io_token
3012 * Parameters:
3013 * bp: structure describing disk write to occur
3015 static void
3016 softdep_disk_io_initiation(struct buf *bp)
3018 struct worklist *wk;
3019 struct worklist marker;
3020 struct indirdep *indirdep;
3023 * We only care about write operations. There should never
3024 * be dependencies for reads.
3026 if (bp->b_cmd == BUF_CMD_READ)
3027 panic("softdep_disk_io_initiation: read");
3029 ACQUIRE_LOCK(&lk);
3030 marker.wk_type = D_LAST + 1; /* Not a normal workitem */
3033 * Do any necessary pre-I/O processing.
3035 for (wk = LIST_FIRST(&bp->b_dep); wk; wk = markernext(&marker)) {
3036 LIST_INSERT_AFTER(wk, &marker, wk_list);
3038 switch (wk->wk_type) {
3039 case D_PAGEDEP:
3040 initiate_write_filepage(WK_PAGEDEP(wk), bp);
3041 continue;
3043 case D_INODEDEP:
3044 initiate_write_inodeblock(WK_INODEDEP(wk), bp);
3045 continue;
3047 case D_INDIRDEP:
3048 indirdep = WK_INDIRDEP(wk);
3049 if (indirdep->ir_state & GOINGAWAY)
3050 panic("disk_io_initiation: indirdep gone");
3052 * If there are no remaining dependencies, this
3053 * will be writing the real pointers, so the
3054 * dependency can be freed.
3056 if (LIST_FIRST(&indirdep->ir_deplisthd) == NULL) {
3057 indirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
3058 brelse(indirdep->ir_savebp);
3059 /* inline expand WORKLIST_REMOVE(wk); */
3060 wk->wk_state &= ~ONWORKLIST;
3061 LIST_REMOVE(wk, wk_list);
3062 WORKITEM_FREE(indirdep, D_INDIRDEP);
3063 continue;
3066 * Replace up-to-date version with safe version.
3068 indirdep->ir_saveddata = kmalloc(bp->b_bcount,
3069 M_INDIRDEP,
3070 M_SOFTDEP_FLAGS);
3071 ACQUIRE_LOCK(&lk);
3072 indirdep->ir_state &= ~ATTACHED;
3073 indirdep->ir_state |= UNDONE;
3074 bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
3075 bcopy(indirdep->ir_savebp->b_data, bp->b_data,
3076 bp->b_bcount);
3077 FREE_LOCK(&lk);
3078 continue;
3080 case D_MKDIR:
3081 case D_BMSAFEMAP:
3082 case D_ALLOCDIRECT:
3083 case D_ALLOCINDIR:
3084 continue;
3086 default:
3087 panic("handle_disk_io_initiation: Unexpected type %s",
3088 TYPENAME(wk->wk_type));
3089 /* NOTREACHED */
3092 FREE_LOCK(&lk);
3096 * Called from within the procedure above to deal with unsatisfied
3097 * allocation dependencies in a directory. The buffer must be locked,
3098 * thus, no I/O completion operations can occur while we are
3099 * manipulating its associated dependencies.
3101 static void
3102 initiate_write_filepage(struct pagedep *pagedep, struct buf *bp)
3104 struct diradd *dap;
3105 struct direct *ep;
3106 int i;
3108 if (pagedep->pd_state & IOSTARTED) {
3110 * This can only happen if there is a driver that does not
3111 * understand chaining. Here biodone will reissue the call
3112 * to strategy for the incomplete buffers.
3114 kprintf("initiate_write_filepage: already started\n");
3115 return;
3117 pagedep->pd_state |= IOSTARTED;
3118 ACQUIRE_LOCK(&lk);
3119 for (i = 0; i < DAHASHSZ; i++) {
3120 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
3121 ep = (struct direct *)
3122 ((char *)bp->b_data + dap->da_offset);
3123 if (ep->d_ino != dap->da_newinum) {
3124 panic("%s: dir inum %d != new %"PRId64,
3125 "initiate_write_filepage",
3126 ep->d_ino, dap->da_newinum);
3128 if (dap->da_state & DIRCHG)
3129 ep->d_ino = dap->da_previous->dm_oldinum;
3130 else
3131 ep->d_ino = 0;
3132 dap->da_state &= ~ATTACHED;
3133 dap->da_state |= UNDONE;
3136 FREE_LOCK(&lk);
3140 * Called from within the procedure above to deal with unsatisfied
3141 * allocation dependencies in an inodeblock. The buffer must be
3142 * locked, thus, no I/O completion operations can occur while we
3143 * are manipulating its associated dependencies.
3145 * Parameters:
3146 * bp: The inode block
3148 static void
3149 initiate_write_inodeblock(struct inodedep *inodedep, struct buf *bp)
3151 struct allocdirect *adp, *lastadp;
3152 struct ufs1_dinode *dp;
3153 struct ufs1_dinode *sip;
3154 struct fs *fs;
3155 ufs_lbn_t prevlbn = 0;
3156 int i, deplist;
3158 if (inodedep->id_state & IOSTARTED)
3159 panic("initiate_write_inodeblock: already started");
3160 inodedep->id_state |= IOSTARTED;
3161 fs = inodedep->id_fs;
3162 dp = (struct ufs1_dinode *)bp->b_data +
3163 ino_to_fsbo(fs, inodedep->id_ino);
3165 * If the bitmap is not yet written, then the allocated
3166 * inode cannot be written to disk.
3168 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
3169 if (inodedep->id_savedino != NULL)
3170 panic("initiate_write_inodeblock: already doing I/O");
3171 sip = kmalloc(sizeof(struct ufs1_dinode), M_INODEDEP,
3172 M_SOFTDEP_FLAGS);
3173 inodedep->id_savedino = sip;
3174 *inodedep->id_savedino = *dp;
3175 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
3176 dp->di_gen = inodedep->id_savedino->di_gen;
3177 return;
3180 * If no dependencies, then there is nothing to roll back.
3182 inodedep->id_savedsize = dp->di_size;
3183 if (TAILQ_FIRST(&inodedep->id_inoupdt) == NULL)
3184 return;
3186 * Set the dependencies to busy.
3188 ACQUIRE_LOCK(&lk);
3189 for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3190 adp = TAILQ_NEXT(adp, ad_next)) {
3191 #ifdef DIAGNOSTIC
3192 if (deplist != 0 && prevlbn >= adp->ad_lbn) {
3193 panic("softdep_write_inodeblock: lbn order");
3195 prevlbn = adp->ad_lbn;
3196 if (adp->ad_lbn < NDADDR &&
3197 dp->di_db[adp->ad_lbn] != adp->ad_newblkno) {
3198 panic("%s: direct pointer #%ld mismatch %d != %d",
3199 "softdep_write_inodeblock", adp->ad_lbn,
3200 dp->di_db[adp->ad_lbn], adp->ad_newblkno);
3202 if (adp->ad_lbn >= NDADDR &&
3203 dp->di_ib[adp->ad_lbn - NDADDR] != adp->ad_newblkno) {
3204 panic("%s: indirect pointer #%ld mismatch %d != %d",
3205 "softdep_write_inodeblock", adp->ad_lbn - NDADDR,
3206 dp->di_ib[adp->ad_lbn - NDADDR], adp->ad_newblkno);
3208 deplist |= 1 << adp->ad_lbn;
3209 if ((adp->ad_state & ATTACHED) == 0) {
3210 panic("softdep_write_inodeblock: Unknown state 0x%x",
3211 adp->ad_state);
3213 #endif /* DIAGNOSTIC */
3214 adp->ad_state &= ~ATTACHED;
3215 adp->ad_state |= UNDONE;
3218 * The on-disk inode cannot claim to be any larger than the last
3219 * fragment that has been written. Otherwise, the on-disk inode
3220 * might have fragments that were not the last block in the file
3221 * which would corrupt the filesystem.
3223 for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3224 lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
3225 if (adp->ad_lbn >= NDADDR)
3226 break;
3227 dp->di_db[adp->ad_lbn] = adp->ad_oldblkno;
3228 /* keep going until hitting a rollback to a frag */
3229 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
3230 continue;
3231 dp->di_size = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
3232 for (i = adp->ad_lbn + 1; i < NDADDR; i++) {
3233 #ifdef DIAGNOSTIC
3234 if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0) {
3235 panic("softdep_write_inodeblock: lost dep1");
3237 #endif /* DIAGNOSTIC */
3238 dp->di_db[i] = 0;
3240 for (i = 0; i < NIADDR; i++) {
3241 #ifdef DIAGNOSTIC
3242 if (dp->di_ib[i] != 0 &&
3243 (deplist & ((1 << NDADDR) << i)) == 0) {
3244 panic("softdep_write_inodeblock: lost dep2");
3246 #endif /* DIAGNOSTIC */
3247 dp->di_ib[i] = 0;
3249 FREE_LOCK(&lk);
3250 return;
3253 * If we have zero'ed out the last allocated block of the file,
3254 * roll back the size to the last currently allocated block.
3255 * We know that this last allocated block is a full-sized as
3256 * we already checked for fragments in the loop above.
3258 if (lastadp != NULL &&
3259 dp->di_size <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
3260 for (i = lastadp->ad_lbn; i >= 0; i--)
3261 if (dp->di_db[i] != 0)
3262 break;
3263 dp->di_size = (i + 1) * fs->fs_bsize;
3266 * The only dependencies are for indirect blocks.
3268 * The file size for indirect block additions is not guaranteed.
3269 * Such a guarantee would be non-trivial to achieve. The conventional
3270 * synchronous write implementation also does not make this guarantee.
3271 * Fsck should catch and fix discrepancies. Arguably, the file size
3272 * can be over-estimated without destroying integrity when the file
3273 * moves into the indirect blocks (i.e., is large). If we want to
3274 * postpone fsck, we are stuck with this argument.
3276 for (; adp; adp = TAILQ_NEXT(adp, ad_next))
3277 dp->di_ib[adp->ad_lbn - NDADDR] = 0;
3278 FREE_LOCK(&lk);
3282 * This routine is called during the completion interrupt
3283 * service routine for a disk write (from the procedure called
3284 * by the device driver to inform the filesystem caches of
3285 * a request completion). It should be called early in this
3286 * procedure, before the block is made available to other
3287 * processes or other routines are called.
3289 * bioops callback - hold io_token
3291 * Parameters:
3292 * bp: describes the completed disk write
3294 static void
3295 softdep_disk_write_complete(struct buf *bp)
3297 struct worklist *wk;
3298 struct workhead reattach;
3299 struct newblk *newblk;
3300 struct allocindir *aip;
3301 struct allocdirect *adp;
3302 struct indirdep *indirdep;
3303 struct inodedep *inodedep;
3304 struct bmsafemap *bmsafemap;
3306 ACQUIRE_LOCK(&lk);
3308 LIST_INIT(&reattach);
3309 while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
3310 WORKLIST_REMOVE(wk);
3311 switch (wk->wk_type) {
3313 case D_PAGEDEP:
3314 if (handle_written_filepage(WK_PAGEDEP(wk), bp))
3315 WORKLIST_INSERT(&reattach, wk);
3316 continue;
3318 case D_INODEDEP:
3319 if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
3320 WORKLIST_INSERT(&reattach, wk);
3321 continue;
3323 case D_BMSAFEMAP:
3324 bmsafemap = WK_BMSAFEMAP(wk);
3325 while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkhd))) {
3326 newblk->nb_state |= DEPCOMPLETE;
3327 newblk->nb_bmsafemap = NULL;
3328 LIST_REMOVE(newblk, nb_deps);
3330 while ((adp =
3331 LIST_FIRST(&bmsafemap->sm_allocdirecthd))) {
3332 adp->ad_state |= DEPCOMPLETE;
3333 adp->ad_buf = NULL;
3334 LIST_REMOVE(adp, ad_deps);
3335 handle_allocdirect_partdone(adp);
3337 while ((aip =
3338 LIST_FIRST(&bmsafemap->sm_allocindirhd))) {
3339 aip->ai_state |= DEPCOMPLETE;
3340 aip->ai_buf = NULL;
3341 LIST_REMOVE(aip, ai_deps);
3342 handle_allocindir_partdone(aip);
3344 while ((inodedep =
3345 LIST_FIRST(&bmsafemap->sm_inodedephd)) != NULL) {
3346 inodedep->id_state |= DEPCOMPLETE;
3347 LIST_REMOVE(inodedep, id_deps);
3348 inodedep->id_buf = NULL;
3350 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
3351 continue;
3353 case D_MKDIR:
3354 handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
3355 continue;
3357 case D_ALLOCDIRECT:
3358 adp = WK_ALLOCDIRECT(wk);
3359 adp->ad_state |= COMPLETE;
3360 handle_allocdirect_partdone(adp);
3361 continue;
3363 case D_ALLOCINDIR:
3364 aip = WK_ALLOCINDIR(wk);
3365 aip->ai_state |= COMPLETE;
3366 handle_allocindir_partdone(aip);
3367 continue;
3369 case D_INDIRDEP:
3370 indirdep = WK_INDIRDEP(wk);
3371 if (indirdep->ir_state & GOINGAWAY) {
3372 panic("disk_write_complete: indirdep gone");
3374 bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
3375 kfree(indirdep->ir_saveddata, M_INDIRDEP);
3376 indirdep->ir_saveddata = NULL;
3377 indirdep->ir_state &= ~UNDONE;
3378 indirdep->ir_state |= ATTACHED;
3379 while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
3380 handle_allocindir_partdone(aip);
3381 if (aip == LIST_FIRST(&indirdep->ir_donehd)) {
3382 panic("disk_write_complete: not gone");
3385 WORKLIST_INSERT(&reattach, wk);
3386 if ((bp->b_flags & B_DELWRI) == 0)
3387 stat_indir_blk_ptrs++;
3388 bdirty(bp);
3389 continue;
3391 default:
3392 panic("handle_disk_write_complete: Unknown type %s",
3393 TYPENAME(wk->wk_type));
3394 /* NOTREACHED */
3398 * Reattach any requests that must be redone.
3400 while ((wk = LIST_FIRST(&reattach)) != NULL) {
3401 WORKLIST_REMOVE(wk);
3402 WORKLIST_INSERT_BP(bp, wk);
3405 FREE_LOCK(&lk);
3409 * Called from within softdep_disk_write_complete above. Note that
3410 * this routine is always called from interrupt level with further
3411 * splbio interrupts blocked.
3413 * Parameters:
3414 * adp: the completed allocdirect
3416 static void
3417 handle_allocdirect_partdone(struct allocdirect *adp)
3419 struct allocdirect *listadp;
3420 struct inodedep *inodedep;
3421 long bsize;
3423 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3424 return;
3425 if (adp->ad_buf != NULL)
3426 panic("handle_allocdirect_partdone: dangling dep");
3429 * The on-disk inode cannot claim to be any larger than the last
3430 * fragment that has been written. Otherwise, the on-disk inode
3431 * might have fragments that were not the last block in the file
3432 * which would corrupt the filesystem. Thus, we cannot free any
3433 * allocdirects after one whose ad_oldblkno claims a fragment as
3434 * these blocks must be rolled back to zero before writing the inode.
3435 * We check the currently active set of allocdirects in id_inoupdt.
3437 inodedep = adp->ad_inodedep;
3438 bsize = inodedep->id_fs->fs_bsize;
3439 TAILQ_FOREACH(listadp, &inodedep->id_inoupdt, ad_next) {
3440 /* found our block */
3441 if (listadp == adp)
3442 break;
3443 /* continue if ad_oldlbn is not a fragment */
3444 if (listadp->ad_oldsize == 0 ||
3445 listadp->ad_oldsize == bsize)
3446 continue;
3447 /* hit a fragment */
3448 return;
3451 * If we have reached the end of the current list without
3452 * finding the just finished dependency, then it must be
3453 * on the future dependency list. Future dependencies cannot
3454 * be freed until they are moved to the current list.
3456 if (listadp == NULL) {
3457 #ifdef DEBUG
3458 TAILQ_FOREACH(listadp, &inodedep->id_newinoupdt, ad_next)
3459 /* found our block */
3460 if (listadp == adp)
3461 break;
3462 if (listadp == NULL)
3463 panic("handle_allocdirect_partdone: lost dep");
3464 #endif /* DEBUG */
3465 return;
3468 * If we have found the just finished dependency, then free
3469 * it along with anything that follows it that is complete.
3471 for (; adp; adp = listadp) {
3472 listadp = TAILQ_NEXT(adp, ad_next);
3473 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3474 return;
3475 free_allocdirect(&inodedep->id_inoupdt, adp, 1);
3480 * Called from within softdep_disk_write_complete above. Note that
3481 * this routine is always called from interrupt level with further
3482 * splbio interrupts blocked.
3484 * Parameters:
3485 * aip: the completed allocindir
3487 static void
3488 handle_allocindir_partdone(struct allocindir *aip)
3490 struct indirdep *indirdep;
3492 if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
3493 return;
3494 if (aip->ai_buf != NULL)
3495 panic("handle_allocindir_partdone: dangling dependency");
3497 indirdep = aip->ai_indirdep;
3498 if (indirdep->ir_state & UNDONE) {
3499 LIST_REMOVE(aip, ai_next);
3500 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
3501 return;
3503 ((ufs_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
3504 aip->ai_newblkno;
3505 LIST_REMOVE(aip, ai_next);
3506 if (aip->ai_freefrag != NULL)
3507 add_to_worklist(&aip->ai_freefrag->ff_list);
3508 WORKITEM_FREE(aip, D_ALLOCINDIR);
3512 * Called from within softdep_disk_write_complete above to restore
3513 * in-memory inode block contents to their most up-to-date state. Note
3514 * that this routine is always called from interrupt level with further
3515 * splbio interrupts blocked.
3517 * Parameters:
3518 * bp: buffer containing the inode block
3520 static int
3521 handle_written_inodeblock(struct inodedep *inodedep, struct buf *bp)
3523 struct worklist *wk, *filefree;
3524 struct allocdirect *adp, *nextadp;
3525 struct ufs1_dinode *dp;
3526 int hadchanges;
3528 if ((inodedep->id_state & IOSTARTED) == 0)
3529 panic("handle_written_inodeblock: not started");
3531 inodedep->id_state &= ~IOSTARTED;
3532 dp = (struct ufs1_dinode *)bp->b_data +
3533 ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
3535 * If we had to rollback the inode allocation because of
3536 * bitmaps being incomplete, then simply restore it.
3537 * Keep the block dirty so that it will not be reclaimed until
3538 * all associated dependencies have been cleared and the
3539 * corresponding updates written to disk.
3541 if (inodedep->id_savedino != NULL) {
3542 *dp = *inodedep->id_savedino;
3543 kfree(inodedep->id_savedino, M_INODEDEP);
3544 inodedep->id_savedino = NULL;
3545 if ((bp->b_flags & B_DELWRI) == 0)
3546 stat_inode_bitmap++;
3547 bdirty(bp);
3548 return (1);
3550 inodedep->id_state |= COMPLETE;
3552 * Roll forward anything that had to be rolled back before
3553 * the inode could be updated.
3555 hadchanges = 0;
3556 for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
3557 nextadp = TAILQ_NEXT(adp, ad_next);
3558 if (adp->ad_state & ATTACHED)
3559 panic("handle_written_inodeblock: new entry");
3561 if (adp->ad_lbn < NDADDR) {
3562 if (dp->di_db[adp->ad_lbn] != adp->ad_oldblkno) {
3563 panic("%s: %s #%ld mismatch %d != %d",
3564 "handle_written_inodeblock",
3565 "direct pointer", adp->ad_lbn,
3566 dp->di_db[adp->ad_lbn], adp->ad_oldblkno);
3568 dp->di_db[adp->ad_lbn] = adp->ad_newblkno;
3569 } else {
3570 if (dp->di_ib[adp->ad_lbn - NDADDR] != 0) {
3571 panic("%s: %s #%ld allocated as %d",
3572 "handle_written_inodeblock",
3573 "indirect pointer", adp->ad_lbn - NDADDR,
3574 dp->di_ib[adp->ad_lbn - NDADDR]);
3576 dp->di_ib[adp->ad_lbn - NDADDR] = adp->ad_newblkno;
3578 adp->ad_state &= ~UNDONE;
3579 adp->ad_state |= ATTACHED;
3580 hadchanges = 1;
3582 if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
3583 stat_direct_blk_ptrs++;
3585 * Reset the file size to its most up-to-date value.
3587 if (inodedep->id_savedsize == -1) {
3588 panic("handle_written_inodeblock: bad size");
3590 if (dp->di_size != inodedep->id_savedsize) {
3591 dp->di_size = inodedep->id_savedsize;
3592 hadchanges = 1;
3594 inodedep->id_savedsize = -1;
3596 * If there were any rollbacks in the inode block, then it must be
3597 * marked dirty so that its will eventually get written back in
3598 * its correct form.
3600 if (hadchanges)
3601 bdirty(bp);
3603 * Process any allocdirects that completed during the update.
3605 if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
3606 handle_allocdirect_partdone(adp);
3608 * Process deallocations that were held pending until the
3609 * inode had been written to disk. Freeing of the inode
3610 * is delayed until after all blocks have been freed to
3611 * avoid creation of new <vfsid, inum, lbn> triples
3612 * before the old ones have been deleted.
3614 filefree = NULL;
3615 while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
3616 WORKLIST_REMOVE(wk);
3617 switch (wk->wk_type) {
3619 case D_FREEFILE:
3621 * We defer adding filefree to the worklist until
3622 * all other additions have been made to ensure
3623 * that it will be done after all the old blocks
3624 * have been freed.
3626 if (filefree != NULL) {
3627 panic("handle_written_inodeblock: filefree");
3629 filefree = wk;
3630 continue;
3632 case D_MKDIR:
3633 handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
3634 continue;
3636 case D_DIRADD:
3637 diradd_inode_written(WK_DIRADD(wk), inodedep);
3638 continue;
3640 case D_FREEBLKS:
3641 wk->wk_state |= COMPLETE;
3642 if ((wk->wk_state & ALLCOMPLETE) != ALLCOMPLETE)
3643 continue;
3644 /* -- fall through -- */
3645 case D_FREEFRAG:
3646 case D_DIRREM:
3647 add_to_worklist(wk);
3648 continue;
3650 default:
3651 panic("handle_written_inodeblock: Unknown type %s",
3652 TYPENAME(wk->wk_type));
3653 /* NOTREACHED */
3656 if (filefree != NULL) {
3657 if (free_inodedep(inodedep) == 0) {
3658 panic("handle_written_inodeblock: live inodedep");
3660 add_to_worklist(filefree);
3661 return (0);
3665 * If no outstanding dependencies, free it.
3667 if (free_inodedep(inodedep) || TAILQ_FIRST(&inodedep->id_inoupdt) == NULL)
3668 return (0);
3669 return (hadchanges);
3673 * Process a diradd entry after its dependent inode has been written.
3674 * This routine must be called with splbio interrupts blocked.
3676 static void
3677 diradd_inode_written(struct diradd *dap, struct inodedep *inodedep)
3679 struct pagedep *pagedep;
3681 dap->da_state |= COMPLETE;
3682 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3683 if (dap->da_state & DIRCHG)
3684 pagedep = dap->da_previous->dm_pagedep;
3685 else
3686 pagedep = dap->da_pagedep;
3687 LIST_REMOVE(dap, da_pdlist);
3688 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3690 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
3694 * Handle the completion of a mkdir dependency.
3696 static void
3697 handle_written_mkdir(struct mkdir *mkdir, int type)
3699 struct diradd *dap;
3700 struct pagedep *pagedep;
3702 if (mkdir->md_state != type) {
3703 panic("handle_written_mkdir: bad type");
3705 dap = mkdir->md_diradd;
3706 dap->da_state &= ~type;
3707 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
3708 dap->da_state |= DEPCOMPLETE;
3709 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3710 if (dap->da_state & DIRCHG)
3711 pagedep = dap->da_previous->dm_pagedep;
3712 else
3713 pagedep = dap->da_pagedep;
3714 LIST_REMOVE(dap, da_pdlist);
3715 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3717 LIST_REMOVE(mkdir, md_mkdirs);
3718 WORKITEM_FREE(mkdir, D_MKDIR);
3722 * Called from within softdep_disk_write_complete above.
3723 * A write operation was just completed. Removed inodes can
3724 * now be freed and associated block pointers may be committed.
3725 * Note that this routine is always called from interrupt level
3726 * with further splbio interrupts blocked.
3728 * Parameters:
3729 * bp: buffer containing the written page
3731 static int
3732 handle_written_filepage(struct pagedep *pagedep, struct buf *bp)
3734 struct dirrem *dirrem;
3735 struct diradd *dap, *nextdap;
3736 struct direct *ep;
3737 int i, chgs;
3739 if ((pagedep->pd_state & IOSTARTED) == 0) {
3740 panic("handle_written_filepage: not started");
3742 pagedep->pd_state &= ~IOSTARTED;
3744 * Process any directory removals that have been committed.
3746 while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
3747 LIST_REMOVE(dirrem, dm_next);
3748 dirrem->dm_dirinum = pagedep->pd_ino;
3749 add_to_worklist(&dirrem->dm_list);
3752 * Free any directory additions that have been committed.
3754 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
3755 free_diradd(dap);
3757 * Uncommitted directory entries must be restored.
3759 for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
3760 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
3761 dap = nextdap) {
3762 nextdap = LIST_NEXT(dap, da_pdlist);
3763 if (dap->da_state & ATTACHED) {
3764 panic("handle_written_filepage: attached");
3766 ep = (struct direct *)
3767 ((char *)bp->b_data + dap->da_offset);
3768 ep->d_ino = dap->da_newinum;
3769 dap->da_state &= ~UNDONE;
3770 dap->da_state |= ATTACHED;
3771 chgs = 1;
3773 * If the inode referenced by the directory has
3774 * been written out, then the dependency can be
3775 * moved to the pending list.
3777 if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3778 LIST_REMOVE(dap, da_pdlist);
3779 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
3780 da_pdlist);
3785 * If there were any rollbacks in the directory, then it must be
3786 * marked dirty so that its will eventually get written back in
3787 * its correct form.
3789 if (chgs) {
3790 if ((bp->b_flags & B_DELWRI) == 0)
3791 stat_dir_entry++;
3792 bdirty(bp);
3795 * If no dependencies remain, the pagedep will be freed.
3796 * Otherwise it will remain to update the page before it
3797 * is written back to disk.
3799 if (LIST_FIRST(&pagedep->pd_pendinghd) == NULL) {
3800 for (i = 0; i < DAHASHSZ; i++)
3801 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) != NULL)
3802 break;
3803 if (i == DAHASHSZ) {
3804 LIST_REMOVE(pagedep, pd_hash);
3805 WORKITEM_FREE(pagedep, D_PAGEDEP);
3806 return (0);
3809 return (1);
3813 * Writing back in-core inode structures.
3815 * The filesystem only accesses an inode's contents when it occupies an
3816 * "in-core" inode structure. These "in-core" structures are separate from
3817 * the page frames used to cache inode blocks. Only the latter are
3818 * transferred to/from the disk. So, when the updated contents of the
3819 * "in-core" inode structure are copied to the corresponding in-memory inode
3820 * block, the dependencies are also transferred. The following procedure is
3821 * called when copying a dirty "in-core" inode to a cached inode block.
3825 * Called when an inode is loaded from disk. If the effective link count
3826 * differed from the actual link count when it was last flushed, then we
3827 * need to ensure that the correct effective link count is put back.
3829 * Parameters:
3830 * ip: the "in_core" copy of the inode
3832 void
3833 softdep_load_inodeblock(struct inode *ip)
3835 struct inodedep *inodedep;
3838 * Check for alternate nlink count.
3840 ip->i_effnlink = ip->i_nlink;
3841 ACQUIRE_LOCK(&lk);
3842 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3843 FREE_LOCK(&lk);
3844 return;
3846 ip->i_effnlink -= inodedep->id_nlinkdelta;
3847 FREE_LOCK(&lk);
3851 * This routine is called just before the "in-core" inode
3852 * information is to be copied to the in-memory inode block.
3853 * Recall that an inode block contains several inodes. If
3854 * the force flag is set, then the dependencies will be
3855 * cleared so that the update can always be made. Note that
3856 * the buffer is locked when this routine is called, so we
3857 * will never be in the middle of writing the inode block
3858 * to disk.
3860 * Parameters:
3861 * ip: the "in_core" copy of the inode
3862 * bp: the buffer containing the inode block
3863 * waitfor: nonzero => update must be allowed
3865 void
3866 softdep_update_inodeblock(struct inode *ip, struct buf *bp,
3867 int waitfor)
3869 struct inodedep *inodedep;
3870 struct worklist *wk;
3871 struct buf *ibp;
3872 int error, gotit;
3875 * If the effective link count is not equal to the actual link
3876 * count, then we must track the difference in an inodedep while
3877 * the inode is (potentially) tossed out of the cache. Otherwise,
3878 * if there is no existing inodedep, then there are no dependencies
3879 * to track.
3881 ACQUIRE_LOCK(&lk);
3882 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3883 FREE_LOCK(&lk);
3884 if (ip->i_effnlink != ip->i_nlink)
3885 panic("softdep_update_inodeblock: bad link count");
3886 return;
3888 if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink) {
3889 panic("softdep_update_inodeblock: bad delta");
3892 * Changes have been initiated. Anything depending on these
3893 * changes cannot occur until this inode has been written.
3895 inodedep->id_state &= ~COMPLETE;
3896 if ((inodedep->id_state & ONWORKLIST) == 0)
3897 WORKLIST_INSERT_BP(bp, &inodedep->id_list);
3899 * Any new dependencies associated with the incore inode must
3900 * now be moved to the list associated with the buffer holding
3901 * the in-memory copy of the inode. Once merged process any
3902 * allocdirects that are completed by the merger.
3904 merge_inode_lists(inodedep);
3905 if (TAILQ_FIRST(&inodedep->id_inoupdt) != NULL)
3906 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt));
3908 * Now that the inode has been pushed into the buffer, the
3909 * operations dependent on the inode being written to disk
3910 * can be moved to the id_bufwait so that they will be
3911 * processed when the buffer I/O completes.
3913 while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
3914 WORKLIST_REMOVE(wk);
3915 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
3918 * Newly allocated inodes cannot be written until the bitmap
3919 * that allocates them have been written (indicated by
3920 * DEPCOMPLETE being set in id_state). If we are doing a
3921 * forced sync (e.g., an fsync on a file), we force the bitmap
3922 * to be written so that the update can be done.
3924 if (waitfor == 0) {
3925 FREE_LOCK(&lk);
3926 return;
3928 retry:
3929 if ((inodedep->id_state & DEPCOMPLETE) != 0) {
3930 FREE_LOCK(&lk);
3931 return;
3933 gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
3934 if (gotit == 0) {
3935 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) != 0)
3936 goto retry;
3937 FREE_LOCK(&lk);
3938 return;
3940 ibp = inodedep->id_buf;
3941 FREE_LOCK(&lk);
3942 if ((error = bwrite(ibp)) != 0)
3943 softdep_error("softdep_update_inodeblock: bwrite", error);
3947 * Merge the new inode dependency list (id_newinoupdt) into the old
3948 * inode dependency list (id_inoupdt). This routine must be called
3949 * with splbio interrupts blocked.
3951 static void
3952 merge_inode_lists(struct inodedep *inodedep)
3954 struct allocdirect *listadp, *newadp;
3956 newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3957 for (listadp = TAILQ_FIRST(&inodedep->id_inoupdt); listadp && newadp;) {
3958 if (listadp->ad_lbn < newadp->ad_lbn) {
3959 listadp = TAILQ_NEXT(listadp, ad_next);
3960 continue;
3962 TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3963 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
3964 if (listadp->ad_lbn == newadp->ad_lbn) {
3965 allocdirect_merge(&inodedep->id_inoupdt, newadp,
3966 listadp);
3967 listadp = newadp;
3969 newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3971 while ((newadp = TAILQ_FIRST(&inodedep->id_newinoupdt)) != NULL) {
3972 TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3973 TAILQ_INSERT_TAIL(&inodedep->id_inoupdt, newadp, ad_next);
3978 * If we are doing an fsync, then we must ensure that any directory
3979 * entries for the inode have been written after the inode gets to disk.
3981 * bioops callback - hold io_token
3983 * Parameters:
3984 * vp: the "in_core" copy of the inode
3986 static int
3987 softdep_fsync(struct vnode *vp)
3989 struct inodedep *inodedep;
3990 struct pagedep *pagedep;
3991 struct worklist *wk;
3992 struct diradd *dap;
3993 struct mount *mnt;
3994 struct vnode *pvp;
3995 struct inode *ip;
3996 struct buf *bp;
3997 struct fs *fs;
3998 int error, flushparent;
3999 ino_t parentino;
4000 ufs_lbn_t lbn;
4003 * Move check from original kernel code, possibly not needed any
4004 * more with the per-mount bioops.
4006 if ((vp->v_mount->mnt_flag & MNT_SOFTDEP) == 0)
4007 return (0);
4009 ip = VTOI(vp);
4010 fs = ip->i_fs;
4011 ACQUIRE_LOCK(&lk);
4012 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0) {
4013 FREE_LOCK(&lk);
4014 return (0);
4016 if (LIST_FIRST(&inodedep->id_inowait) != NULL ||
4017 LIST_FIRST(&inodedep->id_bufwait) != NULL ||
4018 TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
4019 TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL) {
4020 panic("softdep_fsync: pending ops");
4022 for (error = 0, flushparent = 0; ; ) {
4023 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
4024 break;
4025 if (wk->wk_type != D_DIRADD) {
4026 panic("softdep_fsync: Unexpected type %s",
4027 TYPENAME(wk->wk_type));
4029 dap = WK_DIRADD(wk);
4031 * Flush our parent if this directory entry
4032 * has a MKDIR_PARENT dependency.
4034 if (dap->da_state & DIRCHG)
4035 pagedep = dap->da_previous->dm_pagedep;
4036 else
4037 pagedep = dap->da_pagedep;
4038 mnt = pagedep->pd_mnt;
4039 parentino = pagedep->pd_ino;
4040 lbn = pagedep->pd_lbn;
4041 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE) {
4042 panic("softdep_fsync: dirty");
4044 flushparent = dap->da_state & MKDIR_PARENT;
4046 * If we are being fsync'ed as part of vgone'ing this vnode,
4047 * then we will not be able to release and recover the
4048 * vnode below, so we just have to give up on writing its
4049 * directory entry out. It will eventually be written, just
4050 * not now, but then the user was not asking to have it
4051 * written, so we are not breaking any promises.
4053 if (vp->v_flag & VRECLAIMED)
4054 break;
4056 * We prevent deadlock by always fetching inodes from the
4057 * root, moving down the directory tree. Thus, when fetching
4058 * our parent directory, we must unlock ourselves before
4059 * requesting the lock on our parent. See the comment in
4060 * ufs_lookup for details on possible races.
4062 FREE_LOCK(&lk);
4063 vn_unlock(vp);
4064 error = VFS_VGET(mnt, NULL, parentino, &pvp);
4065 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4066 if (error != 0) {
4067 return (error);
4069 if (flushparent) {
4070 if ((error = ffs_update(pvp, 1)) != 0) {
4071 vput(pvp);
4072 return (error);
4076 * Flush directory page containing the inode's name.
4078 error = bread(pvp, lblktodoff(fs, lbn), blksize(fs, VTOI(pvp), lbn), &bp);
4079 if (error == 0)
4080 error = bwrite(bp);
4081 vput(pvp);
4082 if (error != 0) {
4083 return (error);
4085 ACQUIRE_LOCK(&lk);
4086 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0)
4087 break;
4089 FREE_LOCK(&lk);
4090 return (0);
4094 * Flush all the dirty bitmaps associated with the block device
4095 * before flushing the rest of the dirty blocks so as to reduce
4096 * the number of dependencies that will have to be rolled back.
4098 static int softdep_fsync_mountdev_bp(struct buf *bp, void *data);
4100 void
4101 softdep_fsync_mountdev(struct vnode *vp)
4103 if (!vn_isdisk(vp, NULL))
4104 panic("softdep_fsync_mountdev: vnode not a disk");
4105 ACQUIRE_LOCK(&lk);
4106 lwkt_gettoken(&vp->v_token);
4107 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
4108 softdep_fsync_mountdev_bp, vp);
4109 lwkt_reltoken(&vp->v_token);
4110 drain_output(vp, 1);
4111 FREE_LOCK(&lk);
4114 static int
4115 softdep_fsync_mountdev_bp(struct buf *bp, void *data)
4117 struct worklist *wk;
4118 struct vnode *vp = data;
4121 * If it is already scheduled, skip to the next buffer.
4123 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT))
4124 return(0);
4125 if (bp->b_vp != vp || (bp->b_flags & B_DELWRI) == 0) {
4126 BUF_UNLOCK(bp);
4127 kprintf("softdep_fsync_mountdev_bp: warning, buffer %p ripped out from under vnode %p\n", bp, vp);
4128 return(0);
4131 * We are only interested in bitmaps with outstanding
4132 * dependencies.
4134 if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
4135 wk->wk_type != D_BMSAFEMAP) {
4136 BUF_UNLOCK(bp);
4137 return(0);
4139 bremfree(bp);
4140 FREE_LOCK(&lk);
4141 (void) bawrite(bp);
4142 ACQUIRE_LOCK(&lk);
4143 return(0);
4147 * This routine is called when we are trying to synchronously flush a
4148 * file. This routine must eliminate any filesystem metadata dependencies
4149 * so that the syncing routine can succeed by pushing the dirty blocks
4150 * associated with the file. If any I/O errors occur, they are returned.
4152 struct softdep_sync_metadata_info {
4153 struct vnode *vp;
4154 int waitfor;
4157 static int softdep_sync_metadata_bp(struct buf *bp, void *data);
4160 softdep_sync_metadata(struct vnode *vp, struct thread *td)
4162 struct softdep_sync_metadata_info info;
4163 int error, waitfor;
4166 * Check whether this vnode is involved in a filesystem
4167 * that is doing soft dependency processing.
4169 if (!vn_isdisk(vp, NULL)) {
4170 if (!DOINGSOFTDEP(vp))
4171 return (0);
4172 } else
4173 if (vp->v_rdev->si_mountpoint == NULL ||
4174 (vp->v_rdev->si_mountpoint->mnt_flag & MNT_SOFTDEP) == 0)
4175 return (0);
4177 * Ensure that any direct block dependencies have been cleared.
4179 ACQUIRE_LOCK(&lk);
4180 if ((error = flush_inodedep_deps(VTOI(vp)->i_fs, VTOI(vp)->i_number))) {
4181 FREE_LOCK(&lk);
4182 return (error);
4185 * For most files, the only metadata dependencies are the
4186 * cylinder group maps that allocate their inode or blocks.
4187 * The block allocation dependencies can be found by traversing
4188 * the dependency lists for any buffers that remain on their
4189 * dirty buffer list. The inode allocation dependency will
4190 * be resolved when the inode is updated with MNT_WAIT.
4191 * This work is done in two passes. The first pass grabs most
4192 * of the buffers and begins asynchronously writing them. The
4193 * only way to wait for these asynchronous writes is to sleep
4194 * on the filesystem vnode which may stay busy for a long time
4195 * if the filesystem is active. So, instead, we make a second
4196 * pass over the dependencies blocking on each write. In the
4197 * usual case we will be blocking against a write that we
4198 * initiated, so when it is done the dependency will have been
4199 * resolved. Thus the second pass is expected to end quickly.
4201 waitfor = MNT_NOWAIT;
4202 top:
4204 * We must wait for any I/O in progress to finish so that
4205 * all potential buffers on the dirty list will be visible.
4207 drain_output(vp, 1);
4209 info.vp = vp;
4210 info.waitfor = waitfor;
4211 lwkt_gettoken(&vp->v_token);
4212 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
4213 softdep_sync_metadata_bp, &info);
4214 lwkt_reltoken(&vp->v_token);
4215 if (error < 0) {
4216 FREE_LOCK(&lk);
4217 return(-error); /* error code */
4221 * The brief unlock is to allow any pent up dependency
4222 * processing to be done. Then proceed with the second pass.
4224 if (waitfor & MNT_NOWAIT) {
4225 waitfor = MNT_WAIT;
4226 FREE_LOCK(&lk);
4227 ACQUIRE_LOCK(&lk);
4228 goto top;
4232 * If we have managed to get rid of all the dirty buffers,
4233 * then we are done. For certain directories and block
4234 * devices, we may need to do further work.
4236 * We must wait for any I/O in progress to finish so that
4237 * all potential buffers on the dirty list will be visible.
4239 drain_output(vp, 1);
4240 if (RB_EMPTY(&vp->v_rbdirty_tree)) {
4241 FREE_LOCK(&lk);
4242 return (0);
4245 FREE_LOCK(&lk);
4247 * If we are trying to sync a block device, some of its buffers may
4248 * contain metadata that cannot be written until the contents of some
4249 * partially written files have been written to disk. The only easy
4250 * way to accomplish this is to sync the entire filesystem (luckily
4251 * this happens rarely).
4253 if (vn_isdisk(vp, NULL) &&
4254 vp->v_rdev &&
4255 vp->v_rdev->si_mountpoint && !vn_islocked(vp) &&
4256 (error = VFS_SYNC(vp->v_rdev->si_mountpoint, MNT_WAIT)) != 0)
4257 return (error);
4258 return (0);
4261 static int
4262 softdep_sync_metadata_bp(struct buf *bp, void *data)
4264 struct softdep_sync_metadata_info *info = data;
4265 struct pagedep *pagedep;
4266 struct allocdirect *adp;
4267 struct allocindir *aip;
4268 struct worklist *wk;
4269 struct buf *nbp;
4270 int error;
4271 int i;
4273 if (getdirtybuf(&bp, MNT_WAIT) == 0) {
4274 kprintf("softdep_sync_metadata_bp(1): caught buf %p going away\n", bp);
4275 return (1);
4277 if (bp->b_vp != info->vp || (bp->b_flags & B_DELWRI) == 0) {
4278 kprintf("softdep_sync_metadata_bp(2): caught buf %p going away vp %p\n", bp, info->vp);
4279 BUF_UNLOCK(bp);
4280 return(1);
4284 * As we hold the buffer locked, none of its dependencies
4285 * will disappear.
4287 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4288 switch (wk->wk_type) {
4290 case D_ALLOCDIRECT:
4291 adp = WK_ALLOCDIRECT(wk);
4292 if (adp->ad_state & DEPCOMPLETE)
4293 break;
4294 nbp = adp->ad_buf;
4295 if (getdirtybuf(&nbp, info->waitfor) == 0)
4296 break;
4297 FREE_LOCK(&lk);
4298 if (info->waitfor & MNT_NOWAIT) {
4299 bawrite(nbp);
4300 } else if ((error = bwrite(nbp)) != 0) {
4301 bawrite(bp);
4302 ACQUIRE_LOCK(&lk);
4303 return (-error);
4305 ACQUIRE_LOCK(&lk);
4306 break;
4308 case D_ALLOCINDIR:
4309 aip = WK_ALLOCINDIR(wk);
4310 if (aip->ai_state & DEPCOMPLETE)
4311 break;
4312 nbp = aip->ai_buf;
4313 if (getdirtybuf(&nbp, info->waitfor) == 0)
4314 break;
4315 FREE_LOCK(&lk);
4316 if (info->waitfor & MNT_NOWAIT) {
4317 bawrite(nbp);
4318 } else if ((error = bwrite(nbp)) != 0) {
4319 bawrite(bp);
4320 ACQUIRE_LOCK(&lk);
4321 return (-error);
4323 ACQUIRE_LOCK(&lk);
4324 break;
4326 case D_INDIRDEP:
4327 restart:
4329 LIST_FOREACH(aip, &WK_INDIRDEP(wk)->ir_deplisthd, ai_next) {
4330 if (aip->ai_state & DEPCOMPLETE)
4331 continue;
4332 nbp = aip->ai_buf;
4333 if (getdirtybuf(&nbp, MNT_WAIT) == 0)
4334 goto restart;
4335 FREE_LOCK(&lk);
4336 if ((error = bwrite(nbp)) != 0) {
4337 bawrite(bp);
4338 ACQUIRE_LOCK(&lk);
4339 return (-error);
4341 ACQUIRE_LOCK(&lk);
4342 goto restart;
4344 break;
4346 case D_INODEDEP:
4347 if ((error = flush_inodedep_deps(WK_INODEDEP(wk)->id_fs,
4348 WK_INODEDEP(wk)->id_ino)) != 0) {
4349 FREE_LOCK(&lk);
4350 bawrite(bp);
4351 ACQUIRE_LOCK(&lk);
4352 return (-error);
4354 break;
4356 case D_PAGEDEP:
4358 * We are trying to sync a directory that may
4359 * have dependencies on both its own metadata
4360 * and/or dependencies on the inodes of any
4361 * recently allocated files. We walk its diradd
4362 * lists pushing out the associated inode.
4364 pagedep = WK_PAGEDEP(wk);
4365 for (i = 0; i < DAHASHSZ; i++) {
4366 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL)
4367 continue;
4368 if ((error =
4369 flush_pagedep_deps(info->vp,
4370 pagedep->pd_mnt,
4371 &pagedep->pd_diraddhd[i]))) {
4372 FREE_LOCK(&lk);
4373 bawrite(bp);
4374 ACQUIRE_LOCK(&lk);
4375 return (-error);
4378 break;
4380 case D_MKDIR:
4382 * This case should never happen if the vnode has
4383 * been properly sync'ed. However, if this function
4384 * is used at a place where the vnode has not yet
4385 * been sync'ed, this dependency can show up. So,
4386 * rather than panic, just flush it.
4388 nbp = WK_MKDIR(wk)->md_buf;
4389 if (getdirtybuf(&nbp, info->waitfor) == 0)
4390 break;
4391 FREE_LOCK(&lk);
4392 if (info->waitfor & MNT_NOWAIT) {
4393 bawrite(nbp);
4394 } else if ((error = bwrite(nbp)) != 0) {
4395 bawrite(bp);
4396 ACQUIRE_LOCK(&lk);
4397 return (-error);
4399 ACQUIRE_LOCK(&lk);
4400 break;
4402 case D_BMSAFEMAP:
4404 * This case should never happen if the vnode has
4405 * been properly sync'ed. However, if this function
4406 * is used at a place where the vnode has not yet
4407 * been sync'ed, this dependency can show up. So,
4408 * rather than panic, just flush it.
4410 * nbp can wind up == bp if a device node for the
4411 * same filesystem is being fsynced at the same time,
4412 * leading to a panic if we don't catch the case.
4414 nbp = WK_BMSAFEMAP(wk)->sm_buf;
4415 if (nbp == bp)
4416 break;
4417 if (getdirtybuf(&nbp, info->waitfor) == 0)
4418 break;
4419 FREE_LOCK(&lk);
4420 if (info->waitfor & MNT_NOWAIT) {
4421 bawrite(nbp);
4422 } else if ((error = bwrite(nbp)) != 0) {
4423 bawrite(bp);
4424 ACQUIRE_LOCK(&lk);
4425 return (-error);
4427 ACQUIRE_LOCK(&lk);
4428 break;
4430 default:
4431 panic("softdep_sync_metadata: Unknown type %s",
4432 TYPENAME(wk->wk_type));
4433 /* NOTREACHED */
4436 FREE_LOCK(&lk);
4437 bawrite(bp);
4438 ACQUIRE_LOCK(&lk);
4439 return(0);
4443 * Flush the dependencies associated with an inodedep.
4444 * Called with splbio blocked.
4446 static int
4447 flush_inodedep_deps(struct fs *fs, ino_t ino)
4449 struct inodedep *inodedep;
4450 struct allocdirect *adp;
4451 int error, waitfor;
4452 struct buf *bp;
4455 * This work is done in two passes. The first pass grabs most
4456 * of the buffers and begins asynchronously writing them. The
4457 * only way to wait for these asynchronous writes is to sleep
4458 * on the filesystem vnode which may stay busy for a long time
4459 * if the filesystem is active. So, instead, we make a second
4460 * pass over the dependencies blocking on each write. In the
4461 * usual case we will be blocking against a write that we
4462 * initiated, so when it is done the dependency will have been
4463 * resolved. Thus the second pass is expected to end quickly.
4464 * We give a brief window at the top of the loop to allow
4465 * any pending I/O to complete.
4467 for (waitfor = MNT_NOWAIT; ; ) {
4468 FREE_LOCK(&lk);
4469 ACQUIRE_LOCK(&lk);
4470 if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4471 return (0);
4472 TAILQ_FOREACH(adp, &inodedep->id_inoupdt, ad_next) {
4473 if (adp->ad_state & DEPCOMPLETE)
4474 continue;
4475 bp = adp->ad_buf;
4476 if (getdirtybuf(&bp, waitfor) == 0) {
4477 if (waitfor & MNT_NOWAIT)
4478 continue;
4479 break;
4481 FREE_LOCK(&lk);
4482 if (waitfor & MNT_NOWAIT) {
4483 bawrite(bp);
4484 } else if ((error = bwrite(bp)) != 0) {
4485 ACQUIRE_LOCK(&lk);
4486 return (error);
4488 ACQUIRE_LOCK(&lk);
4489 break;
4491 if (adp != NULL)
4492 continue;
4493 TAILQ_FOREACH(adp, &inodedep->id_newinoupdt, ad_next) {
4494 if (adp->ad_state & DEPCOMPLETE)
4495 continue;
4496 bp = adp->ad_buf;
4497 if (getdirtybuf(&bp, waitfor) == 0) {
4498 if (waitfor & MNT_NOWAIT)
4499 continue;
4500 break;
4502 FREE_LOCK(&lk);
4503 if (waitfor & MNT_NOWAIT) {
4504 bawrite(bp);
4505 } else if ((error = bwrite(bp)) != 0) {
4506 ACQUIRE_LOCK(&lk);
4507 return (error);
4509 ACQUIRE_LOCK(&lk);
4510 break;
4512 if (adp != NULL)
4513 continue;
4515 * If pass2, we are done, otherwise do pass 2.
4517 if (waitfor == MNT_WAIT)
4518 break;
4519 waitfor = MNT_WAIT;
4522 * Try freeing inodedep in case all dependencies have been removed.
4524 if (inodedep_lookup(fs, ino, 0, &inodedep) != 0)
4525 (void) free_inodedep(inodedep);
4526 return (0);
4530 * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
4531 * Called with splbio blocked.
4533 static int
4534 flush_pagedep_deps(struct vnode *pvp, struct mount *mp,
4535 struct diraddhd *diraddhdp)
4537 struct inodedep *inodedep;
4538 struct ufsmount *ump;
4539 struct diradd *dap;
4540 struct worklist *wk;
4541 struct vnode *vp;
4542 int gotit, error = 0;
4543 struct buf *bp;
4544 ino_t inum;
4546 ump = VFSTOUFS(mp);
4547 while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
4549 * Flush ourselves if this directory entry
4550 * has a MKDIR_PARENT dependency.
4552 if (dap->da_state & MKDIR_PARENT) {
4553 FREE_LOCK(&lk);
4554 if ((error = ffs_update(pvp, 1)) != 0)
4555 break;
4556 ACQUIRE_LOCK(&lk);
4558 * If that cleared dependencies, go on to next.
4560 if (dap != LIST_FIRST(diraddhdp))
4561 continue;
4562 if (dap->da_state & MKDIR_PARENT) {
4563 panic("flush_pagedep_deps: MKDIR_PARENT");
4567 * A newly allocated directory must have its "." and
4568 * ".." entries written out before its name can be
4569 * committed in its parent. We do not want or need
4570 * the full semantics of a synchronous VOP_FSYNC as
4571 * that may end up here again, once for each directory
4572 * level in the filesystem. Instead, we push the blocks
4573 * and wait for them to clear. We have to fsync twice
4574 * because the first call may choose to defer blocks
4575 * that still have dependencies, but deferral will
4576 * happen at most once.
4578 inum = dap->da_newinum;
4579 if (dap->da_state & MKDIR_BODY) {
4580 FREE_LOCK(&lk);
4581 if ((error = VFS_VGET(mp, NULL, inum, &vp)) != 0)
4582 break;
4583 if ((error=VOP_FSYNC(vp, MNT_NOWAIT, 0)) ||
4584 (error=VOP_FSYNC(vp, MNT_NOWAIT, 0))) {
4585 vput(vp);
4586 break;
4588 drain_output(vp, 0);
4590 * If first block is still dirty with a D_MKDIR
4591 * dependency then it needs to be written now.
4593 error = 0;
4594 ACQUIRE_LOCK(&lk);
4595 bp = findblk(vp, 0, FINDBLK_TEST);
4596 if (bp == NULL) {
4597 FREE_LOCK(&lk);
4598 goto mkdir_body_continue;
4600 LIST_FOREACH(wk, &bp->b_dep, wk_list)
4601 if (wk->wk_type == D_MKDIR) {
4602 gotit = getdirtybuf(&bp, MNT_WAIT);
4603 FREE_LOCK(&lk);
4604 if (gotit && (error = bwrite(bp)) != 0)
4605 goto mkdir_body_continue;
4606 break;
4608 if (wk == NULL)
4609 FREE_LOCK(&lk);
4610 mkdir_body_continue:
4611 vput(vp);
4612 /* Flushing of first block failed. */
4613 if (error)
4614 break;
4615 ACQUIRE_LOCK(&lk);
4617 * If that cleared dependencies, go on to next.
4619 if (dap != LIST_FIRST(diraddhdp))
4620 continue;
4621 if (dap->da_state & MKDIR_BODY) {
4622 panic("flush_pagedep_deps: %p MKDIR_BODY", dap);
4626 * Flush the inode on which the directory entry depends.
4627 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
4628 * the only remaining dependency is that the updated inode
4629 * count must get pushed to disk. The inode has already
4630 * been pushed into its inode buffer (via VOP_UPDATE) at
4631 * the time of the reference count change. So we need only
4632 * locate that buffer, ensure that there will be no rollback
4633 * caused by a bitmap dependency, then write the inode buffer.
4635 retry_lookup:
4636 if (inodedep_lookup(ump->um_fs, inum, 0, &inodedep) == 0) {
4637 panic("flush_pagedep_deps: lost inode");
4640 * If the inode still has bitmap dependencies,
4641 * push them to disk.
4643 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4644 gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
4645 if (gotit == 0)
4646 goto retry_lookup;
4647 FREE_LOCK(&lk);
4648 if (gotit && (error = bwrite(inodedep->id_buf)) != 0)
4649 break;
4650 ACQUIRE_LOCK(&lk);
4651 if (dap != LIST_FIRST(diraddhdp))
4652 continue;
4655 * If the inode is still sitting in a buffer waiting
4656 * to be written, push it to disk.
4658 FREE_LOCK(&lk);
4659 if ((error = bread(ump->um_devvp,
4660 fsbtodoff(ump->um_fs, ino_to_fsba(ump->um_fs, inum)),
4661 (int)ump->um_fs->fs_bsize, &bp)) != 0)
4662 break;
4663 if ((error = bwrite(bp)) != 0)
4664 break;
4665 ACQUIRE_LOCK(&lk);
4667 * If we have failed to get rid of all the dependencies
4668 * then something is seriously wrong.
4670 if (dap == LIST_FIRST(diraddhdp)) {
4671 panic("flush_pagedep_deps: flush failed");
4674 if (error)
4675 ACQUIRE_LOCK(&lk);
4676 return (error);
4680 * A large burst of file addition or deletion activity can drive the
4681 * memory load excessively high. First attempt to slow things down
4682 * using the techniques below. If that fails, this routine requests
4683 * the offending operations to fall back to running synchronously
4684 * until the memory load returns to a reasonable level.
4687 softdep_slowdown(struct vnode *vp)
4689 int max_softdeps_hard;
4691 max_softdeps_hard = max_softdeps * 11 / 10;
4692 if (num_dirrem < max_softdeps_hard / 2 &&
4693 num_inodedep < max_softdeps_hard)
4694 return (0);
4695 stat_sync_limit_hit += 1;
4696 return (1);
4700 * If memory utilization has gotten too high, deliberately slow things
4701 * down and speed up the I/O processing.
4703 static int
4704 request_cleanup(int resource)
4706 struct thread *td = curthread; /* XXX */
4708 KKASSERT(lock_held(&lk) > 0);
4711 * We never hold up the filesystem syncer process.
4713 if (td == filesys_syncer)
4714 return (0);
4716 * First check to see if the work list has gotten backlogged.
4717 * If it has, co-opt this process to help clean up two entries.
4718 * Because this process may hold inodes locked, we cannot
4719 * handle any remove requests that might block on a locked
4720 * inode as that could lead to deadlock.
4722 if (num_on_worklist > max_softdeps / 10) {
4723 process_worklist_item(NULL, LK_NOWAIT);
4724 process_worklist_item(NULL, LK_NOWAIT);
4725 stat_worklist_push += 2;
4726 return(1);
4730 * If we are resource constrained on inode dependencies, try
4731 * flushing some dirty inodes. Otherwise, we are constrained
4732 * by file deletions, so try accelerating flushes of directories
4733 * with removal dependencies. We would like to do the cleanup
4734 * here, but we probably hold an inode locked at this point and
4735 * that might deadlock against one that we try to clean. So,
4736 * the best that we can do is request the syncer daemon to do
4737 * the cleanup for us.
4739 switch (resource) {
4741 case FLUSH_INODES:
4742 stat_ino_limit_push += 1;
4743 req_clear_inodedeps += 1;
4744 stat_countp = &stat_ino_limit_hit;
4745 break;
4747 case FLUSH_REMOVE:
4748 stat_blk_limit_push += 1;
4749 req_clear_remove += 1;
4750 stat_countp = &stat_blk_limit_hit;
4751 break;
4753 default:
4754 panic("request_cleanup: unknown type");
4757 * Hopefully the syncer daemon will catch up and awaken us.
4758 * We wait at most tickdelay before proceeding in any case.
4760 lksleep(&proc_waiting, &lk, 0, "softupdate",
4761 tickdelay > 2 ? tickdelay : 2);
4762 return (1);
4766 * Flush out a directory with at least one removal dependency in an effort to
4767 * reduce the number of dirrem, freefile, and freeblks dependency structures.
4769 static void
4770 clear_remove(struct thread *td)
4772 struct pagedep_hashhead *pagedephd;
4773 struct pagedep *pagedep;
4774 static int next = 0;
4775 struct mount *mp;
4776 struct vnode *vp;
4777 int error, cnt;
4778 ino_t ino;
4780 ACQUIRE_LOCK(&lk);
4781 for (cnt = 0; cnt < pagedep_hash; cnt++) {
4782 pagedephd = &pagedep_hashtbl[next++];
4783 if (next >= pagedep_hash)
4784 next = 0;
4785 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
4786 if (LIST_FIRST(&pagedep->pd_dirremhd) == NULL)
4787 continue;
4788 mp = pagedep->pd_mnt;
4789 ino = pagedep->pd_ino;
4790 FREE_LOCK(&lk);
4791 if ((error = VFS_VGET(mp, NULL, ino, &vp)) != 0) {
4792 softdep_error("clear_remove: vget", error);
4793 return;
4795 if ((error = VOP_FSYNC(vp, MNT_NOWAIT, 0)))
4796 softdep_error("clear_remove: fsync", error);
4797 drain_output(vp, 0);
4798 vput(vp);
4799 return;
4802 FREE_LOCK(&lk);
4806 * Clear out a block of dirty inodes in an effort to reduce
4807 * the number of inodedep dependency structures.
4809 struct clear_inodedeps_info {
4810 struct fs *fs;
4811 struct mount *mp;
4814 static int
4815 clear_inodedeps_mountlist_callback(struct mount *mp, void *data)
4817 struct clear_inodedeps_info *info = data;
4819 if ((mp->mnt_flag & MNT_SOFTDEP) && info->fs == VFSTOUFS(mp)->um_fs) {
4820 info->mp = mp;
4821 return(-1);
4823 return(0);
4826 static void
4827 clear_inodedeps(struct thread *td)
4829 struct clear_inodedeps_info info;
4830 struct inodedep_hashhead *inodedephd;
4831 struct inodedep *inodedep;
4832 static int next = 0;
4833 struct vnode *vp;
4834 struct fs *fs;
4835 int error, cnt;
4836 ino_t firstino, lastino, ino;
4838 ACQUIRE_LOCK(&lk);
4840 * Pick a random inode dependency to be cleared.
4841 * We will then gather up all the inodes in its block
4842 * that have dependencies and flush them out.
4844 inodedep = NULL; /* avoid gcc warnings */
4845 for (cnt = 0; cnt < inodedep_hash; cnt++) {
4846 inodedephd = &inodedep_hashtbl[next++];
4847 if (next >= inodedep_hash)
4848 next = 0;
4849 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
4850 break;
4852 if (inodedep == NULL) {
4853 FREE_LOCK(&lk);
4854 return;
4857 * Ugly code to find mount point given pointer to superblock.
4859 fs = inodedep->id_fs;
4860 info.mp = NULL;
4861 info.fs = fs;
4862 mountlist_scan(clear_inodedeps_mountlist_callback,
4863 &info, MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
4865 * Find the last inode in the block with dependencies.
4867 firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
4868 for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
4869 if (inodedep_lookup(fs, lastino, 0, &inodedep) != 0)
4870 break;
4872 * Asynchronously push all but the last inode with dependencies.
4873 * Synchronously push the last inode with dependencies to ensure
4874 * that the inode block gets written to free up the inodedeps.
4876 for (ino = firstino; ino <= lastino; ino++) {
4877 if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4878 continue;
4879 FREE_LOCK(&lk);
4880 if ((error = VFS_VGET(info.mp, NULL, ino, &vp)) != 0) {
4881 softdep_error("clear_inodedeps: vget", error);
4882 return;
4884 if (ino == lastino) {
4885 if ((error = VOP_FSYNC(vp, MNT_WAIT, 0)))
4886 softdep_error("clear_inodedeps: fsync1", error);
4887 } else {
4888 if ((error = VOP_FSYNC(vp, MNT_NOWAIT, 0)))
4889 softdep_error("clear_inodedeps: fsync2", error);
4890 drain_output(vp, 0);
4892 vput(vp);
4893 ACQUIRE_LOCK(&lk);
4895 FREE_LOCK(&lk);
4899 * Function to determine if the buffer has outstanding dependencies
4900 * that will cause a roll-back if the buffer is written. If wantcount
4901 * is set, return number of dependencies, otherwise just yes or no.
4903 * bioops callback - hold io_token
4905 static int
4906 softdep_count_dependencies(struct buf *bp, int wantcount)
4908 struct worklist *wk;
4909 struct inodedep *inodedep;
4910 struct indirdep *indirdep;
4911 struct allocindir *aip;
4912 struct pagedep *pagedep;
4913 struct diradd *dap;
4914 int i, retval;
4916 retval = 0;
4917 ACQUIRE_LOCK(&lk);
4919 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4920 switch (wk->wk_type) {
4922 case D_INODEDEP:
4923 inodedep = WK_INODEDEP(wk);
4924 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4925 /* bitmap allocation dependency */
4926 retval += 1;
4927 if (!wantcount)
4928 goto out;
4930 if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
4931 /* direct block pointer dependency */
4932 retval += 1;
4933 if (!wantcount)
4934 goto out;
4936 continue;
4938 case D_INDIRDEP:
4939 indirdep = WK_INDIRDEP(wk);
4941 LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
4942 /* indirect block pointer dependency */
4943 retval += 1;
4944 if (!wantcount)
4945 goto out;
4947 continue;
4949 case D_PAGEDEP:
4950 pagedep = WK_PAGEDEP(wk);
4951 for (i = 0; i < DAHASHSZ; i++) {
4953 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
4954 /* directory entry dependency */
4955 retval += 1;
4956 if (!wantcount)
4957 goto out;
4960 continue;
4962 case D_BMSAFEMAP:
4963 case D_ALLOCDIRECT:
4964 case D_ALLOCINDIR:
4965 case D_MKDIR:
4966 /* never a dependency on these blocks */
4967 continue;
4969 default:
4970 panic("softdep_check_for_rollback: Unexpected type %s",
4971 TYPENAME(wk->wk_type));
4972 /* NOTREACHED */
4975 out:
4976 FREE_LOCK(&lk);
4978 return retval;
4982 * Acquire exclusive access to a buffer. Requires softdep lock
4983 * to be held on entry. If waitfor is MNT_WAIT, may release/reacquire
4984 * softdep lock.
4986 * Returns 1 if the buffer was locked, 0 if it was not locked or
4987 * if we had to block.
4989 * NOTE! In order to return 1 we must acquire the buffer lock prior
4990 * to any release of &lk. Once we release &lk it's all over.
4991 * We may still have to block on the (type-stable) bp in that
4992 * case, but we must then unlock it and return 0.
4994 static int
4995 getdirtybuf(struct buf **bpp, int waitfor)
4997 struct buf *bp;
4998 int error;
5001 * If the contents of *bpp is NULL the caller presumably lost a race.
5003 bp = *bpp;
5004 if (bp == NULL)
5005 return (0);
5008 * Try to obtain the buffer lock without deadlocking on &lk.
5010 KKASSERT(lock_held(&lk) > 0);
5011 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT);
5012 if (error == 0) {
5014 * If the buffer is no longer dirty the OS already wrote it
5015 * out, return failure.
5017 if ((bp->b_flags & B_DELWRI) == 0) {
5018 BUF_UNLOCK(bp);
5019 return (0);
5023 * Finish nominal buffer locking sequence return success.
5025 bremfree(bp);
5026 return (1);
5030 * Failure case.
5032 * If we are not being asked to wait, return 0 immediately.
5034 if (waitfor != MNT_WAIT)
5035 return (0);
5038 * Once we release the softdep lock we can never return success,
5039 * but we still have to block on the type-stable buf for the caller
5040 * to be able to retry without livelocking the system.
5042 * The caller will normally retry in this case.
5044 FREE_LOCK(&lk);
5045 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL);
5046 ACQUIRE_LOCK(&lk);
5047 if (error == 0)
5048 BUF_UNLOCK(bp);
5049 return (0);
5053 * Wait for pending output on a vnode to complete.
5054 * Must be called with vnode locked.
5056 static void
5057 drain_output(struct vnode *vp, int islocked)
5060 if (!islocked)
5061 ACQUIRE_LOCK(&lk);
5062 while (bio_track_active(&vp->v_track_write)) {
5063 FREE_LOCK(&lk);
5064 bio_track_wait(&vp->v_track_write, 0, 0);
5065 ACQUIRE_LOCK(&lk);
5067 if (!islocked)
5068 FREE_LOCK(&lk);
5072 * Called whenever a buffer that is being invalidated or reallocated
5073 * contains dependencies. This should only happen if an I/O error has
5074 * occurred. The routine is called with the buffer locked.
5076 * bioops callback - hold io_token
5078 static void
5079 softdep_deallocate_dependencies(struct buf *bp)
5081 /* nothing to do, mp lock not needed */
5082 if ((bp->b_flags & B_ERROR) == 0)
5083 panic("softdep_deallocate_dependencies: dangling deps");
5084 softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntfromname, bp->b_error);
5085 panic("softdep_deallocate_dependencies: unrecovered I/O error");
5089 * Function to handle asynchronous write errors in the filesystem.
5091 void
5092 softdep_error(char *func, int error)
5094 /* XXX should do something better! */
5095 kprintf("%s: got error %d while accessing filesystem\n", func, error);