xref: /freebsd-13-stable/sys/ufs/ffs/ffs_softdep.c (revision 6a356edd4fc3c8d7959fcc6a2447c7193d830392)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright 1998, 2000 Marshall Kirk McKusick.
5  * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
6  * All rights reserved.
7  *
8  * The soft updates code is derived from the appendix of a University
9  * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
10  * "Soft Updates: A Solution to the Metadata Update Problem in File
11  * Systems", CSE-TR-254-95, August 1995).
12  *
13  * Further information about soft updates can be obtained from:
14  *
15  *	Marshall Kirk McKusick		http://www.mckusick.com/softdep/
16  *	1614 Oxford Street		mckusick@mckusick.com
17  *	Berkeley, CA 94709-1608		+1-510-843-9542
18  *	USA
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  *
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
35  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
36  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
37  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
38  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
39  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  *	from: @(#)ffs_softdep.c	9.59 (McKusick) 6/21/00
42  */
43 
44 #include <sys/cdefs.h>
45 #include "opt_ffs.h"
46 #include "opt_quota.h"
47 #include "opt_ddb.h"
48 
49 #include <sys/param.h>
50 #include <sys/kernel.h>
51 #include <sys/systm.h>
52 #include <sys/bio.h>
53 #include <sys/buf.h>
54 #include <sys/kdb.h>
55 #include <sys/kthread.h>
56 #include <sys/ktr.h>
57 #include <sys/limits.h>
58 #include <sys/lock.h>
59 #include <sys/malloc.h>
60 #include <sys/mount.h>
61 #include <sys/mutex.h>
62 #include <sys/namei.h>
63 #include <sys/priv.h>
64 #include <sys/proc.h>
65 #include <sys/racct.h>
66 #include <sys/rwlock.h>
67 #include <sys/stat.h>
68 #include <sys/sysctl.h>
69 #include <sys/syslog.h>
70 #include <sys/vnode.h>
71 #include <sys/conf.h>
72 
73 #include <ufs/ufs/dir.h>
74 #include <ufs/ufs/extattr.h>
75 #include <ufs/ufs/quota.h>
76 #include <ufs/ufs/inode.h>
77 #include <ufs/ufs/ufsmount.h>
78 #include <ufs/ffs/fs.h>
79 #include <ufs/ffs/softdep.h>
80 #include <ufs/ffs/ffs_extern.h>
81 #include <ufs/ufs/ufs_extern.h>
82 
83 #include <vm/vm.h>
84 #include <vm/vm_extern.h>
85 #include <vm/vm_object.h>
86 
87 #include <geom/geom.h>
88 #include <geom/geom_vfs.h>
89 
90 #include <ddb/ddb.h>
91 
92 #define	KTR_SUJ	0	/* Define to KTR_SPARE. */
93 
94 #ifndef SOFTUPDATES
95 
96 int
softdep_flushfiles(struct mount * oldmnt,int flags,struct thread * td)97 softdep_flushfiles(struct mount *oldmnt,
98 	int flags,
99 	struct thread *td)
100 {
101 
102 	panic("softdep_flushfiles called");
103 }
104 
105 int
softdep_mount(struct vnode * devvp,struct mount * mp,struct fs * fs,struct ucred * cred)106 softdep_mount(struct vnode *devvp,
107 	struct mount *mp,
108 	struct fs *fs,
109 	struct ucred *cred)
110 {
111 
112 	return (0);
113 }
114 
115 void
softdep_initialize(void)116 softdep_initialize(void)
117 {
118 
119 	return;
120 }
121 
122 void
softdep_uninitialize(void)123 softdep_uninitialize(void)
124 {
125 
126 	return;
127 }
128 
129 void
softdep_unmount(struct mount * mp)130 softdep_unmount(struct mount *mp)
131 {
132 
133 	panic("softdep_unmount called");
134 }
135 
136 void
softdep_setup_sbupdate(struct ufsmount * ump,struct fs * fs,struct buf * bp)137 softdep_setup_sbupdate(struct ufsmount *ump,
138 	struct fs *fs,
139 	struct buf *bp)
140 {
141 
142 	panic("softdep_setup_sbupdate called");
143 }
144 
145 void
softdep_setup_inomapdep(struct buf * bp,struct inode * ip,ino_t newinum,int mode)146 softdep_setup_inomapdep(struct buf *bp,
147 	struct inode *ip,
148 	ino_t newinum,
149 	int mode)
150 {
151 
152 	panic("softdep_setup_inomapdep called");
153 }
154 
155 void
softdep_setup_blkmapdep(struct buf * bp,struct mount * mp,ufs2_daddr_t newblkno,int frags,int oldfrags)156 softdep_setup_blkmapdep(struct buf *bp,
157 	struct mount *mp,
158 	ufs2_daddr_t newblkno,
159 	int frags,
160 	int oldfrags)
161 {
162 
163 	panic("softdep_setup_blkmapdep called");
164 }
165 
166 void
softdep_setup_allocdirect(struct inode * ip,ufs_lbn_t lbn,ufs2_daddr_t newblkno,ufs2_daddr_t oldblkno,long newsize,long oldsize,struct buf * bp)167 softdep_setup_allocdirect(struct inode *ip,
168 	ufs_lbn_t lbn,
169 	ufs2_daddr_t newblkno,
170 	ufs2_daddr_t oldblkno,
171 	long newsize,
172 	long oldsize,
173 	struct buf *bp)
174 {
175 
176 	panic("softdep_setup_allocdirect called");
177 }
178 
179 void
softdep_setup_allocext(struct inode * ip,ufs_lbn_t lbn,ufs2_daddr_t newblkno,ufs2_daddr_t oldblkno,long newsize,long oldsize,struct buf * bp)180 softdep_setup_allocext(struct inode *ip,
181 	ufs_lbn_t lbn,
182 	ufs2_daddr_t newblkno,
183 	ufs2_daddr_t oldblkno,
184 	long newsize,
185 	long oldsize,
186 	struct buf *bp)
187 {
188 
189 	panic("softdep_setup_allocext called");
190 }
191 
192 void
softdep_setup_allocindir_page(struct inode * ip,ufs_lbn_t lbn,struct buf * bp,int ptrno,ufs2_daddr_t newblkno,ufs2_daddr_t oldblkno,struct buf * nbp)193 softdep_setup_allocindir_page(struct inode *ip,
194 	ufs_lbn_t lbn,
195 	struct buf *bp,
196 	int ptrno,
197 	ufs2_daddr_t newblkno,
198 	ufs2_daddr_t oldblkno,
199 	struct buf *nbp)
200 {
201 
202 	panic("softdep_setup_allocindir_page called");
203 }
204 
205 void
softdep_setup_allocindir_meta(struct buf * nbp,struct inode * ip,struct buf * bp,int ptrno,ufs2_daddr_t newblkno)206 softdep_setup_allocindir_meta(struct buf *nbp,
207 	struct inode *ip,
208 	struct buf *bp,
209 	int ptrno,
210 	ufs2_daddr_t newblkno)
211 {
212 
213 	panic("softdep_setup_allocindir_meta called");
214 }
215 
216 void
softdep_journal_freeblocks(struct inode * ip,struct ucred * cred,off_t length,int flags)217 softdep_journal_freeblocks(struct inode *ip,
218 	struct ucred *cred,
219 	off_t length,
220 	int flags)
221 {
222 
223 	panic("softdep_journal_freeblocks called");
224 }
225 
226 void
softdep_journal_fsync(struct inode * ip)227 softdep_journal_fsync(struct inode *ip)
228 {
229 
230 	panic("softdep_journal_fsync called");
231 }
232 
233 void
softdep_setup_freeblocks(struct inode * ip,off_t length,int flags)234 softdep_setup_freeblocks(struct inode *ip,
235 	off_t length,
236 	int flags)
237 {
238 
239 	panic("softdep_setup_freeblocks called");
240 }
241 
242 void
softdep_freefile(struct vnode * pvp,ino_t ino,int mode)243 softdep_freefile(struct vnode *pvp,
244 		ino_t ino,
245 		int mode)
246 {
247 
248 	panic("softdep_freefile called");
249 }
250 
251 int
softdep_setup_directory_add(struct buf * bp,struct inode * dp,off_t diroffset,ino_t newinum,struct buf * newdirbp,int isnewblk)252 softdep_setup_directory_add(struct buf *bp,
253 	struct inode *dp,
254 	off_t diroffset,
255 	ino_t newinum,
256 	struct buf *newdirbp,
257 	int isnewblk)
258 {
259 
260 	panic("softdep_setup_directory_add called");
261 }
262 
263 void
softdep_change_directoryentry_offset(struct buf * bp,struct inode * dp,caddr_t base,caddr_t oldloc,caddr_t newloc,int entrysize)264 softdep_change_directoryentry_offset(struct buf *bp,
265 	struct inode *dp,
266 	caddr_t base,
267 	caddr_t oldloc,
268 	caddr_t newloc,
269 	int entrysize)
270 {
271 
272 	panic("softdep_change_directoryentry_offset called");
273 }
274 
275 void
softdep_setup_remove(struct buf * bp,struct inode * dp,struct inode * ip,int isrmdir)276 softdep_setup_remove(struct buf *bp,
277 	struct inode *dp,
278 	struct inode *ip,
279 	int isrmdir)
280 {
281 
282 	panic("softdep_setup_remove called");
283 }
284 
285 void
softdep_setup_directory_change(struct buf * bp,struct inode * dp,struct inode * ip,ino_t newinum,int isrmdir)286 softdep_setup_directory_change(struct buf *bp,
287 	struct inode *dp,
288 	struct inode *ip,
289 	ino_t newinum,
290 	int isrmdir)
291 {
292 
293 	panic("softdep_setup_directory_change called");
294 }
295 
296 void
softdep_setup_blkfree(struct mount * mp,struct buf * bp,ufs2_daddr_t blkno,int frags,struct workhead * wkhd,bool doingrecovery)297 softdep_setup_blkfree(struct mount *mp,
298 	struct buf *bp,
299 	ufs2_daddr_t blkno,
300 	int frags,
301 	struct workhead *wkhd,
302 	bool doingrecovery)
303 {
304 
305 	panic("%s called", __FUNCTION__);
306 }
307 
308 void
softdep_setup_inofree(struct mount * mp,struct buf * bp,ino_t ino,struct workhead * wkhd,bool doingrecovery)309 softdep_setup_inofree(struct mount *mp,
310 	struct buf *bp,
311 	ino_t ino,
312 	struct workhead *wkhd,
313 	bool doingrecovery)
314 {
315 
316 	panic("%s called", __FUNCTION__);
317 }
318 
319 void
softdep_setup_unlink(struct inode * dp,struct inode * ip)320 softdep_setup_unlink(struct inode *dp, struct inode *ip)
321 {
322 
323 	panic("%s called", __FUNCTION__);
324 }
325 
326 void
softdep_setup_link(struct inode * dp,struct inode * ip)327 softdep_setup_link(struct inode *dp, struct inode *ip)
328 {
329 
330 	panic("%s called", __FUNCTION__);
331 }
332 
333 void
softdep_revert_link(struct inode * dp,struct inode * ip)334 softdep_revert_link(struct inode *dp, struct inode *ip)
335 {
336 
337 	panic("%s called", __FUNCTION__);
338 }
339 
340 void
softdep_setup_rmdir(struct inode * dp,struct inode * ip)341 softdep_setup_rmdir(struct inode *dp, struct inode *ip)
342 {
343 
344 	panic("%s called", __FUNCTION__);
345 }
346 
347 void
softdep_revert_rmdir(struct inode * dp,struct inode * ip)348 softdep_revert_rmdir(struct inode *dp, struct inode *ip)
349 {
350 
351 	panic("%s called", __FUNCTION__);
352 }
353 
354 void
softdep_setup_create(struct inode * dp,struct inode * ip)355 softdep_setup_create(struct inode *dp, struct inode *ip)
356 {
357 
358 	panic("%s called", __FUNCTION__);
359 }
360 
361 void
softdep_revert_create(struct inode * dp,struct inode * ip)362 softdep_revert_create(struct inode *dp, struct inode *ip)
363 {
364 
365 	panic("%s called", __FUNCTION__);
366 }
367 
368 void
softdep_setup_mkdir(struct inode * dp,struct inode * ip)369 softdep_setup_mkdir(struct inode *dp, struct inode *ip)
370 {
371 
372 	panic("%s called", __FUNCTION__);
373 }
374 
375 void
softdep_revert_mkdir(struct inode * dp,struct inode * ip)376 softdep_revert_mkdir(struct inode *dp, struct inode *ip)
377 {
378 
379 	panic("%s called", __FUNCTION__);
380 }
381 
382 void
softdep_setup_dotdot_link(struct inode * dp,struct inode * ip)383 softdep_setup_dotdot_link(struct inode *dp, struct inode *ip)
384 {
385 
386 	panic("%s called", __FUNCTION__);
387 }
388 
389 int
softdep_prealloc(struct vnode * vp,int waitok)390 softdep_prealloc(struct vnode *vp, int waitok)
391 {
392 
393 	panic("%s called", __FUNCTION__);
394 }
395 
396 int
softdep_journal_lookup(struct mount * mp,struct vnode ** vpp)397 softdep_journal_lookup(struct mount *mp, struct vnode **vpp)
398 {
399 
400 	return (ENOENT);
401 }
402 
403 void
softdep_change_linkcnt(struct inode * ip)404 softdep_change_linkcnt(struct inode *ip)
405 {
406 
407 	panic("softdep_change_linkcnt called");
408 }
409 
410 void
softdep_load_inodeblock(struct inode * ip)411 softdep_load_inodeblock(struct inode *ip)
412 {
413 
414 	panic("softdep_load_inodeblock called");
415 }
416 
417 void
softdep_update_inodeblock(struct inode * ip,struct buf * bp,int waitfor)418 softdep_update_inodeblock(struct inode *ip,
419 	struct buf *bp,
420 	int waitfor)
421 {
422 
423 	panic("softdep_update_inodeblock called");
424 }
425 
426 int
softdep_fsync(struct vnode * vp)427 softdep_fsync(struct vnode *vp)	/* the "in_core" copy of the inode */
428 {
429 
430 	return (0);
431 }
432 
433 void
softdep_fsync_mountdev(struct vnode * vp)434 softdep_fsync_mountdev(struct vnode *vp)
435 {
436 
437 	return;
438 }
439 
440 int
softdep_flushworklist(struct mount * oldmnt,int * countp,struct thread * td)441 softdep_flushworklist(struct mount *oldmnt,
442 	int *countp,
443 	struct thread *td)
444 {
445 
446 	*countp = 0;
447 	return (0);
448 }
449 
450 int
softdep_sync_metadata(struct vnode * vp)451 softdep_sync_metadata(struct vnode *vp)
452 {
453 
454 	panic("softdep_sync_metadata called");
455 }
456 
457 int
softdep_sync_buf(struct vnode * vp,struct buf * bp,int waitfor)458 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
459 {
460 
461 	panic("softdep_sync_buf called");
462 }
463 
464 int
softdep_slowdown(struct vnode * vp)465 softdep_slowdown(struct vnode *vp)
466 {
467 
468 	panic("softdep_slowdown called");
469 }
470 
471 int
softdep_request_cleanup(struct fs * fs,struct vnode * vp,struct ucred * cred,int resource)472 softdep_request_cleanup(struct fs *fs,
473 	struct vnode *vp,
474 	struct ucred *cred,
475 	int resource)
476 {
477 
478 	return (0);
479 }
480 
481 int
softdep_check_suspend(struct mount * mp,struct vnode * devvp,int softdep_depcnt,int softdep_accdepcnt,int secondary_writes,int secondary_accwrites)482 softdep_check_suspend(struct mount *mp,
483 		      struct vnode *devvp,
484 		      int softdep_depcnt,
485 		      int softdep_accdepcnt,
486 		      int secondary_writes,
487 		      int secondary_accwrites)
488 {
489 	struct bufobj *bo;
490 	int error;
491 
492 	(void) softdep_depcnt,
493 	(void) softdep_accdepcnt;
494 
495 	bo = &devvp->v_bufobj;
496 	ASSERT_BO_WLOCKED(bo);
497 
498 	MNT_ILOCK(mp);
499 	while (mp->mnt_secondary_writes != 0) {
500 		BO_UNLOCK(bo);
501 		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
502 		    (PUSER - 1) | PDROP, "secwr", 0);
503 		BO_LOCK(bo);
504 		MNT_ILOCK(mp);
505 	}
506 
507 	/*
508 	 * Reasons for needing more work before suspend:
509 	 * - Dirty buffers on devvp.
510 	 * - Secondary writes occurred after start of vnode sync loop
511 	 */
512 	error = 0;
513 	if (bo->bo_numoutput > 0 ||
514 	    bo->bo_dirty.bv_cnt > 0 ||
515 	    secondary_writes != 0 ||
516 	    mp->mnt_secondary_writes != 0 ||
517 	    secondary_accwrites != mp->mnt_secondary_accwrites)
518 		error = EAGAIN;
519 	BO_UNLOCK(bo);
520 	return (error);
521 }
522 
523 void
softdep_get_depcounts(struct mount * mp,int * softdepactivep,int * softdepactiveaccp)524 softdep_get_depcounts(struct mount *mp,
525 		      int *softdepactivep,
526 		      int *softdepactiveaccp)
527 {
528 	(void) mp;
529 	*softdepactivep = 0;
530 	*softdepactiveaccp = 0;
531 }
532 
533 void
softdep_buf_append(struct buf * bp,struct workhead * wkhd)534 softdep_buf_append(struct buf *bp, struct workhead *wkhd)
535 {
536 
537 	panic("softdep_buf_appendwork called");
538 }
539 
540 void
softdep_inode_append(struct inode * ip,struct ucred * cred,struct workhead * wkhd)541 softdep_inode_append(struct inode *ip,
542 	struct ucred *cred,
543 	struct workhead *wkhd)
544 {
545 
546 	panic("softdep_inode_appendwork called");
547 }
548 
549 void
softdep_freework(struct workhead * wkhd)550 softdep_freework(struct workhead *wkhd)
551 {
552 
553 	panic("softdep_freework called");
554 }
555 
556 int
softdep_prerename(struct vnode * fdvp,struct vnode * fvp,struct vnode * tdvp,struct vnode * tvp)557 softdep_prerename(struct vnode *fdvp,
558 	struct vnode *fvp,
559 	struct vnode *tdvp,
560 	struct vnode *tvp)
561 {
562 
563 	panic("softdep_prerename called");
564 }
565 
566 int
softdep_prelink(struct vnode * dvp,struct vnode * vp,struct componentname * cnp)567 softdep_prelink(struct vnode *dvp,
568 	struct vnode *vp,
569 	struct componentname *cnp)
570 {
571 
572 	panic("softdep_prelink called");
573 }
574 
575 #else
576 
577 FEATURE(softupdates, "FFS soft-updates support");
578 
579 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
580     "soft updates stats");
581 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total,
582     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
583     "total dependencies allocated");
584 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse,
585     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
586     "high use dependencies allocated");
587 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current,
588     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
589     "current dependencies allocated");
590 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write,
591     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
592     "current dependencies written");
593 
594 unsigned long dep_current[D_LAST + 1];
595 unsigned long dep_highuse[D_LAST + 1];
596 unsigned long dep_total[D_LAST + 1];
597 unsigned long dep_write[D_LAST + 1];
598 
599 #define	SOFTDEP_TYPE(type, str, long)					\
600     static MALLOC_DEFINE(M_ ## type, #str, long);			\
601     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
602 	&dep_total[D_ ## type], 0, "");					\
603     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
604 	&dep_current[D_ ## type], 0, "");				\
605     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD, 	\
606 	&dep_highuse[D_ ## type], 0, "");				\
607     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
608 	&dep_write[D_ ## type], 0, "");
609 
610 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
611 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
612 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
613     "Block or frag allocated from cyl group map");
614 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
615 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
616 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
617 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
618 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
619 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
620 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
621 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
622 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
623 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
624 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
625 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
626 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
627 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
628 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
629 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
630 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
631 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
632 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
633 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
634 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
635 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
636 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
637 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
638 
639 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
640 
641 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
642 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
643 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
644 
645 #define M_SOFTDEP_FLAGS	(M_WAITOK)
646 
647 /*
648  * translate from workitem type to memory type
649  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
650  */
651 static struct malloc_type *memtype[] = {
652 	NULL,
653 	M_PAGEDEP,
654 	M_INODEDEP,
655 	M_BMSAFEMAP,
656 	M_NEWBLK,
657 	M_ALLOCDIRECT,
658 	M_INDIRDEP,
659 	M_ALLOCINDIR,
660 	M_FREEFRAG,
661 	M_FREEBLKS,
662 	M_FREEFILE,
663 	M_DIRADD,
664 	M_MKDIR,
665 	M_DIRREM,
666 	M_NEWDIRBLK,
667 	M_FREEWORK,
668 	M_FREEDEP,
669 	M_JADDREF,
670 	M_JREMREF,
671 	M_JMVREF,
672 	M_JNEWBLK,
673 	M_JFREEBLK,
674 	M_JFREEFRAG,
675 	M_JSEG,
676 	M_JSEGDEP,
677 	M_SBDEP,
678 	M_JTRUNC,
679 	M_JFSYNC,
680 	M_SENTINEL
681 };
682 
683 #define DtoM(type) (memtype[type])
684 
685 /*
686  * Names of malloc types.
687  */
688 #define TYPENAME(type)  \
689 	((unsigned)(type) <= D_LAST && (unsigned)(type) >= D_FIRST ? \
690 	memtype[type]->ks_shortdesc : "???")
691 /*
692  * End system adaptation definitions.
693  */
694 
695 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
696 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
697 
698 /*
699  * Internal function prototypes.
700  */
701 static	void check_clear_deps(struct mount *);
702 static	void softdep_error(char *, int);
703 static	int softdep_prerename_vnode(struct ufsmount *, struct vnode *);
704 static	int softdep_process_worklist(struct mount *, int);
705 static	int softdep_waitidle(struct mount *, int);
706 static	void drain_output(struct vnode *);
707 static	struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
708 static	int check_inodedep_free(struct inodedep *);
709 static	void clear_remove(struct mount *);
710 static	void clear_inodedeps(struct mount *);
711 static	void unlinked_inodedep(struct mount *, struct inodedep *);
712 static	void clear_unlinked_inodedep(struct inodedep *);
713 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
714 static	int flush_pagedep_deps(struct vnode *, struct mount *,
715 	    struct diraddhd *, struct buf *);
716 static	int free_pagedep(struct pagedep *);
717 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
718 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
719 static	int flush_deplist(struct allocdirectlst *, int, int *);
720 static	int sync_cgs(struct mount *, int);
721 static	int handle_written_filepage(struct pagedep *, struct buf *, int);
722 static	int handle_written_sbdep(struct sbdep *, struct buf *);
723 static	void initiate_write_sbdep(struct sbdep *);
724 static	void diradd_inode_written(struct diradd *, struct inodedep *);
725 static	int handle_written_indirdep(struct indirdep *, struct buf *,
726 	    struct buf**, int);
727 static	int handle_written_inodeblock(struct inodedep *, struct buf *, int);
728 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
729 	    uint8_t *);
730 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
731 static	void handle_written_jaddref(struct jaddref *);
732 static	void handle_written_jremref(struct jremref *);
733 static	void handle_written_jseg(struct jseg *, struct buf *);
734 static	void handle_written_jnewblk(struct jnewblk *);
735 static	void handle_written_jblkdep(struct jblkdep *);
736 static	void handle_written_jfreefrag(struct jfreefrag *);
737 static	void complete_jseg(struct jseg *);
738 static	void complete_jsegs(struct jseg *);
739 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
740 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
741 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
742 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
743 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
744 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
745 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
746 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
747 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
748 static	inline void inoref_write(struct inoref *, struct jseg *,
749 	    struct jrefrec *);
750 static	void handle_allocdirect_partdone(struct allocdirect *,
751 	    struct workhead *);
752 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
753 	    struct workhead *);
754 static	void indirdep_complete(struct indirdep *);
755 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
756 static	void indirblk_insert(struct freework *);
757 static	void indirblk_remove(struct freework *);
758 static	void handle_allocindir_partdone(struct allocindir *);
759 static	void initiate_write_filepage(struct pagedep *, struct buf *);
760 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
761 static	void handle_written_mkdir(struct mkdir *, int);
762 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
763 	    uint8_t *);
764 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
765 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
766 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
767 static	void handle_workitem_freefile(struct freefile *);
768 static	int handle_workitem_remove(struct dirrem *, int);
769 static	struct dirrem *newdirrem(struct buf *, struct inode *,
770 	    struct inode *, int, struct dirrem **);
771 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
772 	    struct buf *);
773 static	void cancel_indirdep(struct indirdep *, struct buf *,
774 	    struct freeblks *);
775 static	void free_indirdep(struct indirdep *);
776 static	void free_diradd(struct diradd *, struct workhead *);
777 static	void merge_diradd(struct inodedep *, struct diradd *);
778 static	void complete_diradd(struct diradd *);
779 static	struct diradd *diradd_lookup(struct pagedep *, int);
780 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
781 	    struct jremref *);
782 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
783 	    struct jremref *);
784 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
785 	    struct jremref *, struct jremref *);
786 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
787 	    struct jremref *);
788 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
789 	    struct freeblks *, int);
790 static	int setup_trunc_indir(struct freeblks *, struct inode *,
791 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
792 static	void complete_trunc_indir(struct freework *);
793 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
794 	    int);
795 static	void complete_mkdir(struct mkdir *);
796 static	void free_newdirblk(struct newdirblk *);
797 static	void free_jremref(struct jremref *);
798 static	void free_jaddref(struct jaddref *);
799 static	void free_jsegdep(struct jsegdep *);
800 static	void free_jsegs(struct jblocks *);
801 static	void rele_jseg(struct jseg *);
802 static	void free_jseg(struct jseg *, struct jblocks *);
803 static	void free_jnewblk(struct jnewblk *);
804 static	void free_jblkdep(struct jblkdep *);
805 static	void free_jfreefrag(struct jfreefrag *);
806 static	void free_freedep(struct freedep *);
807 static	void journal_jremref(struct dirrem *, struct jremref *,
808 	    struct inodedep *);
809 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
810 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
811 	    struct workhead *);
812 static	void cancel_jfreefrag(struct jfreefrag *);
813 static	inline void setup_freedirect(struct freeblks *, struct inode *,
814 	    int, int);
815 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
816 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
817 	    ufs_lbn_t, int);
818 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
819 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
820 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
821 static	ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
822 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
823 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
824 	    int, int);
825 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
826 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
827 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
828 static	void newblk_freefrag(struct newblk*);
829 static	void free_newblk(struct newblk *);
830 static	void cancel_allocdirect(struct allocdirectlst *,
831 	    struct allocdirect *, struct freeblks *);
832 static	int check_inode_unwritten(struct inodedep *);
833 static	int free_inodedep(struct inodedep *);
834 static	void freework_freeblock(struct freework *, uint64_t);
835 static	void freework_enqueue(struct freework *);
836 static	int handle_workitem_freeblocks(struct freeblks *, int);
837 static	int handle_complete_freeblocks(struct freeblks *, int);
838 static	void handle_workitem_indirblk(struct freework *);
839 static	void handle_written_freework(struct freework *);
840 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
841 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
842 	    struct workhead *);
843 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
844 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
845 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
846 	    ufs2_daddr_t, ufs_lbn_t);
847 static	void handle_workitem_freefrag(struct freefrag *);
848 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
849 	    ufs_lbn_t, uint64_t);
850 static	void allocdirect_merge(struct allocdirectlst *,
851 	    struct allocdirect *, struct allocdirect *);
852 static	struct freefrag *allocindir_merge(struct allocindir *,
853 	    struct allocindir *);
854 static	int bmsafemap_find(struct bmsafemap_hashhead *, int,
855 	    struct bmsafemap **);
856 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
857 	    int cg, struct bmsafemap *);
858 static	int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
859 	    struct newblk **);
860 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
861 static	int inodedep_find(struct inodedep_hashhead *, ino_t,
862 	    struct inodedep **);
863 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
864 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
865 	    int, struct pagedep **);
866 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
867 	    struct pagedep **);
868 static	void pause_timer(void *);
869 static	int request_cleanup(struct mount *, int);
870 static	int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
871 static	void schedule_cleanup(struct mount *);
872 static void softdep_ast_cleanup_proc(struct thread *);
873 static struct ufsmount *softdep_bp_to_mp(struct buf *bp);
874 static	int process_worklist_item(struct mount *, int, int);
875 static	void process_removes(struct vnode *);
876 static	void process_truncates(struct vnode *);
877 static	void jwork_move(struct workhead *, struct workhead *);
878 static	void jwork_insert(struct workhead *, struct jsegdep *);
879 static	void add_to_worklist(struct worklist *, int);
880 static	void wake_worklist(struct worklist *);
881 static	void wait_worklist(struct worklist *, char *);
882 static	void remove_from_worklist(struct worklist *);
883 static	void softdep_flush(void *);
884 static	void softdep_flushjournal(struct mount *);
885 static	int softdep_speedup(struct ufsmount *);
886 static	void worklist_speedup(struct mount *);
887 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
888 static	void journal_unmount(struct ufsmount *);
889 static	int journal_space(struct ufsmount *, int);
890 static	void journal_suspend(struct ufsmount *);
891 static	int journal_unsuspend(struct ufsmount *ump);
892 static	void add_to_journal(struct worklist *);
893 static	void remove_from_journal(struct worklist *);
894 static	bool softdep_excess_items(struct ufsmount *, int);
895 static	void softdep_process_journal(struct mount *, struct worklist *, int);
896 static	struct jremref *newjremref(struct dirrem *, struct inode *,
897 	    struct inode *ip, off_t, nlink_t);
898 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
899 	    uint16_t);
900 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
901 	    uint16_t);
902 static	inline struct jsegdep *inoref_jseg(struct inoref *);
903 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
904 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
905 	    ufs2_daddr_t, int);
906 static	void adjust_newfreework(struct freeblks *, int);
907 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
908 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
909 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
910 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
911 	    ufs2_daddr_t, long, ufs_lbn_t);
912 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
913 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
914 static	int jwait(struct worklist *, int);
915 static	struct inodedep *inodedep_lookup_ip(struct inode *);
916 static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
917 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
918 static	void handle_jwork(struct workhead *);
919 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
920 	    struct mkdir **);
921 static	struct jblocks *jblocks_create(void);
922 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
923 static	void jblocks_free(struct jblocks *, struct mount *, int);
924 static	void jblocks_destroy(struct jblocks *);
925 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
926 
927 /*
928  * Exported softdep operations.
929  */
930 static	void softdep_disk_io_initiation(struct buf *);
931 static	void softdep_disk_write_complete(struct buf *);
932 static	void softdep_deallocate_dependencies(struct buf *);
933 static	int softdep_count_dependencies(struct buf *bp, int);
934 
935 /*
936  * Global lock over all of soft updates.
937  */
938 static struct mtx lk;
939 MTX_SYSINIT(softdep_lock, &lk, "global softdep", MTX_DEF);
940 
941 #define ACQUIRE_GBLLOCK(lk)	mtx_lock(lk)
942 #define FREE_GBLLOCK(lk)	mtx_unlock(lk)
943 #define GBLLOCK_OWNED(lk)	mtx_assert((lk), MA_OWNED)
944 
945 /*
946  * Per-filesystem soft-updates locking.
947  */
948 #define LOCK_PTR(ump)		(&(ump)->um_softdep->sd_fslock)
949 #define TRY_ACQUIRE_LOCK(ump)	rw_try_wlock(&(ump)->um_softdep->sd_fslock)
950 #define ACQUIRE_LOCK(ump)	rw_wlock(&(ump)->um_softdep->sd_fslock)
951 #define FREE_LOCK(ump)		rw_wunlock(&(ump)->um_softdep->sd_fslock)
952 #define LOCK_OWNED(ump)		rw_assert(&(ump)->um_softdep->sd_fslock, \
953 				    RA_WLOCKED)
954 
955 #define	BUF_AREC(bp)		lockallowrecurse(&(bp)->b_lock)
956 #define	BUF_NOREC(bp)		lockdisablerecurse(&(bp)->b_lock)
957 
958 /*
959  * Worklist queue management.
960  * These routines require that the lock be held.
961  */
962 #ifndef /* NOT */ INVARIANTS
963 #define WORKLIST_INSERT(head, item) do {	\
964 	(item)->wk_state |= ONWORKLIST;		\
965 	LIST_INSERT_HEAD(head, item, wk_list);	\
966 } while (0)
967 #define WORKLIST_REMOVE(item) do {		\
968 	(item)->wk_state &= ~ONWORKLIST;	\
969 	LIST_REMOVE(item, wk_list);		\
970 } while (0)
971 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
972 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
973 
974 #else /* INVARIANTS */
975 static	void worklist_insert(struct workhead *, struct worklist *, int,
976 	const char *, int);
977 static	void worklist_remove(struct worklist *, int, const char *, int);
978 
979 #define WORKLIST_INSERT(head, item) \
980 	worklist_insert(head, item, 1, __func__, __LINE__)
981 #define WORKLIST_INSERT_UNLOCKED(head, item)\
982 	worklist_insert(head, item, 0, __func__, __LINE__)
983 #define WORKLIST_REMOVE(item)\
984 	worklist_remove(item, 1, __func__, __LINE__)
985 #define WORKLIST_REMOVE_UNLOCKED(item)\
986 	worklist_remove(item, 0, __func__, __LINE__)
987 
988 static void
worklist_insert(struct workhead * head,struct worklist * item,int locked,const char * func,int line)989 worklist_insert(struct workhead *head,
990 	struct worklist *item,
991 	int locked,
992 	const char *func,
993 	int line)
994 {
995 
996 	if (locked)
997 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
998 	if (item->wk_state & ONWORKLIST)
999 		panic("worklist_insert: %p %s(0x%X) already on list, "
1000 		    "added in function %s at line %d",
1001 		    item, TYPENAME(item->wk_type), item->wk_state,
1002 		    item->wk_func, item->wk_line);
1003 	item->wk_state |= ONWORKLIST;
1004 	item->wk_func = func;
1005 	item->wk_line = line;
1006 	LIST_INSERT_HEAD(head, item, wk_list);
1007 }
1008 
1009 static void
worklist_remove(struct worklist * item,int locked,const char * func,int line)1010 worklist_remove(struct worklist *item,
1011 	int locked,
1012 	const char *func,
1013 	int line)
1014 {
1015 
1016 	if (locked)
1017 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1018 	if ((item->wk_state & ONWORKLIST) == 0)
1019 		panic("worklist_remove: %p %s(0x%X) not on list, "
1020 		    "removed in function %s at line %d",
1021 		    item, TYPENAME(item->wk_type), item->wk_state,
1022 		    item->wk_func, item->wk_line);
1023 	item->wk_state &= ~ONWORKLIST;
1024 	item->wk_func = func;
1025 	item->wk_line = line;
1026 	LIST_REMOVE(item, wk_list);
1027 }
1028 #endif /* INVARIANTS */
1029 
1030 /*
1031  * Merge two jsegdeps keeping only the oldest one as newer references
1032  * can't be discarded until after older references.
1033  */
1034 static inline struct jsegdep *
jsegdep_merge(struct jsegdep * one,struct jsegdep * two)1035 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1036 {
1037 	struct jsegdep *swp;
1038 
1039 	if (two == NULL)
1040 		return (one);
1041 
1042 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1043 		swp = one;
1044 		one = two;
1045 		two = swp;
1046 	}
1047 	WORKLIST_REMOVE(&two->jd_list);
1048 	free_jsegdep(two);
1049 
1050 	return (one);
1051 }
1052 
1053 /*
1054  * If two freedeps are compatible free one to reduce list size.
1055  */
1056 static inline struct freedep *
freedep_merge(struct freedep * one,struct freedep * two)1057 freedep_merge(struct freedep *one, struct freedep *two)
1058 {
1059 	if (two == NULL)
1060 		return (one);
1061 
1062 	if (one->fd_freework == two->fd_freework) {
1063 		WORKLIST_REMOVE(&two->fd_list);
1064 		free_freedep(two);
1065 	}
1066 	return (one);
1067 }
1068 
1069 /*
1070  * Move journal work from one list to another.  Duplicate freedeps and
1071  * jsegdeps are coalesced to keep the lists as small as possible.
1072  */
1073 static void
jwork_move(struct workhead * dst,struct workhead * src)1074 jwork_move(struct workhead *dst, struct workhead *src)
1075 {
1076 	struct freedep *freedep;
1077 	struct jsegdep *jsegdep;
1078 	struct worklist *wkn;
1079 	struct worklist *wk;
1080 
1081 	KASSERT(dst != src,
1082 	    ("jwork_move: dst == src"));
1083 	freedep = NULL;
1084 	jsegdep = NULL;
1085 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1086 		if (wk->wk_type == D_JSEGDEP)
1087 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1088 		else if (wk->wk_type == D_FREEDEP)
1089 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1090 	}
1091 
1092 	while ((wk = LIST_FIRST(src)) != NULL) {
1093 		WORKLIST_REMOVE(wk);
1094 		WORKLIST_INSERT(dst, wk);
1095 		if (wk->wk_type == D_JSEGDEP) {
1096 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1097 			continue;
1098 		}
1099 		if (wk->wk_type == D_FREEDEP)
1100 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1101 	}
1102 }
1103 
1104 static void
jwork_insert(struct workhead * dst,struct jsegdep * jsegdep)1105 jwork_insert(struct workhead *dst, struct jsegdep *jsegdep)
1106 {
1107 	struct jsegdep *jsegdepn;
1108 	struct worklist *wk;
1109 
1110 	LIST_FOREACH(wk, dst, wk_list)
1111 		if (wk->wk_type == D_JSEGDEP)
1112 			break;
1113 	if (wk == NULL) {
1114 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1115 		return;
1116 	}
1117 	jsegdepn = WK_JSEGDEP(wk);
1118 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1119 		WORKLIST_REMOVE(wk);
1120 		free_jsegdep(jsegdepn);
1121 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1122 	} else
1123 		free_jsegdep(jsegdep);
1124 }
1125 
1126 /*
1127  * Routines for tracking and managing workitems.
1128  */
1129 static	void workitem_free(struct worklist *, int);
1130 static	void workitem_alloc(struct worklist *, int, struct mount *);
1131 static	void workitem_reassign(struct worklist *, int);
1132 
1133 #define	WORKITEM_FREE(item, type) \
1134 	workitem_free((struct worklist *)(item), (type))
1135 #define	WORKITEM_REASSIGN(item, type) \
1136 	workitem_reassign((struct worklist *)(item), (type))
1137 
1138 static void
workitem_free(struct worklist * item,int type)1139 workitem_free(struct worklist *item, int type)
1140 {
1141 	struct ufsmount *ump;
1142 
1143 #ifdef INVARIANTS
1144 	if (item->wk_state & ONWORKLIST)
1145 		panic("workitem_free: %s(0x%X) still on list, "
1146 		    "added in function %s at line %d",
1147 		    TYPENAME(item->wk_type), item->wk_state,
1148 		    item->wk_func, item->wk_line);
1149 	if (item->wk_type != type && type != D_NEWBLK)
1150 		panic("workitem_free: type mismatch %s != %s",
1151 		    TYPENAME(item->wk_type), TYPENAME(type));
1152 #endif
1153 	if (item->wk_state & IOWAITING)
1154 		wakeup(item);
1155 	ump = VFSTOUFS(item->wk_mp);
1156 	LOCK_OWNED(ump);
1157 	KASSERT(ump->softdep_deps > 0,
1158 	    ("workitem_free: %s: softdep_deps going negative",
1159 	    ump->um_fs->fs_fsmnt));
1160 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1161 		wakeup(&ump->softdep_deps);
1162 	KASSERT(dep_current[item->wk_type] > 0,
1163 	    ("workitem_free: %s: dep_current[%s] going negative",
1164 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1165 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1166 	    ("workitem_free: %s: softdep_curdeps[%s] going negative",
1167 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1168 	atomic_subtract_long(&dep_current[item->wk_type], 1);
1169 	ump->softdep_curdeps[item->wk_type] -= 1;
1170 	LIST_REMOVE(item, wk_all);
1171 	free(item, DtoM(type));
1172 }
1173 
1174 static void
workitem_alloc(struct worklist * item,int type,struct mount * mp)1175 workitem_alloc(struct worklist *item,
1176 	int type,
1177 	struct mount *mp)
1178 {
1179 	struct ufsmount *ump;
1180 
1181 	item->wk_type = type;
1182 	item->wk_mp = mp;
1183 	item->wk_state = 0;
1184 
1185 	ump = VFSTOUFS(mp);
1186 	ACQUIRE_GBLLOCK(&lk);
1187 	dep_current[type]++;
1188 	if (dep_current[type] > dep_highuse[type])
1189 		dep_highuse[type] = dep_current[type];
1190 	dep_total[type]++;
1191 	FREE_GBLLOCK(&lk);
1192 	ACQUIRE_LOCK(ump);
1193 	ump->softdep_curdeps[type] += 1;
1194 	ump->softdep_deps++;
1195 	ump->softdep_accdeps++;
1196 	LIST_INSERT_HEAD(&ump->softdep_alldeps[type], item, wk_all);
1197 	FREE_LOCK(ump);
1198 }
1199 
1200 static void
workitem_reassign(struct worklist * item,int newtype)1201 workitem_reassign(struct worklist *item, int newtype)
1202 {
1203 	struct ufsmount *ump;
1204 
1205 	ump = VFSTOUFS(item->wk_mp);
1206 	LOCK_OWNED(ump);
1207 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1208 	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1209 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1210 	ump->softdep_curdeps[item->wk_type] -= 1;
1211 	ump->softdep_curdeps[newtype] += 1;
1212 	KASSERT(dep_current[item->wk_type] > 0,
1213 	    ("workitem_reassign: %s: dep_current[%s] going negative",
1214 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1215 	ACQUIRE_GBLLOCK(&lk);
1216 	dep_current[newtype]++;
1217 	dep_current[item->wk_type]--;
1218 	if (dep_current[newtype] > dep_highuse[newtype])
1219 		dep_highuse[newtype] = dep_current[newtype];
1220 	dep_total[newtype]++;
1221 	FREE_GBLLOCK(&lk);
1222 	item->wk_type = newtype;
1223 	LIST_REMOVE(item, wk_all);
1224 	LIST_INSERT_HEAD(&ump->softdep_alldeps[newtype], item, wk_all);
1225 }
1226 
1227 /*
1228  * Workitem queue management
1229  */
1230 static int max_softdeps;	/* maximum number of structs before slowdown */
1231 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1232 static int proc_waiting;	/* tracks whether we have a timeout posted */
1233 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1234 static struct callout softdep_callout;
1235 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1236 static int req_clear_remove;	/* syncer process flush some freeblks */
1237 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1238 
1239 /*
1240  * runtime statistics
1241  */
1242 static int stat_flush_threads;	/* number of softdep flushing threads */
1243 static int stat_worklist_push;	/* number of worklist cleanups */
1244 static int stat_delayed_inact;	/* number of delayed inactivation cleanups */
1245 static int stat_blk_limit_push;	/* number of times block limit neared */
1246 static int stat_ino_limit_push;	/* number of times inode limit neared */
1247 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1248 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1249 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1250 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1251 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1252 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1253 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1254 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1255 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1256 static int stat_journal_min;	/* Times hit journal min threshold */
1257 static int stat_journal_low;	/* Times hit journal low threshold */
1258 static int stat_journal_wait;	/* Times blocked in jwait(). */
1259 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1260 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1261 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1262 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1263 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1264 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1265 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1266 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1267 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1268 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1269 
1270 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1271     &max_softdeps, 0, "");
1272 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1273     &tickdelay, 0, "");
1274 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1275     &stat_flush_threads, 0, "");
1276 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push,
1277     CTLFLAG_RW | CTLFLAG_STATS, &stat_worklist_push, 0,"");
1278 SYSCTL_INT(_debug_softdep, OID_AUTO, delayed_inactivations, CTLFLAG_RD,
1279     &stat_delayed_inact, 0, "");
1280 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push,
1281     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_push, 0,"");
1282 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push,
1283     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_push, 0,"");
1284 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit,
1285     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_hit, 0, "");
1286 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit,
1287     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_hit, 0, "");
1288 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit,
1289     CTLFLAG_RW | CTLFLAG_STATS, &stat_sync_limit_hit, 0, "");
1290 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs,
1291     CTLFLAG_RW | CTLFLAG_STATS, &stat_indir_blk_ptrs, 0, "");
1292 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap,
1293     CTLFLAG_RW | CTLFLAG_STATS, &stat_inode_bitmap, 0, "");
1294 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs,
1295     CTLFLAG_RW | CTLFLAG_STATS, &stat_direct_blk_ptrs, 0, "");
1296 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry,
1297     CTLFLAG_RW | CTLFLAG_STATS, &stat_dir_entry, 0, "");
1298 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback,
1299     CTLFLAG_RW | CTLFLAG_STATS, &stat_jaddref, 0, "");
1300 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback,
1301     CTLFLAG_RW | CTLFLAG_STATS, &stat_jnewblk, 0, "");
1302 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low,
1303     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_low, 0, "");
1304 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min,
1305     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_min, 0, "");
1306 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait,
1307     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_wait, 0, "");
1308 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage,
1309     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_filepage, 0, "");
1310 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks,
1311     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_freeblks, 0, "");
1312 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode,
1313     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_inode, 0, "");
1314 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk,
1315     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_newblk, 0, "");
1316 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests,
1317     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_blkrequests, 0, "");
1318 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests,
1319     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_inorequests, 0, "");
1320 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay,
1321     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_high_delay, 0, "");
1322 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries,
1323     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_retries, 0, "");
1324 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures,
1325     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_failures, 0, "");
1326 
1327 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1328     &softdep_flushcache, 0, "");
1329 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1330     &stat_emptyjblocks, 0, "");
1331 
1332 SYSCTL_DECL(_vfs_ffs);
1333 
1334 /* Whether to recompute the summary at mount time */
1335 static int compute_summary_at_mount = 0;
1336 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1337 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1338 static int print_threads = 0;
1339 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1340     &print_threads, 0, "Notify flusher thread start/stop");
1341 
1342 /* List of all filesystems mounted with soft updates */
1343 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1344 
1345 static void
get_parent_vp_unlock_bp(struct mount * mp,struct buf * bp,struct diraddhd * diraddhdp,struct diraddhd * unfinishedp)1346 get_parent_vp_unlock_bp(struct mount *mp,
1347 	struct buf *bp,
1348 	struct diraddhd *diraddhdp,
1349 	struct diraddhd *unfinishedp)
1350 {
1351 	struct diradd *dap;
1352 
1353 	/*
1354 	 * Requeue unfinished dependencies before
1355 	 * unlocking buffer, which could make
1356 	 * diraddhdp invalid.
1357 	 */
1358 	ACQUIRE_LOCK(VFSTOUFS(mp));
1359 	while ((dap = LIST_FIRST(unfinishedp)) != NULL) {
1360 		LIST_REMOVE(dap, da_pdlist);
1361 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
1362 	}
1363 	FREE_LOCK(VFSTOUFS(mp));
1364 
1365 	bp->b_vflags &= ~BV_SCANNED;
1366 	BUF_NOREC(bp);
1367 	BUF_UNLOCK(bp);
1368 }
1369 
1370 /*
1371  * This function fetches inode inum on mount point mp.  We already
1372  * hold a locked vnode vp, and might have a locked buffer bp belonging
1373  * to vp.
1374 
1375  * We must not block on acquiring the new inode lock as we will get
1376  * into a lock-order reversal with the buffer lock and possibly get a
1377  * deadlock.  Thus if we cannot instantiate the requested vnode
1378  * without sleeping on its lock, we must unlock the vnode and the
1379  * buffer before doing a blocking on the vnode lock.  We return
1380  * ERELOOKUP if we have had to unlock either the vnode or the buffer so
1381  * that the caller can reassess its state.
1382  *
1383  * Top-level VFS code (for syscalls and other consumers, e.g. callers
1384  * of VOP_FSYNC() in syncer) check for ERELOOKUP and restart at safe
1385  * point.
1386  *
1387  * Since callers expect to operate on fully constructed vnode, we also
1388  * recheck v_data after relock, and return ENOENT if NULL.
1389  *
1390  * If unlocking bp, we must unroll dequeueing its unfinished
1391  * dependencies, and clear scan flag, before unlocking.  If unlocking
1392  * vp while it is under deactivation, we re-queue deactivation.
1393  */
1394 static int
get_parent_vp(struct vnode * vp,struct mount * mp,ino_t inum,struct buf * bp,struct diraddhd * diraddhdp,struct diraddhd * unfinishedp,struct vnode ** rvp)1395 get_parent_vp(struct vnode *vp,
1396 	struct mount *mp,
1397 	ino_t inum,
1398 	struct buf *bp,
1399 	struct diraddhd *diraddhdp,
1400 	struct diraddhd *unfinishedp,
1401 	struct vnode **rvp)
1402 {
1403 	struct vnode *pvp;
1404 	int error;
1405 	bool bplocked;
1406 
1407 	ASSERT_VOP_ELOCKED(vp, "child vnode must be locked");
1408 	for (bplocked = true, pvp = NULL;;) {
1409 		error = ffs_vgetf(mp, inum, LK_EXCLUSIVE | LK_NOWAIT, &pvp,
1410 		    FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP);
1411 		if (error == 0) {
1412 			/*
1413 			 * Since we could have unlocked vp, the inode
1414 			 * number could no longer indicate a
1415 			 * constructed node.  In this case, we must
1416 			 * restart the syscall.
1417 			 */
1418 			if (VTOI(pvp)->i_mode == 0 || !bplocked) {
1419 				if (bp != NULL && bplocked)
1420 					get_parent_vp_unlock_bp(mp, bp,
1421 					    diraddhdp, unfinishedp);
1422 				if (VTOI(pvp)->i_mode == 0)
1423 					vgone(pvp);
1424 				error = ERELOOKUP;
1425 				goto out2;
1426 			}
1427 			goto out1;
1428 		}
1429 		if (bp != NULL && bplocked) {
1430 			get_parent_vp_unlock_bp(mp, bp, diraddhdp, unfinishedp);
1431 			bplocked = false;
1432 		}
1433 
1434 		/*
1435 		 * Do not drop vnode lock while inactivating during
1436 		 * vunref.  This would result in leaks of the VI flags
1437 		 * and reclaiming of non-truncated vnode.  Instead,
1438 		 * re-schedule inactivation hoping that we would be
1439 		 * able to sync inode later.
1440 		 */
1441 		if ((vp->v_iflag & VI_DOINGINACT) != 0 &&
1442 		    (vp->v_vflag & VV_UNREF) != 0) {
1443 			VI_LOCK(vp);
1444 			vp->v_iflag |= VI_OWEINACT;
1445 			VI_UNLOCK(vp);
1446 			return (ERELOOKUP);
1447 		}
1448 
1449 		VOP_UNLOCK(vp);
1450 		error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &pvp,
1451 		    FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP);
1452 		if (error != 0) {
1453 			MPASS(error != ERELOOKUP);
1454 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1455 			break;
1456 		}
1457 		if (VTOI(pvp)->i_mode == 0) {
1458 			vgone(pvp);
1459 			vput(pvp);
1460 			pvp = NULL;
1461 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1462 			error = ERELOOKUP;
1463 			break;
1464 		}
1465 		error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
1466 		if (error == 0)
1467 			break;
1468 		vput(pvp);
1469 		pvp = NULL;
1470 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1471 		if (vp->v_data == NULL) {
1472 			error = ENOENT;
1473 			break;
1474 		}
1475 	}
1476 	if (bp != NULL) {
1477 		MPASS(!bplocked);
1478 		error = ERELOOKUP;
1479 	}
1480 out2:
1481 	if (error != 0 && pvp != NULL) {
1482 		vput(pvp);
1483 		pvp = NULL;
1484 	}
1485 out1:
1486 	*rvp = pvp;
1487 	ASSERT_VOP_ELOCKED(vp, "child vnode must be locked on return");
1488 	return (error);
1489 }
1490 
1491 /*
1492  * This function cleans the worklist for a filesystem.
1493  * Each filesystem running with soft dependencies gets its own
1494  * thread to run in this function. The thread is started up in
1495  * softdep_mount and shutdown in softdep_unmount. They show up
1496  * as part of the kernel "bufdaemon" process whose process
1497  * entry is available in bufdaemonproc.
1498  */
1499 static int searchfailed;
1500 extern struct proc *bufdaemonproc;
1501 static void
softdep_flush(void * addr)1502 softdep_flush(void *addr)
1503 {
1504 	struct mount *mp;
1505 	struct thread *td;
1506 	struct ufsmount *ump;
1507 	int cleanups;
1508 
1509 	td = curthread;
1510 	td->td_pflags |= TDP_NORUNNINGBUF;
1511 	mp = (struct mount *)addr;
1512 	ump = VFSTOUFS(mp);
1513 	atomic_add_int(&stat_flush_threads, 1);
1514 	ACQUIRE_LOCK(ump);
1515 	ump->softdep_flags &= ~FLUSH_STARTING;
1516 	wakeup(&ump->softdep_flushtd);
1517 	FREE_LOCK(ump);
1518 	if (print_threads) {
1519 		if (stat_flush_threads == 1)
1520 			printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1521 			    bufdaemonproc->p_pid);
1522 		printf("Start thread %s\n", td->td_name);
1523 	}
1524 	for (;;) {
1525 		while (softdep_process_worklist(mp, 0) > 0 ||
1526 		    (MOUNTEDSUJ(mp) &&
1527 		    VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1528 			kthread_suspend_check();
1529 		ACQUIRE_LOCK(ump);
1530 		if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1531 			msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1532 			    "sdflush", hz / 2);
1533 		ump->softdep_flags &= ~FLUSH_CLEANUP;
1534 		/*
1535 		 * Check to see if we are done and need to exit.
1536 		 */
1537 		if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1538 			FREE_LOCK(ump);
1539 			continue;
1540 		}
1541 		ump->softdep_flags &= ~FLUSH_EXIT;
1542 		cleanups = ump->um_softdep->sd_cleanups;
1543 		FREE_LOCK(ump);
1544 		wakeup(&ump->softdep_flags);
1545 		if (print_threads) {
1546 			printf("Stop thread %s: searchfailed %d, "
1547 			    "did cleanups %d\n",
1548 			    td->td_name, searchfailed, cleanups);
1549 		}
1550 		atomic_subtract_int(&stat_flush_threads, 1);
1551 		kthread_exit();
1552 		panic("kthread_exit failed\n");
1553 	}
1554 }
1555 
1556 static void
worklist_speedup(struct mount * mp)1557 worklist_speedup(struct mount *mp)
1558 {
1559 	struct ufsmount *ump;
1560 
1561 	ump = VFSTOUFS(mp);
1562 	LOCK_OWNED(ump);
1563 	if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1564 		ump->softdep_flags |= FLUSH_CLEANUP;
1565 	wakeup(&ump->softdep_flushtd);
1566 }
1567 
1568 static void
softdep_send_speedup(struct ufsmount * ump,off_t shortage,uint64_t flags)1569 softdep_send_speedup(struct ufsmount *ump,
1570 	off_t shortage,
1571 	uint64_t flags)
1572 {
1573 	struct buf *bp;
1574 
1575 	if ((ump->um_flags & UM_CANSPEEDUP) == 0)
1576 		return;
1577 
1578 	bp = malloc(sizeof(*bp), M_TRIM, M_WAITOK | M_ZERO);
1579 	bp->b_iocmd = BIO_SPEEDUP;
1580 	bp->b_ioflags = flags;
1581 	bp->b_bcount = omin(shortage, LONG_MAX);
1582 	g_vfs_strategy(ump->um_bo, bp);
1583 	bufwait(bp);
1584 	free(bp, M_TRIM);
1585 }
1586 
1587 static int
softdep_speedup(struct ufsmount * ump)1588 softdep_speedup(struct ufsmount *ump)
1589 {
1590 	struct ufsmount *altump;
1591 	struct mount_softdeps *sdp;
1592 
1593 	LOCK_OWNED(ump);
1594 	worklist_speedup(ump->um_mountp);
1595 	bd_speedup();
1596 	/*
1597 	 * If we have global shortages, then we need other
1598 	 * filesystems to help with the cleanup. Here we wakeup a
1599 	 * flusher thread for a filesystem that is over its fair
1600 	 * share of resources.
1601 	 */
1602 	if (req_clear_inodedeps || req_clear_remove) {
1603 		ACQUIRE_GBLLOCK(&lk);
1604 		TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1605 			if ((altump = sdp->sd_ump) == ump)
1606 				continue;
1607 			if (((req_clear_inodedeps &&
1608 			    altump->softdep_curdeps[D_INODEDEP] >
1609 			    max_softdeps / stat_flush_threads) ||
1610 			    (req_clear_remove &&
1611 			    altump->softdep_curdeps[D_DIRREM] >
1612 			    (max_softdeps / 2) / stat_flush_threads)) &&
1613 			    TRY_ACQUIRE_LOCK(altump))
1614 				break;
1615 		}
1616 		if (sdp == NULL) {
1617 			searchfailed++;
1618 			FREE_GBLLOCK(&lk);
1619 		} else {
1620 			/*
1621 			 * Move to the end of the list so we pick a
1622 			 * different one on out next try.
1623 			 */
1624 			TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1625 			TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1626 			FREE_GBLLOCK(&lk);
1627 			if ((altump->softdep_flags &
1628 			    (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1629 				altump->softdep_flags |= FLUSH_CLEANUP;
1630 			altump->um_softdep->sd_cleanups++;
1631 			wakeup(&altump->softdep_flushtd);
1632 			FREE_LOCK(altump);
1633 		}
1634 	}
1635 	return (speedup_syncer());
1636 }
1637 
1638 /*
1639  * Add an item to the end of the work queue.
1640  * This routine requires that the lock be held.
1641  * This is the only routine that adds items to the list.
1642  * The following routine is the only one that removes items
1643  * and does so in order from first to last.
1644  */
1645 
1646 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1647 #define	WK_NODELAY	0x0002	/* Process immediately. */
1648 
1649 static void
add_to_worklist(struct worklist * wk,int flags)1650 add_to_worklist(struct worklist *wk, int flags)
1651 {
1652 	struct ufsmount *ump;
1653 
1654 	ump = VFSTOUFS(wk->wk_mp);
1655 	LOCK_OWNED(ump);
1656 	if (wk->wk_state & ONWORKLIST)
1657 		panic("add_to_worklist: %s(0x%X) already on list",
1658 		    TYPENAME(wk->wk_type), wk->wk_state);
1659 	wk->wk_state |= ONWORKLIST;
1660 	if (ump->softdep_on_worklist == 0) {
1661 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1662 		ump->softdep_worklist_tail = wk;
1663 	} else if (flags & WK_HEAD) {
1664 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1665 	} else {
1666 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1667 		ump->softdep_worklist_tail = wk;
1668 	}
1669 	ump->softdep_on_worklist += 1;
1670 	if (flags & WK_NODELAY)
1671 		worklist_speedup(wk->wk_mp);
1672 }
1673 
1674 /*
1675  * Remove the item to be processed. If we are removing the last
1676  * item on the list, we need to recalculate the tail pointer.
1677  */
1678 static void
remove_from_worklist(struct worklist * wk)1679 remove_from_worklist(struct worklist *wk)
1680 {
1681 	struct ufsmount *ump;
1682 
1683 	ump = VFSTOUFS(wk->wk_mp);
1684 	if (ump->softdep_worklist_tail == wk)
1685 		ump->softdep_worklist_tail =
1686 		    (struct worklist *)wk->wk_list.le_prev;
1687 	WORKLIST_REMOVE(wk);
1688 	ump->softdep_on_worklist -= 1;
1689 }
1690 
1691 static void
wake_worklist(struct worklist * wk)1692 wake_worklist(struct worklist *wk)
1693 {
1694 	if (wk->wk_state & IOWAITING) {
1695 		wk->wk_state &= ~IOWAITING;
1696 		wakeup(wk);
1697 	}
1698 }
1699 
1700 static void
wait_worklist(struct worklist * wk,char * wmesg)1701 wait_worklist(struct worklist *wk, char *wmesg)
1702 {
1703 	struct ufsmount *ump;
1704 
1705 	ump = VFSTOUFS(wk->wk_mp);
1706 	wk->wk_state |= IOWAITING;
1707 	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1708 }
1709 
1710 /*
1711  * Process that runs once per second to handle items in the background queue.
1712  *
1713  * Note that we ensure that everything is done in the order in which they
1714  * appear in the queue. The code below depends on this property to ensure
1715  * that blocks of a file are freed before the inode itself is freed. This
1716  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1717  * until all the old ones have been purged from the dependency lists.
1718  */
1719 static int
softdep_process_worklist(struct mount * mp,int full)1720 softdep_process_worklist(struct mount *mp, int full)
1721 {
1722 	int cnt, matchcnt;
1723 	struct ufsmount *ump;
1724 	long starttime;
1725 
1726 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1727 	ump = VFSTOUFS(mp);
1728 	if (ump->um_softdep == NULL)
1729 		return (0);
1730 	matchcnt = 0;
1731 	ACQUIRE_LOCK(ump);
1732 	starttime = time_second;
1733 	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1734 	check_clear_deps(mp);
1735 	while (ump->softdep_on_worklist > 0) {
1736 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1737 			break;
1738 		else
1739 			matchcnt += cnt;
1740 		check_clear_deps(mp);
1741 		/*
1742 		 * We do not generally want to stop for buffer space, but if
1743 		 * we are really being a buffer hog, we will stop and wait.
1744 		 */
1745 		if (should_yield()) {
1746 			FREE_LOCK(ump);
1747 			kern_yield(PRI_USER);
1748 			bwillwrite();
1749 			ACQUIRE_LOCK(ump);
1750 		}
1751 		/*
1752 		 * Never allow processing to run for more than one
1753 		 * second. This gives the syncer thread the opportunity
1754 		 * to pause if appropriate.
1755 		 */
1756 		if (!full && starttime != time_second)
1757 			break;
1758 	}
1759 	if (full == 0)
1760 		journal_unsuspend(ump);
1761 	FREE_LOCK(ump);
1762 	return (matchcnt);
1763 }
1764 
1765 /*
1766  * Process all removes associated with a vnode if we are running out of
1767  * journal space.  Any other process which attempts to flush these will
1768  * be unable as we have the vnodes locked.
1769  */
1770 static void
process_removes(struct vnode * vp)1771 process_removes(struct vnode *vp)
1772 {
1773 	struct inodedep *inodedep;
1774 	struct dirrem *dirrem;
1775 	struct ufsmount *ump;
1776 	struct mount *mp;
1777 	ino_t inum;
1778 
1779 	mp = vp->v_mount;
1780 	ump = VFSTOUFS(mp);
1781 	LOCK_OWNED(ump);
1782 	inum = VTOI(vp)->i_number;
1783 	for (;;) {
1784 top:
1785 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1786 			return;
1787 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1788 			/*
1789 			 * If another thread is trying to lock this vnode
1790 			 * it will fail but we must wait for it to do so
1791 			 * before we can proceed.
1792 			 */
1793 			if (dirrem->dm_state & INPROGRESS) {
1794 				wait_worklist(&dirrem->dm_list, "pwrwait");
1795 				goto top;
1796 			}
1797 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1798 			    (COMPLETE | ONWORKLIST))
1799 				break;
1800 		}
1801 		if (dirrem == NULL)
1802 			return;
1803 		remove_from_worklist(&dirrem->dm_list);
1804 		FREE_LOCK(ump);
1805 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1806 			panic("process_removes: suspended filesystem");
1807 		handle_workitem_remove(dirrem, 0);
1808 		vn_finished_secondary_write(mp);
1809 		ACQUIRE_LOCK(ump);
1810 	}
1811 }
1812 
1813 /*
1814  * Process all truncations associated with a vnode if we are running out
1815  * of journal space.  This is called when the vnode lock is already held
1816  * and no other process can clear the truncation.  This function returns
1817  * a value greater than zero if it did any work.
1818  */
1819 static void
process_truncates(struct vnode * vp)1820 process_truncates(struct vnode *vp)
1821 {
1822 	struct inodedep *inodedep;
1823 	struct freeblks *freeblks;
1824 	struct ufsmount *ump;
1825 	struct mount *mp;
1826 	ino_t inum;
1827 	int cgwait;
1828 
1829 	mp = vp->v_mount;
1830 	ump = VFSTOUFS(mp);
1831 	LOCK_OWNED(ump);
1832 	inum = VTOI(vp)->i_number;
1833 	for (;;) {
1834 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1835 			return;
1836 		cgwait = 0;
1837 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1838 			/* Journal entries not yet written.  */
1839 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1840 				jwait(&LIST_FIRST(
1841 				    &freeblks->fb_jblkdephd)->jb_list,
1842 				    MNT_WAIT);
1843 				break;
1844 			}
1845 			/* Another thread is executing this item. */
1846 			if (freeblks->fb_state & INPROGRESS) {
1847 				wait_worklist(&freeblks->fb_list, "ptrwait");
1848 				break;
1849 			}
1850 			/* Freeblks is waiting on a inode write. */
1851 			if ((freeblks->fb_state & COMPLETE) == 0) {
1852 				FREE_LOCK(ump);
1853 				ffs_update(vp, 1);
1854 				ACQUIRE_LOCK(ump);
1855 				break;
1856 			}
1857 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1858 			    (ALLCOMPLETE | ONWORKLIST)) {
1859 				remove_from_worklist(&freeblks->fb_list);
1860 				freeblks->fb_state |= INPROGRESS;
1861 				FREE_LOCK(ump);
1862 				if (vn_start_secondary_write(NULL, &mp,
1863 				    V_NOWAIT))
1864 					panic("process_truncates: "
1865 					    "suspended filesystem");
1866 				handle_workitem_freeblocks(freeblks, 0);
1867 				vn_finished_secondary_write(mp);
1868 				ACQUIRE_LOCK(ump);
1869 				break;
1870 			}
1871 			if (freeblks->fb_cgwait)
1872 				cgwait++;
1873 		}
1874 		if (cgwait) {
1875 			FREE_LOCK(ump);
1876 			sync_cgs(mp, MNT_WAIT);
1877 			ffs_sync_snap(mp, MNT_WAIT);
1878 			ACQUIRE_LOCK(ump);
1879 			continue;
1880 		}
1881 		if (freeblks == NULL)
1882 			break;
1883 	}
1884 	return;
1885 }
1886 
1887 /*
1888  * Process one item on the worklist.
1889  */
1890 static int
process_worklist_item(struct mount * mp,int target,int flags)1891 process_worklist_item(struct mount *mp,
1892 	int target,
1893 	int flags)
1894 {
1895 	struct worklist sentinel;
1896 	struct worklist *wk;
1897 	struct ufsmount *ump;
1898 	int matchcnt;
1899 	int error;
1900 
1901 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1902 	/*
1903 	 * If we are being called because of a process doing a
1904 	 * copy-on-write, then it is not safe to write as we may
1905 	 * recurse into the copy-on-write routine.
1906 	 */
1907 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1908 		return (-1);
1909 	PHOLD(curproc);	/* Don't let the stack go away. */
1910 	ump = VFSTOUFS(mp);
1911 	LOCK_OWNED(ump);
1912 	matchcnt = 0;
1913 	sentinel.wk_mp = NULL;
1914 	sentinel.wk_type = D_SENTINEL;
1915 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1916 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1917 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1918 		if (wk->wk_type == D_SENTINEL) {
1919 			LIST_REMOVE(&sentinel, wk_list);
1920 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1921 			continue;
1922 		}
1923 		if (wk->wk_state & INPROGRESS)
1924 			panic("process_worklist_item: %p already in progress.",
1925 			    wk);
1926 		wk->wk_state |= INPROGRESS;
1927 		remove_from_worklist(wk);
1928 		FREE_LOCK(ump);
1929 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1930 			panic("process_worklist_item: suspended filesystem");
1931 		switch (wk->wk_type) {
1932 		case D_DIRREM:
1933 			/* removal of a directory entry */
1934 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
1935 			break;
1936 
1937 		case D_FREEBLKS:
1938 			/* releasing blocks and/or fragments from a file */
1939 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1940 			    flags);
1941 			break;
1942 
1943 		case D_FREEFRAG:
1944 			/* releasing a fragment when replaced as a file grows */
1945 			handle_workitem_freefrag(WK_FREEFRAG(wk));
1946 			error = 0;
1947 			break;
1948 
1949 		case D_FREEFILE:
1950 			/* releasing an inode when its link count drops to 0 */
1951 			handle_workitem_freefile(WK_FREEFILE(wk));
1952 			error = 0;
1953 			break;
1954 
1955 		default:
1956 			panic("%s_process_worklist: Unknown type %s",
1957 			    "softdep", TYPENAME(wk->wk_type));
1958 			/* NOTREACHED */
1959 		}
1960 		vn_finished_secondary_write(mp);
1961 		ACQUIRE_LOCK(ump);
1962 		if (error == 0) {
1963 			if (++matchcnt == target)
1964 				break;
1965 			continue;
1966 		}
1967 		/*
1968 		 * We have to retry the worklist item later.  Wake up any
1969 		 * waiters who may be able to complete it immediately and
1970 		 * add the item back to the head so we don't try to execute
1971 		 * it again.
1972 		 */
1973 		wk->wk_state &= ~INPROGRESS;
1974 		wake_worklist(wk);
1975 		add_to_worklist(wk, WK_HEAD);
1976 	}
1977 	/* Sentinal could've become the tail from remove_from_worklist. */
1978 	if (ump->softdep_worklist_tail == &sentinel)
1979 		ump->softdep_worklist_tail =
1980 		    (struct worklist *)sentinel.wk_list.le_prev;
1981 	LIST_REMOVE(&sentinel, wk_list);
1982 	PRELE(curproc);
1983 	return (matchcnt);
1984 }
1985 
1986 /*
1987  * Move dependencies from one buffer to another.
1988  */
1989 int
softdep_move_dependencies(struct buf * oldbp,struct buf * newbp)1990 softdep_move_dependencies(struct buf *oldbp, struct buf *newbp)
1991 {
1992 	struct worklist *wk, *wktail;
1993 	struct ufsmount *ump;
1994 	int dirty;
1995 
1996 	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1997 		return (0);
1998 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1999 	    ("softdep_move_dependencies called on non-softdep filesystem"));
2000 	dirty = 0;
2001 	wktail = NULL;
2002 	ump = VFSTOUFS(wk->wk_mp);
2003 	ACQUIRE_LOCK(ump);
2004 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
2005 		LIST_REMOVE(wk, wk_list);
2006 		if (wk->wk_type == D_BMSAFEMAP &&
2007 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
2008 			dirty = 1;
2009 		if (wktail == NULL)
2010 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
2011 		else
2012 			LIST_INSERT_AFTER(wktail, wk, wk_list);
2013 		wktail = wk;
2014 	}
2015 	FREE_LOCK(ump);
2016 
2017 	return (dirty);
2018 }
2019 
2020 /*
2021  * Purge the work list of all items associated with a particular mount point.
2022  */
2023 int
softdep_flushworklist(struct mount * oldmnt,int * countp,struct thread * td)2024 softdep_flushworklist(struct mount *oldmnt,
2025 	int *countp,
2026 	struct thread *td)
2027 {
2028 	struct vnode *devvp;
2029 	struct ufsmount *ump;
2030 	int count, error;
2031 
2032 	/*
2033 	 * Alternately flush the block device associated with the mount
2034 	 * point and process any dependencies that the flushing
2035 	 * creates. We continue until no more worklist dependencies
2036 	 * are found.
2037 	 */
2038 	*countp = 0;
2039 	error = 0;
2040 	ump = VFSTOUFS(oldmnt);
2041 	devvp = ump->um_devvp;
2042 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
2043 		*countp += count;
2044 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
2045 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
2046 		VOP_UNLOCK(devvp);
2047 		if (error != 0)
2048 			break;
2049 	}
2050 	return (error);
2051 }
2052 
2053 #define	SU_WAITIDLE_RETRIES	20
2054 static int
softdep_waitidle(struct mount * mp,int flags __unused)2055 softdep_waitidle(struct mount *mp, int flags __unused)
2056 {
2057 	struct ufsmount *ump;
2058 	struct vnode *devvp;
2059 	struct thread *td;
2060 	int error, i;
2061 
2062 	ump = VFSTOUFS(mp);
2063 	KASSERT(ump->um_softdep != NULL,
2064 	    ("softdep_waitidle called on non-softdep filesystem"));
2065 	devvp = ump->um_devvp;
2066 	td = curthread;
2067 	error = 0;
2068 	ACQUIRE_LOCK(ump);
2069 	for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
2070 		ump->softdep_req = 1;
2071 		KASSERT((flags & FORCECLOSE) == 0 ||
2072 		    ump->softdep_on_worklist == 0,
2073 		    ("softdep_waitidle: work added after flush"));
2074 		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
2075 		    "softdeps", 10 * hz);
2076 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
2077 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
2078 		VOP_UNLOCK(devvp);
2079 		ACQUIRE_LOCK(ump);
2080 		if (error != 0)
2081 			break;
2082 	}
2083 	ump->softdep_req = 0;
2084 	if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
2085 		error = EBUSY;
2086 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
2087 		    mp);
2088 	}
2089 	FREE_LOCK(ump);
2090 	return (error);
2091 }
2092 
2093 /*
2094  * Flush all vnodes and worklist items associated with a specified mount point.
2095  */
2096 int
softdep_flushfiles(struct mount * oldmnt,int flags,struct thread * td)2097 softdep_flushfiles(struct mount *oldmnt,
2098 	int flags,
2099 	struct thread *td)
2100 {
2101 	struct ufsmount *ump;
2102 #ifdef QUOTA
2103 	int i;
2104 #endif
2105 	int error, early, depcount, loopcnt, retry_flush_count, retry;
2106 	int morework;
2107 
2108 	ump = VFSTOUFS(oldmnt);
2109 	KASSERT(ump->um_softdep != NULL,
2110 	    ("softdep_flushfiles called on non-softdep filesystem"));
2111 	loopcnt = 10;
2112 	retry_flush_count = 3;
2113 retry_flush:
2114 	error = 0;
2115 
2116 	/*
2117 	 * Alternately flush the vnodes associated with the mount
2118 	 * point and process any dependencies that the flushing
2119 	 * creates. In theory, this loop can happen at most twice,
2120 	 * but we give it a few extra just to be sure.
2121 	 */
2122 	for (; loopcnt > 0; loopcnt--) {
2123 		/*
2124 		 * Do another flush in case any vnodes were brought in
2125 		 * as part of the cleanup operations.
2126 		 */
2127 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
2128 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
2129 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
2130 			break;
2131 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
2132 		    depcount == 0)
2133 			break;
2134 	}
2135 	/*
2136 	 * If we are unmounting then it is an error to fail. If we
2137 	 * are simply trying to downgrade to read-only, then filesystem
2138 	 * activity can keep us busy forever, so we just fail with EBUSY.
2139 	 */
2140 	if (loopcnt == 0) {
2141 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2142 			panic("softdep_flushfiles: looping");
2143 		error = EBUSY;
2144 	}
2145 	if (!error)
2146 		error = softdep_waitidle(oldmnt, flags);
2147 	if (!error) {
2148 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2149 			retry = 0;
2150 			MNT_ILOCK(oldmnt);
2151 			morework = oldmnt->mnt_nvnodelistsize > 0;
2152 #ifdef QUOTA
2153 			UFS_LOCK(ump);
2154 			for (i = 0; i < MAXQUOTAS; i++) {
2155 				if (ump->um_quotas[i] != NULLVP)
2156 					morework = 1;
2157 			}
2158 			UFS_UNLOCK(ump);
2159 #endif
2160 			if (morework) {
2161 				if (--retry_flush_count > 0) {
2162 					retry = 1;
2163 					loopcnt = 3;
2164 				} else
2165 					error = EBUSY;
2166 			}
2167 			MNT_IUNLOCK(oldmnt);
2168 			if (retry)
2169 				goto retry_flush;
2170 		}
2171 	}
2172 	return (error);
2173 }
2174 
2175 /*
2176  * Structure hashing.
2177  *
2178  * There are four types of structures that can be looked up:
2179  *	1) pagedep structures identified by mount point, inode number,
2180  *	   and logical block.
2181  *	2) inodedep structures identified by mount point and inode number.
2182  *	3) newblk structures identified by mount point and
2183  *	   physical block number.
2184  *	4) bmsafemap structures identified by mount point and
2185  *	   cylinder group number.
2186  *
2187  * The "pagedep" and "inodedep" dependency structures are hashed
2188  * separately from the file blocks and inodes to which they correspond.
2189  * This separation helps when the in-memory copy of an inode or
2190  * file block must be replaced. It also obviates the need to access
2191  * an inode or file page when simply updating (or de-allocating)
2192  * dependency structures. Lookup of newblk structures is needed to
2193  * find newly allocated blocks when trying to associate them with
2194  * their allocdirect or allocindir structure.
2195  *
2196  * The lookup routines optionally create and hash a new instance when
2197  * an existing entry is not found. The bmsafemap lookup routine always
2198  * allocates a new structure if an existing one is not found.
2199  */
2200 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2201 
2202 /*
2203  * Structures and routines associated with pagedep caching.
2204  */
2205 #define	PAGEDEP_HASH(ump, inum, lbn) \
2206 	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2207 
2208 static int
pagedep_find(struct pagedep_hashhead * pagedephd,ino_t ino,ufs_lbn_t lbn,struct pagedep ** pagedeppp)2209 pagedep_find(struct pagedep_hashhead *pagedephd,
2210 	ino_t ino,
2211 	ufs_lbn_t lbn,
2212 	struct pagedep **pagedeppp)
2213 {
2214 	struct pagedep *pagedep;
2215 
2216 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2217 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2218 			*pagedeppp = pagedep;
2219 			return (1);
2220 		}
2221 	}
2222 	*pagedeppp = NULL;
2223 	return (0);
2224 }
2225 /*
2226  * Look up a pagedep. Return 1 if found, 0 otherwise.
2227  * If not found, allocate if DEPALLOC flag is passed.
2228  * Found or allocated entry is returned in pagedeppp.
2229  */
2230 static int
pagedep_lookup(struct mount * mp,struct buf * bp,ino_t ino,ufs_lbn_t lbn,int flags,struct pagedep ** pagedeppp)2231 pagedep_lookup(struct mount *mp,
2232 	struct buf *bp,
2233 	ino_t ino,
2234 	ufs_lbn_t lbn,
2235 	int flags,
2236 	struct pagedep **pagedeppp)
2237 {
2238 	struct pagedep *pagedep;
2239 	struct pagedep_hashhead *pagedephd;
2240 	struct worklist *wk;
2241 	struct ufsmount *ump;
2242 	int ret;
2243 	int i;
2244 
2245 	ump = VFSTOUFS(mp);
2246 	LOCK_OWNED(ump);
2247 	if (bp) {
2248 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2249 			if (wk->wk_type == D_PAGEDEP) {
2250 				*pagedeppp = WK_PAGEDEP(wk);
2251 				return (1);
2252 			}
2253 		}
2254 	}
2255 	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2256 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2257 	if (ret) {
2258 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2259 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2260 		return (1);
2261 	}
2262 	if ((flags & DEPALLOC) == 0)
2263 		return (0);
2264 	FREE_LOCK(ump);
2265 	pagedep = malloc(sizeof(struct pagedep),
2266 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2267 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2268 	ACQUIRE_LOCK(ump);
2269 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2270 	if (*pagedeppp) {
2271 		/*
2272 		 * This should never happen since we only create pagedeps
2273 		 * with the vnode lock held.  Could be an assert.
2274 		 */
2275 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2276 		return (ret);
2277 	}
2278 	pagedep->pd_ino = ino;
2279 	pagedep->pd_lbn = lbn;
2280 	LIST_INIT(&pagedep->pd_dirremhd);
2281 	LIST_INIT(&pagedep->pd_pendinghd);
2282 	for (i = 0; i < DAHASHSZ; i++)
2283 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2284 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2285 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2286 	*pagedeppp = pagedep;
2287 	return (0);
2288 }
2289 
2290 /*
2291  * Structures and routines associated with inodedep caching.
2292  */
2293 #define	INODEDEP_HASH(ump, inum) \
2294       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2295 
2296 static int
inodedep_find(struct inodedep_hashhead * inodedephd,ino_t inum,struct inodedep ** inodedeppp)2297 inodedep_find(struct inodedep_hashhead *inodedephd,
2298 	ino_t inum,
2299 	struct inodedep **inodedeppp)
2300 {
2301 	struct inodedep *inodedep;
2302 
2303 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2304 		if (inum == inodedep->id_ino)
2305 			break;
2306 	if (inodedep) {
2307 		*inodedeppp = inodedep;
2308 		return (1);
2309 	}
2310 	*inodedeppp = NULL;
2311 
2312 	return (0);
2313 }
2314 /*
2315  * Look up an inodedep. Return 1 if found, 0 if not found.
2316  * If not found, allocate if DEPALLOC flag is passed.
2317  * Found or allocated entry is returned in inodedeppp.
2318  */
2319 static int
inodedep_lookup(struct mount * mp,ino_t inum,int flags,struct inodedep ** inodedeppp)2320 inodedep_lookup(struct mount *mp,
2321 	ino_t inum,
2322 	int flags,
2323 	struct inodedep **inodedeppp)
2324 {
2325 	struct inodedep *inodedep;
2326 	struct inodedep_hashhead *inodedephd;
2327 	struct ufsmount *ump;
2328 	struct fs *fs;
2329 
2330 	ump = VFSTOUFS(mp);
2331 	LOCK_OWNED(ump);
2332 	fs = ump->um_fs;
2333 	inodedephd = INODEDEP_HASH(ump, inum);
2334 
2335 	if (inodedep_find(inodedephd, inum, inodedeppp))
2336 		return (1);
2337 	if ((flags & DEPALLOC) == 0)
2338 		return (0);
2339 	/*
2340 	 * If the system is over its limit and our filesystem is
2341 	 * responsible for more than our share of that usage and
2342 	 * we are not in a rush, request some inodedep cleanup.
2343 	 */
2344 	if (softdep_excess_items(ump, D_INODEDEP))
2345 		schedule_cleanup(mp);
2346 	else
2347 		FREE_LOCK(ump);
2348 	inodedep = malloc(sizeof(struct inodedep),
2349 		M_INODEDEP, M_SOFTDEP_FLAGS);
2350 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2351 	ACQUIRE_LOCK(ump);
2352 	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2353 		WORKITEM_FREE(inodedep, D_INODEDEP);
2354 		return (1);
2355 	}
2356 	inodedep->id_fs = fs;
2357 	inodedep->id_ino = inum;
2358 	inodedep->id_state = ALLCOMPLETE;
2359 	inodedep->id_nlinkdelta = 0;
2360 	inodedep->id_nlinkwrote = -1;
2361 	inodedep->id_savedino1 = NULL;
2362 	inodedep->id_savedsize = -1;
2363 	inodedep->id_savedextsize = -1;
2364 	inodedep->id_savednlink = -1;
2365 	inodedep->id_bmsafemap = NULL;
2366 	inodedep->id_mkdiradd = NULL;
2367 	LIST_INIT(&inodedep->id_dirremhd);
2368 	LIST_INIT(&inodedep->id_pendinghd);
2369 	LIST_INIT(&inodedep->id_inowait);
2370 	LIST_INIT(&inodedep->id_bufwait);
2371 	TAILQ_INIT(&inodedep->id_inoreflst);
2372 	TAILQ_INIT(&inodedep->id_inoupdt);
2373 	TAILQ_INIT(&inodedep->id_newinoupdt);
2374 	TAILQ_INIT(&inodedep->id_extupdt);
2375 	TAILQ_INIT(&inodedep->id_newextupdt);
2376 	TAILQ_INIT(&inodedep->id_freeblklst);
2377 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2378 	*inodedeppp = inodedep;
2379 	return (0);
2380 }
2381 
2382 /*
2383  * Structures and routines associated with newblk caching.
2384  */
2385 #define	NEWBLK_HASH(ump, inum) \
2386 	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2387 
2388 static int
newblk_find(struct newblk_hashhead * newblkhd,ufs2_daddr_t newblkno,int flags,struct newblk ** newblkpp)2389 newblk_find(struct newblk_hashhead *newblkhd,
2390 	ufs2_daddr_t newblkno,
2391 	int flags,
2392 	struct newblk **newblkpp)
2393 {
2394 	struct newblk *newblk;
2395 
2396 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2397 		if (newblkno != newblk->nb_newblkno)
2398 			continue;
2399 		/*
2400 		 * If we're creating a new dependency don't match those that
2401 		 * have already been converted to allocdirects.  This is for
2402 		 * a frag extend.
2403 		 */
2404 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2405 			continue;
2406 		break;
2407 	}
2408 	if (newblk) {
2409 		*newblkpp = newblk;
2410 		return (1);
2411 	}
2412 	*newblkpp = NULL;
2413 	return (0);
2414 }
2415 
2416 /*
2417  * Look up a newblk. Return 1 if found, 0 if not found.
2418  * If not found, allocate if DEPALLOC flag is passed.
2419  * Found or allocated entry is returned in newblkpp.
2420  */
2421 static int
newblk_lookup(struct mount * mp,ufs2_daddr_t newblkno,int flags,struct newblk ** newblkpp)2422 newblk_lookup(struct mount *mp,
2423 	ufs2_daddr_t newblkno,
2424 	int flags,
2425 	struct newblk **newblkpp)
2426 {
2427 	struct newblk *newblk;
2428 	struct newblk_hashhead *newblkhd;
2429 	struct ufsmount *ump;
2430 
2431 	ump = VFSTOUFS(mp);
2432 	LOCK_OWNED(ump);
2433 	newblkhd = NEWBLK_HASH(ump, newblkno);
2434 	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2435 		return (1);
2436 	if ((flags & DEPALLOC) == 0)
2437 		return (0);
2438 	if (softdep_excess_items(ump, D_NEWBLK) ||
2439 	    softdep_excess_items(ump, D_ALLOCDIRECT) ||
2440 	    softdep_excess_items(ump, D_ALLOCINDIR))
2441 		schedule_cleanup(mp);
2442 	else
2443 		FREE_LOCK(ump);
2444 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2445 	    M_SOFTDEP_FLAGS | M_ZERO);
2446 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2447 	ACQUIRE_LOCK(ump);
2448 	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2449 		WORKITEM_FREE(newblk, D_NEWBLK);
2450 		return (1);
2451 	}
2452 	newblk->nb_freefrag = NULL;
2453 	LIST_INIT(&newblk->nb_indirdeps);
2454 	LIST_INIT(&newblk->nb_newdirblk);
2455 	LIST_INIT(&newblk->nb_jwork);
2456 	newblk->nb_state = ATTACHED;
2457 	newblk->nb_newblkno = newblkno;
2458 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2459 	*newblkpp = newblk;
2460 	return (0);
2461 }
2462 
2463 /*
2464  * Structures and routines associated with freed indirect block caching.
2465  */
2466 #define	INDIR_HASH(ump, blkno) \
2467 	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2468 
2469 /*
2470  * Lookup an indirect block in the indir hash table.  The freework is
2471  * removed and potentially freed.  The caller must do a blocking journal
2472  * write before writing to the blkno.
2473  */
2474 static int
indirblk_lookup(struct mount * mp,ufs2_daddr_t blkno)2475 indirblk_lookup(struct mount *mp, ufs2_daddr_t blkno)
2476 {
2477 	struct freework *freework;
2478 	struct indir_hashhead *wkhd;
2479 	struct ufsmount *ump;
2480 
2481 	ump = VFSTOUFS(mp);
2482 	wkhd = INDIR_HASH(ump, blkno);
2483 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2484 		if (freework->fw_blkno != blkno)
2485 			continue;
2486 		indirblk_remove(freework);
2487 		return (1);
2488 	}
2489 	return (0);
2490 }
2491 
2492 /*
2493  * Insert an indirect block represented by freework into the indirblk
2494  * hash table so that it may prevent the block from being re-used prior
2495  * to the journal being written.
2496  */
2497 static void
indirblk_insert(struct freework * freework)2498 indirblk_insert(struct freework *freework)
2499 {
2500 	struct jblocks *jblocks;
2501 	struct jseg *jseg;
2502 	struct ufsmount *ump;
2503 
2504 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2505 	jblocks = ump->softdep_jblocks;
2506 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2507 	if (jseg == NULL)
2508 		return;
2509 
2510 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2511 	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2512 	    fw_next);
2513 	freework->fw_state &= ~DEPCOMPLETE;
2514 }
2515 
2516 static void
indirblk_remove(struct freework * freework)2517 indirblk_remove(struct freework *freework)
2518 {
2519 	struct ufsmount *ump;
2520 
2521 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2522 	LIST_REMOVE(freework, fw_segs);
2523 	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2524 	freework->fw_state |= DEPCOMPLETE;
2525 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2526 		WORKITEM_FREE(freework, D_FREEWORK);
2527 }
2528 
2529 /*
2530  * Executed during filesystem system initialization before
2531  * mounting any filesystems.
2532  */
2533 void
softdep_initialize(void)2534 softdep_initialize(void)
2535 {
2536 
2537 	TAILQ_INIT(&softdepmounts);
2538 #ifdef __LP64__
2539 	max_softdeps = desiredvnodes * 4;
2540 #else
2541 	max_softdeps = desiredvnodes * 2;
2542 #endif
2543 
2544 	/* initialise bioops hack */
2545 	bioops.io_start = softdep_disk_io_initiation;
2546 	bioops.io_complete = softdep_disk_write_complete;
2547 	bioops.io_deallocate = softdep_deallocate_dependencies;
2548 	bioops.io_countdeps = softdep_count_dependencies;
2549 	softdep_ast_cleanup = softdep_ast_cleanup_proc;
2550 
2551 	/* Initialize the callout with an mtx. */
2552 	callout_init_mtx(&softdep_callout, &lk, 0);
2553 }
2554 
2555 /*
2556  * Executed after all filesystems have been unmounted during
2557  * filesystem module unload.
2558  */
2559 void
softdep_uninitialize(void)2560 softdep_uninitialize(void)
2561 {
2562 
2563 	/* clear bioops hack */
2564 	bioops.io_start = NULL;
2565 	bioops.io_complete = NULL;
2566 	bioops.io_deallocate = NULL;
2567 	bioops.io_countdeps = NULL;
2568 	softdep_ast_cleanup = NULL;
2569 
2570 	callout_drain(&softdep_callout);
2571 }
2572 
2573 /*
2574  * Called at mount time to notify the dependency code that a
2575  * filesystem wishes to use it.
2576  */
2577 int
softdep_mount(struct vnode * devvp,struct mount * mp,struct fs * fs,struct ucred * cred)2578 softdep_mount(struct vnode *devvp,
2579 	struct mount *mp,
2580 	struct fs *fs,
2581 	struct ucred *cred)
2582 {
2583 	struct csum_total cstotal;
2584 	struct mount_softdeps *sdp;
2585 	struct ufsmount *ump;
2586 	struct cg *cgp;
2587 	struct buf *bp;
2588 	uint64_t cyl, i;
2589 	int error;
2590 
2591 	ump = VFSTOUFS(mp);
2592 
2593 	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2594 	    M_WAITOK | M_ZERO);
2595 	rw_init(&sdp->sd_fslock, "SUrw");
2596 	sdp->sd_ump = ump;
2597 	LIST_INIT(&sdp->sd_workitem_pending);
2598 	LIST_INIT(&sdp->sd_journal_pending);
2599 	TAILQ_INIT(&sdp->sd_unlinked);
2600 	LIST_INIT(&sdp->sd_dirtycg);
2601 	sdp->sd_worklist_tail = NULL;
2602 	sdp->sd_on_worklist = 0;
2603 	sdp->sd_deps = 0;
2604 	LIST_INIT(&sdp->sd_mkdirlisthd);
2605 	sdp->sd_pdhash = hashinit(desiredvnodes / 5, M_PAGEDEP,
2606 	    &sdp->sd_pdhashsize);
2607 	sdp->sd_pdnextclean = 0;
2608 	sdp->sd_idhash = hashinit(desiredvnodes, M_INODEDEP,
2609 	    &sdp->sd_idhashsize);
2610 	sdp->sd_idnextclean = 0;
2611 	sdp->sd_newblkhash = hashinit(max_softdeps / 2,  M_NEWBLK,
2612 	    &sdp->sd_newblkhashsize);
2613 	sdp->sd_bmhash = hashinit(1024, M_BMSAFEMAP, &sdp->sd_bmhashsize);
2614 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2615 	sdp->sd_indirhash = malloc(i * sizeof(struct indir_hashhead),
2616 	    M_FREEWORK, M_WAITOK);
2617 	sdp->sd_indirhashsize = i - 1;
2618 	for (i = 0; i <= sdp->sd_indirhashsize; i++)
2619 		TAILQ_INIT(&sdp->sd_indirhash[i]);
2620 	for (i = 0; i <= D_LAST; i++)
2621 		LIST_INIT(&sdp->sd_alldeps[i]);
2622 	ACQUIRE_GBLLOCK(&lk);
2623 	TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2624 	FREE_GBLLOCK(&lk);
2625 
2626 	ump->um_softdep = sdp;
2627 	MNT_ILOCK(mp);
2628 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2629 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2630 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2631 		    MNTK_SOFTDEP | MNTK_NOASYNC;
2632 	}
2633 	MNT_IUNLOCK(mp);
2634 
2635 	if ((fs->fs_flags & FS_SUJ) &&
2636 	    (error = journal_mount(mp, fs, cred)) != 0) {
2637 		printf("Failed to start journal: %d\n", error);
2638 		softdep_unmount(mp);
2639 		return (error);
2640 	}
2641 	/*
2642 	 * Start our flushing thread in the bufdaemon process.
2643 	 */
2644 	ACQUIRE_LOCK(ump);
2645 	ump->softdep_flags |= FLUSH_STARTING;
2646 	FREE_LOCK(ump);
2647 	kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2648 	    &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2649 	    mp->mnt_stat.f_mntonname);
2650 	ACQUIRE_LOCK(ump);
2651 	while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2652 		msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2653 		    hz / 2);
2654 	}
2655 	FREE_LOCK(ump);
2656 	/*
2657 	 * When doing soft updates, the counters in the
2658 	 * superblock may have gotten out of sync. Recomputation
2659 	 * can take a long time and can be deferred for background
2660 	 * fsck.  However, the old behavior of scanning the cylinder
2661 	 * groups and recalculating them at mount time is available
2662 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2663 	 */
2664 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2665 		return (0);
2666 	bzero(&cstotal, sizeof cstotal);
2667 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2668 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2669 		    fs->fs_cgsize, cred, &bp)) != 0) {
2670 			brelse(bp);
2671 			softdep_unmount(mp);
2672 			return (error);
2673 		}
2674 		cgp = (struct cg *)bp->b_data;
2675 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2676 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2677 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2678 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2679 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2680 		brelse(bp);
2681 	}
2682 #ifdef INVARIANTS
2683 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2684 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2685 #endif
2686 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2687 	return (0);
2688 }
2689 
2690 void
softdep_unmount(struct mount * mp)2691 softdep_unmount(struct mount *mp)
2692 {
2693 	struct ufsmount *ump;
2694 	struct mount_softdeps *ums;
2695 
2696 	ump = VFSTOUFS(mp);
2697 	KASSERT(ump->um_softdep != NULL,
2698 	    ("softdep_unmount called on non-softdep filesystem"));
2699 	MNT_ILOCK(mp);
2700 	mp->mnt_flag &= ~MNT_SOFTDEP;
2701 	if ((mp->mnt_flag & MNT_SUJ) == 0) {
2702 		MNT_IUNLOCK(mp);
2703 	} else {
2704 		mp->mnt_flag &= ~MNT_SUJ;
2705 		MNT_IUNLOCK(mp);
2706 		journal_unmount(ump);
2707 	}
2708 	/*
2709 	 * Shut down our flushing thread. Check for NULL is if
2710 	 * softdep_mount errors out before the thread has been created.
2711 	 */
2712 	if (ump->softdep_flushtd != NULL) {
2713 		ACQUIRE_LOCK(ump);
2714 		ump->softdep_flags |= FLUSH_EXIT;
2715 		wakeup(&ump->softdep_flushtd);
2716 		while ((ump->softdep_flags & FLUSH_EXIT) != 0) {
2717 			msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM,
2718 			    "sdwait", 0);
2719 		}
2720 		KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2721 		    ("Thread shutdown failed"));
2722 		FREE_LOCK(ump);
2723 	}
2724 
2725 	/*
2726 	 * We are no longer have softdep structure attached to ump.
2727 	 */
2728 	ums = ump->um_softdep;
2729 	ACQUIRE_GBLLOCK(&lk);
2730 	TAILQ_REMOVE(&softdepmounts, ums, sd_next);
2731 	FREE_GBLLOCK(&lk);
2732 	ump->um_softdep = NULL;
2733 
2734 	KASSERT(ums->sd_on_journal == 0,
2735 	    ("ump %p ums %p on_journal %d", ump, ums, ums->sd_on_journal));
2736 	KASSERT(ums->sd_on_worklist == 0,
2737 	    ("ump %p ums %p on_worklist %d", ump, ums, ums->sd_on_worklist));
2738 	KASSERT(ums->sd_deps == 0,
2739 	    ("ump %p ums %p deps %d", ump, ums, ums->sd_deps));
2740 
2741 	/*
2742 	 * Free up our resources.
2743 	 */
2744 	rw_destroy(&ums->sd_fslock);
2745 	hashdestroy(ums->sd_pdhash, M_PAGEDEP, ums->sd_pdhashsize);
2746 	hashdestroy(ums->sd_idhash, M_INODEDEP, ums->sd_idhashsize);
2747 	hashdestroy(ums->sd_newblkhash, M_NEWBLK, ums->sd_newblkhashsize);
2748 	hashdestroy(ums->sd_bmhash, M_BMSAFEMAP, ums->sd_bmhashsize);
2749 	free(ums->sd_indirhash, M_FREEWORK);
2750 #ifdef INVARIANTS
2751 	for (int i = 0; i <= D_LAST; i++) {
2752 		KASSERT(ums->sd_curdeps[i] == 0,
2753 		    ("Unmount %s: Dep type %s != 0 (%jd)", ump->um_fs->fs_fsmnt,
2754 		    TYPENAME(i), (intmax_t)ums->sd_curdeps[i]));
2755 		KASSERT(LIST_EMPTY(&ums->sd_alldeps[i]),
2756 		    ("Unmount %s: Dep type %s not empty (%p)",
2757 		    ump->um_fs->fs_fsmnt,
2758 		    TYPENAME(i), LIST_FIRST(&ums->sd_alldeps[i])));
2759 	}
2760 #endif
2761 	free(ums, M_MOUNTDATA);
2762 }
2763 
2764 static struct jblocks *
jblocks_create(void)2765 jblocks_create(void)
2766 {
2767 	struct jblocks *jblocks;
2768 
2769 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2770 	TAILQ_INIT(&jblocks->jb_segs);
2771 	jblocks->jb_avail = 10;
2772 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2773 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2774 
2775 	return (jblocks);
2776 }
2777 
2778 static ufs2_daddr_t
jblocks_alloc(struct jblocks * jblocks,int bytes,int * actual)2779 jblocks_alloc(struct jblocks *jblocks,
2780 	int bytes,
2781 	int *actual)
2782 {
2783 	ufs2_daddr_t daddr;
2784 	struct jextent *jext;
2785 	int freecnt;
2786 	int blocks;
2787 
2788 	blocks = bytes / DEV_BSIZE;
2789 	jext = &jblocks->jb_extent[jblocks->jb_head];
2790 	freecnt = jext->je_blocks - jblocks->jb_off;
2791 	if (freecnt == 0) {
2792 		jblocks->jb_off = 0;
2793 		if (++jblocks->jb_head > jblocks->jb_used)
2794 			jblocks->jb_head = 0;
2795 		jext = &jblocks->jb_extent[jblocks->jb_head];
2796 		freecnt = jext->je_blocks;
2797 	}
2798 	if (freecnt > blocks)
2799 		freecnt = blocks;
2800 	*actual = freecnt * DEV_BSIZE;
2801 	daddr = jext->je_daddr + jblocks->jb_off;
2802 	jblocks->jb_off += freecnt;
2803 	jblocks->jb_free -= freecnt;
2804 
2805 	return (daddr);
2806 }
2807 
2808 static void
jblocks_free(struct jblocks * jblocks,struct mount * mp,int bytes)2809 jblocks_free(struct jblocks *jblocks,
2810 	struct mount *mp,
2811 	int bytes)
2812 {
2813 
2814 	LOCK_OWNED(VFSTOUFS(mp));
2815 	jblocks->jb_free += bytes / DEV_BSIZE;
2816 	if (jblocks->jb_suspended)
2817 		worklist_speedup(mp);
2818 	wakeup(jblocks);
2819 }
2820 
2821 static void
jblocks_destroy(struct jblocks * jblocks)2822 jblocks_destroy(struct jblocks *jblocks)
2823 {
2824 
2825 	if (jblocks->jb_extent)
2826 		free(jblocks->jb_extent, M_JBLOCKS);
2827 	free(jblocks, M_JBLOCKS);
2828 }
2829 
2830 static void
jblocks_add(struct jblocks * jblocks,ufs2_daddr_t daddr,int blocks)2831 jblocks_add(struct jblocks *jblocks,
2832 	ufs2_daddr_t daddr,
2833 	int blocks)
2834 {
2835 	struct jextent *jext;
2836 
2837 	jblocks->jb_blocks += blocks;
2838 	jblocks->jb_free += blocks;
2839 	jext = &jblocks->jb_extent[jblocks->jb_used];
2840 	/* Adding the first block. */
2841 	if (jext->je_daddr == 0) {
2842 		jext->je_daddr = daddr;
2843 		jext->je_blocks = blocks;
2844 		return;
2845 	}
2846 	/* Extending the last extent. */
2847 	if (jext->je_daddr + jext->je_blocks == daddr) {
2848 		jext->je_blocks += blocks;
2849 		return;
2850 	}
2851 	/* Adding a new extent. */
2852 	if (++jblocks->jb_used == jblocks->jb_avail) {
2853 		jblocks->jb_avail *= 2;
2854 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2855 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2856 		memcpy(jext, jblocks->jb_extent,
2857 		    sizeof(struct jextent) * jblocks->jb_used);
2858 		free(jblocks->jb_extent, M_JBLOCKS);
2859 		jblocks->jb_extent = jext;
2860 	}
2861 	jext = &jblocks->jb_extent[jblocks->jb_used];
2862 	jext->je_daddr = daddr;
2863 	jext->je_blocks = blocks;
2864 	return;
2865 }
2866 
2867 int
softdep_journal_lookup(struct mount * mp,struct vnode ** vpp)2868 softdep_journal_lookup(struct mount *mp, struct vnode **vpp)
2869 {
2870 	struct componentname cnp;
2871 	struct vnode *dvp;
2872 	ino_t sujournal;
2873 	int error;
2874 
2875 	error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2876 	if (error)
2877 		return (error);
2878 	bzero(&cnp, sizeof(cnp));
2879 	cnp.cn_nameiop = LOOKUP;
2880 	cnp.cn_flags = ISLASTCN;
2881 	cnp.cn_thread = curthread;
2882 	cnp.cn_cred = curthread->td_ucred;
2883 	cnp.cn_pnbuf = SUJ_FILE;
2884 	cnp.cn_nameptr = SUJ_FILE;
2885 	cnp.cn_namelen = strlen(SUJ_FILE);
2886 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2887 	vput(dvp);
2888 	if (error != 0)
2889 		return (error);
2890 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2891 	return (error);
2892 }
2893 
2894 /*
2895  * Open and verify the journal file.
2896  */
2897 static int
journal_mount(struct mount * mp,struct fs * fs,struct ucred * cred)2898 journal_mount(struct mount *mp,
2899 	struct fs *fs,
2900 	struct ucred *cred)
2901 {
2902 	struct jblocks *jblocks;
2903 	struct ufsmount *ump;
2904 	struct vnode *vp;
2905 	struct inode *ip;
2906 	ufs2_daddr_t blkno;
2907 	int bcount;
2908 	int error;
2909 	int i;
2910 
2911 	ump = VFSTOUFS(mp);
2912 	ump->softdep_journal_tail = NULL;
2913 	ump->softdep_on_journal = 0;
2914 	ump->softdep_accdeps = 0;
2915 	ump->softdep_req = 0;
2916 	ump->softdep_jblocks = NULL;
2917 	error = softdep_journal_lookup(mp, &vp);
2918 	if (error != 0) {
2919 		printf("Failed to find journal.  Use tunefs to create one\n");
2920 		return (error);
2921 	}
2922 	ip = VTOI(vp);
2923 	if (ip->i_size < SUJ_MIN) {
2924 		error = ENOSPC;
2925 		goto out;
2926 	}
2927 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2928 	jblocks = jblocks_create();
2929 	for (i = 0; i < bcount; i++) {
2930 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2931 		if (error)
2932 			break;
2933 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2934 	}
2935 	if (error) {
2936 		jblocks_destroy(jblocks);
2937 		goto out;
2938 	}
2939 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
2940 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2941 	ump->softdep_jblocks = jblocks;
2942 
2943 	MNT_ILOCK(mp);
2944 	mp->mnt_flag |= MNT_SUJ;
2945 	MNT_IUNLOCK(mp);
2946 
2947 	/*
2948 	 * Only validate the journal contents if the
2949 	 * filesystem is clean, otherwise we write the logs
2950 	 * but they'll never be used.  If the filesystem was
2951 	 * still dirty when we mounted it the journal is
2952 	 * invalid and a new journal can only be valid if it
2953 	 * starts from a clean mount.
2954 	 */
2955 	if (fs->fs_clean) {
2956 		DIP_SET(ip, i_modrev, fs->fs_mtime);
2957 		ip->i_flags |= IN_MODIFIED;
2958 		ffs_update(vp, 1);
2959 	}
2960 out:
2961 	vput(vp);
2962 	return (error);
2963 }
2964 
2965 static void
journal_unmount(struct ufsmount * ump)2966 journal_unmount(struct ufsmount *ump)
2967 {
2968 
2969 	if (ump->softdep_jblocks)
2970 		jblocks_destroy(ump->softdep_jblocks);
2971 	ump->softdep_jblocks = NULL;
2972 }
2973 
2974 /*
2975  * Called when a journal record is ready to be written.  Space is allocated
2976  * and the journal entry is created when the journal is flushed to stable
2977  * store.
2978  */
2979 static void
add_to_journal(struct worklist * wk)2980 add_to_journal(struct worklist *wk)
2981 {
2982 	struct ufsmount *ump;
2983 
2984 	ump = VFSTOUFS(wk->wk_mp);
2985 	LOCK_OWNED(ump);
2986 	if (wk->wk_state & ONWORKLIST)
2987 		panic("add_to_journal: %s(0x%X) already on list",
2988 		    TYPENAME(wk->wk_type), wk->wk_state);
2989 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2990 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2991 		ump->softdep_jblocks->jb_age = ticks;
2992 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2993 	} else
2994 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2995 	ump->softdep_journal_tail = wk;
2996 	ump->softdep_on_journal += 1;
2997 }
2998 
2999 /*
3000  * Remove an arbitrary item for the journal worklist maintain the tail
3001  * pointer.  This happens when a new operation obviates the need to
3002  * journal an old operation.
3003  */
3004 static void
remove_from_journal(struct worklist * wk)3005 remove_from_journal(struct worklist *wk)
3006 {
3007 	struct ufsmount *ump;
3008 
3009 	ump = VFSTOUFS(wk->wk_mp);
3010 	LOCK_OWNED(ump);
3011 #ifdef INVARIANTS
3012 	{
3013 		struct worklist *wkn;
3014 
3015 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
3016 			if (wkn == wk)
3017 				break;
3018 		if (wkn == NULL)
3019 			panic("remove_from_journal: %p is not in journal", wk);
3020 	}
3021 #endif
3022 	/*
3023 	 * We emulate a TAILQ to save space in most structures which do not
3024 	 * require TAILQ semantics.  Here we must update the tail position
3025 	 * when removing the tail which is not the final entry. This works
3026 	 * only if the worklist linkage are at the beginning of the structure.
3027 	 */
3028 	if (ump->softdep_journal_tail == wk)
3029 		ump->softdep_journal_tail =
3030 		    (struct worklist *)wk->wk_list.le_prev;
3031 	WORKLIST_REMOVE(wk);
3032 	ump->softdep_on_journal -= 1;
3033 }
3034 
3035 /*
3036  * Check for journal space as well as dependency limits so the prelink
3037  * code can throttle both journaled and non-journaled filesystems.
3038  * Threshold is 0 for low and 1 for min.
3039  */
3040 static int
journal_space(struct ufsmount * ump,int thresh)3041 journal_space(struct ufsmount *ump, int thresh)
3042 {
3043 	struct jblocks *jblocks;
3044 	int limit, avail;
3045 
3046 	jblocks = ump->softdep_jblocks;
3047 	if (jblocks == NULL)
3048 		return (1);
3049 	/*
3050 	 * We use a tighter restriction here to prevent request_cleanup()
3051 	 * running in threads from running into locks we currently hold.
3052 	 * We have to be over the limit and our filesystem has to be
3053 	 * responsible for more than our share of that usage.
3054 	 */
3055 	limit = (max_softdeps / 10) * 9;
3056 	if (dep_current[D_INODEDEP] > limit &&
3057 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
3058 		return (0);
3059 	if (thresh)
3060 		thresh = jblocks->jb_min;
3061 	else
3062 		thresh = jblocks->jb_low;
3063 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
3064 	avail = jblocks->jb_free - avail;
3065 
3066 	return (avail > thresh);
3067 }
3068 
3069 static void
journal_suspend(struct ufsmount * ump)3070 journal_suspend(struct ufsmount *ump)
3071 {
3072 	struct jblocks *jblocks;
3073 	struct mount *mp;
3074 	bool set;
3075 
3076 	mp = UFSTOVFS(ump);
3077 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0)
3078 		return;
3079 
3080 	jblocks = ump->softdep_jblocks;
3081 	vfs_op_enter(mp);
3082 	set = false;
3083 	MNT_ILOCK(mp);
3084 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
3085 		stat_journal_min++;
3086 		mp->mnt_kern_flag |= MNTK_SUSPEND;
3087 		mp->mnt_susp_owner = ump->softdep_flushtd;
3088 		set = true;
3089 	}
3090 	jblocks->jb_suspended = 1;
3091 	MNT_IUNLOCK(mp);
3092 	if (!set)
3093 		vfs_op_exit(mp);
3094 }
3095 
3096 static int
journal_unsuspend(struct ufsmount * ump)3097 journal_unsuspend(struct ufsmount *ump)
3098 {
3099 	struct jblocks *jblocks;
3100 	struct mount *mp;
3101 
3102 	mp = UFSTOVFS(ump);
3103 	jblocks = ump->softdep_jblocks;
3104 
3105 	if (jblocks != NULL && jblocks->jb_suspended &&
3106 	    journal_space(ump, jblocks->jb_min)) {
3107 		jblocks->jb_suspended = 0;
3108 		FREE_LOCK(ump);
3109 		mp->mnt_susp_owner = curthread;
3110 		vfs_write_resume(mp, 0);
3111 		ACQUIRE_LOCK(ump);
3112 		return (1);
3113 	}
3114 	return (0);
3115 }
3116 
3117 static void
journal_check_space(struct ufsmount * ump)3118 journal_check_space(struct ufsmount *ump)
3119 {
3120 	struct mount *mp;
3121 
3122 	LOCK_OWNED(ump);
3123 
3124 	if (journal_space(ump, 0) == 0) {
3125 		softdep_speedup(ump);
3126 		mp = UFSTOVFS(ump);
3127 		FREE_LOCK(ump);
3128 		VFS_SYNC(mp, MNT_NOWAIT);
3129 		ffs_sbupdate(ump, MNT_WAIT, 0);
3130 		ACQUIRE_LOCK(ump);
3131 		if (journal_space(ump, 1) == 0)
3132 			journal_suspend(ump);
3133 	}
3134 }
3135 
3136 /*
3137  * Called before any allocation function to be certain that there is
3138  * sufficient space in the journal prior to creating any new records.
3139  * Since in the case of block allocation we may have multiple locked
3140  * buffers at the time of the actual allocation we can not block
3141  * when the journal records are created.  Doing so would create a deadlock
3142  * if any of these buffers needed to be flushed to reclaim space.  Instead
3143  * we require a sufficiently large amount of available space such that
3144  * each thread in the system could have passed this allocation check and
3145  * still have sufficient free space.  With 20% of a minimum journal size
3146  * of 1MB we have 6553 records available.
3147  */
3148 int
softdep_prealloc(struct vnode * vp,int waitok)3149 softdep_prealloc(struct vnode *vp, int waitok)
3150 {
3151 	struct ufsmount *ump;
3152 
3153 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3154 	    ("softdep_prealloc called on non-softdep filesystem"));
3155 	/*
3156 	 * Nothing to do if we are not running journaled soft updates.
3157 	 * If we currently hold the snapshot lock, we must avoid
3158 	 * handling other resources that could cause deadlock.  Do not
3159 	 * touch quotas vnode since it is typically recursed with
3160 	 * other vnode locks held.
3161 	 */
3162 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3163 	    (vp->v_vflag & VV_SYSTEM) != 0)
3164 		return (0);
3165 	ump = VFSTOUFS(vp->v_mount);
3166 	ACQUIRE_LOCK(ump);
3167 	if (journal_space(ump, 0)) {
3168 		FREE_LOCK(ump);
3169 		return (0);
3170 	}
3171 	stat_journal_low++;
3172 	FREE_LOCK(ump);
3173 	if (waitok == MNT_NOWAIT)
3174 		return (ENOSPC);
3175 	/*
3176 	 * Attempt to sync this vnode once to flush any journal
3177 	 * work attached to it.
3178 	 */
3179 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3180 		ffs_syncvnode(vp, waitok, 0);
3181 	ACQUIRE_LOCK(ump);
3182 	process_removes(vp);
3183 	process_truncates(vp);
3184 	journal_check_space(ump);
3185 	FREE_LOCK(ump);
3186 
3187 	return (0);
3188 }
3189 
3190 /*
3191  * Try hard to sync all data and metadata for the vnode, and workitems
3192  * flushing which might conflict with the vnode lock.  This is a
3193  * helper for softdep_prerename().
3194  */
3195 static int
softdep_prerename_vnode(struct ufsmount * ump,struct vnode * vp)3196 softdep_prerename_vnode(struct ufsmount *ump, struct vnode *vp)
3197 {
3198 	int error;
3199 
3200 	ASSERT_VOP_ELOCKED(vp, "prehandle");
3201 	if (vp->v_data == NULL)
3202 		return (0);
3203 	error = VOP_FSYNC(vp, MNT_WAIT, curthread);
3204 	if (error != 0)
3205 		return (error);
3206 	ACQUIRE_LOCK(ump);
3207 	process_removes(vp);
3208 	process_truncates(vp);
3209 	FREE_LOCK(ump);
3210 	return (0);
3211 }
3212 
3213 /*
3214  * Must be called from VOP_RENAME() after all vnodes are locked.
3215  * Ensures that there is enough journal space for rename.  It is
3216  * sufficiently different from softdep_prelink() by having to handle
3217  * four vnodes.
3218  */
3219 int
softdep_prerename(struct vnode * fdvp,struct vnode * fvp,struct vnode * tdvp,struct vnode * tvp)3220 softdep_prerename(struct vnode *fdvp,
3221 	struct vnode *fvp,
3222 	struct vnode *tdvp,
3223 	struct vnode *tvp)
3224 {
3225 	struct ufsmount *ump;
3226 	int error;
3227 
3228 	ump = VFSTOUFS(fdvp->v_mount);
3229 
3230 	if (journal_space(ump, 0))
3231 		return (0);
3232 
3233 	VOP_UNLOCK(tdvp);
3234 	VOP_UNLOCK(fvp);
3235 	if (tvp != NULL && tvp != tdvp)
3236 		VOP_UNLOCK(tvp);
3237 
3238 	error = softdep_prerename_vnode(ump, fdvp);
3239 	VOP_UNLOCK(fdvp);
3240 	if (error != 0)
3241 		return (error);
3242 
3243 	VOP_LOCK(fvp, LK_EXCLUSIVE | LK_RETRY);
3244 	error = softdep_prerename_vnode(ump, fvp);
3245 	VOP_UNLOCK(fvp);
3246 	if (error != 0)
3247 		return (error);
3248 
3249 	if (tdvp != fdvp) {
3250 		VOP_LOCK(tdvp, LK_EXCLUSIVE | LK_RETRY);
3251 		error = softdep_prerename_vnode(ump, tdvp);
3252 		VOP_UNLOCK(tdvp);
3253 		if (error != 0)
3254 			return (error);
3255 	}
3256 
3257 	if (tvp != fvp && tvp != NULL) {
3258 		VOP_LOCK(tvp, LK_EXCLUSIVE | LK_RETRY);
3259 		error = softdep_prerename_vnode(ump, tvp);
3260 		VOP_UNLOCK(tvp);
3261 		if (error != 0)
3262 			return (error);
3263 	}
3264 
3265 	ACQUIRE_LOCK(ump);
3266 	softdep_speedup(ump);
3267 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3268 	journal_check_space(ump);
3269 	FREE_LOCK(ump);
3270 	return (ERELOOKUP);
3271 }
3272 
3273 /*
3274  * Before adjusting a link count on a vnode verify that we have sufficient
3275  * journal space.  If not, process operations that depend on the currently
3276  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3277  * and softdep flush threads can not acquire these locks to reclaim space.
3278  *
3279  * Returns 0 if all owned locks are still valid and were not dropped
3280  * in the process, in other case it returns either an error from sync,
3281  * or ERELOOKUP if any of the locks were re-acquired.  In the later
3282  * case, the state of the vnodes cannot be relied upon and our VFS
3283  * syscall must be restarted at top level from the lookup.
3284  */
3285 int
softdep_prelink(struct vnode * dvp,struct vnode * vp,struct componentname * cnp)3286 softdep_prelink(struct vnode *dvp,
3287 	struct vnode *vp,
3288 	struct componentname *cnp)
3289 {
3290 	struct ufsmount *ump;
3291 	struct nameidata *ndp;
3292 
3293 	ASSERT_VOP_ELOCKED(dvp, "prelink dvp");
3294 	if (vp != NULL)
3295 		ASSERT_VOP_ELOCKED(vp, "prelink vp");
3296 	ump = VFSTOUFS(dvp->v_mount);
3297 
3298 	/*
3299 	 * Nothing to do if we have sufficient journal space.  We skip
3300 	 * flushing when vp is a snapshot to avoid deadlock where
3301 	 * another thread is trying to update the inodeblock for dvp
3302 	 * and is waiting on snaplk that vp holds.
3303 	 */
3304 	if (journal_space(ump, 0) || (vp != NULL && IS_SNAPSHOT(VTOI(vp))))
3305 		return (0);
3306 
3307 	/*
3308 	 * Check if the journal space consumption can in theory be
3309 	 * accounted on dvp and vp.  If the vnodes metadata was not
3310 	 * changed comparing with the previous round-trip into
3311 	 * softdep_prelink(), as indicated by the seqc generation
3312 	 * recorded in the nameidata, then there is no point in
3313 	 * starting the sync.
3314 	 */
3315 	ndp = __containerof(cnp, struct nameidata, ni_cnd);
3316 	if (!seqc_in_modify(ndp->ni_dvp_seqc) &&
3317 	    vn_seqc_consistent(dvp, ndp->ni_dvp_seqc) &&
3318 	    (vp == NULL || (!seqc_in_modify(ndp->ni_vp_seqc) &&
3319 	    vn_seqc_consistent(vp, ndp->ni_vp_seqc))))
3320 		return (0);
3321 
3322 	stat_journal_low++;
3323 	if (vp != NULL) {
3324 		VOP_UNLOCK(dvp);
3325 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3326 		vn_lock_pair(dvp, false, LK_EXCLUSIVE, vp, true, LK_EXCLUSIVE);
3327 		if (dvp->v_data == NULL)
3328 			goto out;
3329 	}
3330 	if (vp != NULL)
3331 		VOP_UNLOCK(vp);
3332 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3333 	/* Process vp before dvp as it may create .. removes. */
3334 	if (vp != NULL) {
3335 		VOP_UNLOCK(dvp);
3336 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3337 		if (vp->v_data == NULL) {
3338 			vn_lock_pair(dvp, false, LK_EXCLUSIVE, vp, true,
3339 			    LK_EXCLUSIVE);
3340 			goto out;
3341 		}
3342 		ACQUIRE_LOCK(ump);
3343 		process_removes(vp);
3344 		process_truncates(vp);
3345 		FREE_LOCK(ump);
3346 		VOP_UNLOCK(vp);
3347 		vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY);
3348 		if (dvp->v_data == NULL) {
3349 			vn_lock_pair(dvp, true, LK_EXCLUSIVE, vp, false,
3350 			    LK_EXCLUSIVE);
3351 			goto out;
3352 		}
3353 	}
3354 
3355 	ACQUIRE_LOCK(ump);
3356 	process_removes(dvp);
3357 	process_truncates(dvp);
3358 	VOP_UNLOCK(dvp);
3359 	softdep_speedup(ump);
3360 
3361 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3362 	journal_check_space(ump);
3363 	FREE_LOCK(ump);
3364 
3365 	vn_lock_pair(dvp, false, LK_EXCLUSIVE, vp, false, LK_EXCLUSIVE);
3366 out:
3367 	ndp->ni_dvp_seqc = vn_seqc_read_any(dvp);
3368 	if (vp != NULL)
3369 		ndp->ni_vp_seqc = vn_seqc_read_any(vp);
3370 	return (ERELOOKUP);
3371 }
3372 
3373 static void
jseg_write(struct ufsmount * ump,struct jseg * jseg,uint8_t * data)3374 jseg_write(struct ufsmount *ump,
3375 	struct jseg *jseg,
3376 	uint8_t *data)
3377 {
3378 	struct jsegrec *rec;
3379 
3380 	rec = (struct jsegrec *)data;
3381 	rec->jsr_seq = jseg->js_seq;
3382 	rec->jsr_oldest = jseg->js_oldseq;
3383 	rec->jsr_cnt = jseg->js_cnt;
3384 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3385 	rec->jsr_crc = 0;
3386 	rec->jsr_time = ump->um_fs->fs_mtime;
3387 }
3388 
3389 static inline void
inoref_write(struct inoref * inoref,struct jseg * jseg,struct jrefrec * rec)3390 inoref_write(struct inoref *inoref,
3391 	struct jseg *jseg,
3392 	struct jrefrec *rec)
3393 {
3394 
3395 	inoref->if_jsegdep->jd_seg = jseg;
3396 	rec->jr_ino = inoref->if_ino;
3397 	rec->jr_parent = inoref->if_parent;
3398 	rec->jr_nlink = inoref->if_nlink;
3399 	rec->jr_mode = inoref->if_mode;
3400 	rec->jr_diroff = inoref->if_diroff;
3401 }
3402 
3403 static void
jaddref_write(struct jaddref * jaddref,struct jseg * jseg,uint8_t * data)3404 jaddref_write(struct jaddref *jaddref,
3405 	struct jseg *jseg,
3406 	uint8_t *data)
3407 {
3408 	struct jrefrec *rec;
3409 
3410 	rec = (struct jrefrec *)data;
3411 	rec->jr_op = JOP_ADDREF;
3412 	inoref_write(&jaddref->ja_ref, jseg, rec);
3413 }
3414 
3415 static void
jremref_write(struct jremref * jremref,struct jseg * jseg,uint8_t * data)3416 jremref_write(struct jremref *jremref,
3417 	struct jseg *jseg,
3418 	uint8_t *data)
3419 {
3420 	struct jrefrec *rec;
3421 
3422 	rec = (struct jrefrec *)data;
3423 	rec->jr_op = JOP_REMREF;
3424 	inoref_write(&jremref->jr_ref, jseg, rec);
3425 }
3426 
3427 static void
jmvref_write(struct jmvref * jmvref,struct jseg * jseg,uint8_t * data)3428 jmvref_write(struct jmvref *jmvref,
3429 	struct jseg *jseg,
3430 	uint8_t *data)
3431 {
3432 	struct jmvrec *rec;
3433 
3434 	rec = (struct jmvrec *)data;
3435 	rec->jm_op = JOP_MVREF;
3436 	rec->jm_ino = jmvref->jm_ino;
3437 	rec->jm_parent = jmvref->jm_parent;
3438 	rec->jm_oldoff = jmvref->jm_oldoff;
3439 	rec->jm_newoff = jmvref->jm_newoff;
3440 }
3441 
3442 static void
jnewblk_write(struct jnewblk * jnewblk,struct jseg * jseg,uint8_t * data)3443 jnewblk_write(struct jnewblk *jnewblk,
3444 	struct jseg *jseg,
3445 	uint8_t *data)
3446 {
3447 	struct jblkrec *rec;
3448 
3449 	jnewblk->jn_jsegdep->jd_seg = jseg;
3450 	rec = (struct jblkrec *)data;
3451 	rec->jb_op = JOP_NEWBLK;
3452 	rec->jb_ino = jnewblk->jn_ino;
3453 	rec->jb_blkno = jnewblk->jn_blkno;
3454 	rec->jb_lbn = jnewblk->jn_lbn;
3455 	rec->jb_frags = jnewblk->jn_frags;
3456 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3457 }
3458 
3459 static void
jfreeblk_write(struct jfreeblk * jfreeblk,struct jseg * jseg,uint8_t * data)3460 jfreeblk_write(struct jfreeblk *jfreeblk,
3461 	struct jseg *jseg,
3462 	uint8_t *data)
3463 {
3464 	struct jblkrec *rec;
3465 
3466 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3467 	rec = (struct jblkrec *)data;
3468 	rec->jb_op = JOP_FREEBLK;
3469 	rec->jb_ino = jfreeblk->jf_ino;
3470 	rec->jb_blkno = jfreeblk->jf_blkno;
3471 	rec->jb_lbn = jfreeblk->jf_lbn;
3472 	rec->jb_frags = jfreeblk->jf_frags;
3473 	rec->jb_oldfrags = 0;
3474 }
3475 
3476 static void
jfreefrag_write(struct jfreefrag * jfreefrag,struct jseg * jseg,uint8_t * data)3477 jfreefrag_write(struct jfreefrag *jfreefrag,
3478 	struct jseg *jseg,
3479 	uint8_t *data)
3480 {
3481 	struct jblkrec *rec;
3482 
3483 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3484 	rec = (struct jblkrec *)data;
3485 	rec->jb_op = JOP_FREEBLK;
3486 	rec->jb_ino = jfreefrag->fr_ino;
3487 	rec->jb_blkno = jfreefrag->fr_blkno;
3488 	rec->jb_lbn = jfreefrag->fr_lbn;
3489 	rec->jb_frags = jfreefrag->fr_frags;
3490 	rec->jb_oldfrags = 0;
3491 }
3492 
3493 static void
jtrunc_write(struct jtrunc * jtrunc,struct jseg * jseg,uint8_t * data)3494 jtrunc_write(struct jtrunc *jtrunc,
3495 	struct jseg *jseg,
3496 	uint8_t *data)
3497 {
3498 	struct jtrncrec *rec;
3499 
3500 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3501 	rec = (struct jtrncrec *)data;
3502 	rec->jt_op = JOP_TRUNC;
3503 	rec->jt_ino = jtrunc->jt_ino;
3504 	rec->jt_size = jtrunc->jt_size;
3505 	rec->jt_extsize = jtrunc->jt_extsize;
3506 }
3507 
3508 static void
jfsync_write(struct jfsync * jfsync,struct jseg * jseg,uint8_t * data)3509 jfsync_write(struct jfsync *jfsync,
3510 	struct jseg *jseg,
3511 	uint8_t *data)
3512 {
3513 	struct jtrncrec *rec;
3514 
3515 	rec = (struct jtrncrec *)data;
3516 	rec->jt_op = JOP_SYNC;
3517 	rec->jt_ino = jfsync->jfs_ino;
3518 	rec->jt_size = jfsync->jfs_size;
3519 	rec->jt_extsize = jfsync->jfs_extsize;
3520 }
3521 
3522 static void
softdep_flushjournal(struct mount * mp)3523 softdep_flushjournal(struct mount *mp)
3524 {
3525 	struct jblocks *jblocks;
3526 	struct ufsmount *ump;
3527 
3528 	if (MOUNTEDSUJ(mp) == 0)
3529 		return;
3530 	ump = VFSTOUFS(mp);
3531 	jblocks = ump->softdep_jblocks;
3532 	ACQUIRE_LOCK(ump);
3533 	while (ump->softdep_on_journal) {
3534 		jblocks->jb_needseg = 1;
3535 		softdep_process_journal(mp, NULL, MNT_WAIT);
3536 	}
3537 	FREE_LOCK(ump);
3538 }
3539 
3540 static void softdep_synchronize_completed(struct bio *);
3541 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3542 
3543 static void
softdep_synchronize_completed(struct bio * bp)3544 softdep_synchronize_completed(struct bio *bp)
3545 {
3546 	struct jseg *oldest;
3547 	struct jseg *jseg;
3548 	struct ufsmount *ump;
3549 
3550 	/*
3551 	 * caller1 marks the last segment written before we issued the
3552 	 * synchronize cache.
3553 	 */
3554 	jseg = bp->bio_caller1;
3555 	if (jseg == NULL) {
3556 		g_destroy_bio(bp);
3557 		return;
3558 	}
3559 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3560 	ACQUIRE_LOCK(ump);
3561 	oldest = NULL;
3562 	/*
3563 	 * Mark all the journal entries waiting on the synchronize cache
3564 	 * as completed so they may continue on.
3565 	 */
3566 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3567 		jseg->js_state |= COMPLETE;
3568 		oldest = jseg;
3569 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3570 	}
3571 	/*
3572 	 * Restart deferred journal entry processing from the oldest
3573 	 * completed jseg.
3574 	 */
3575 	if (oldest)
3576 		complete_jsegs(oldest);
3577 
3578 	FREE_LOCK(ump);
3579 	g_destroy_bio(bp);
3580 }
3581 
3582 /*
3583  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3584  * barriers.  The journal must be written prior to any blocks that depend
3585  * on it and the journal can not be released until the blocks have be
3586  * written.  This code handles both barriers simultaneously.
3587  */
3588 static void
softdep_synchronize(struct bio * bp,struct ufsmount * ump,void * caller1)3589 softdep_synchronize(struct bio *bp,
3590 	struct ufsmount *ump,
3591 	void *caller1)
3592 {
3593 
3594 	bp->bio_cmd = BIO_FLUSH;
3595 	bp->bio_flags |= BIO_ORDERED;
3596 	bp->bio_data = NULL;
3597 	bp->bio_offset = ump->um_cp->provider->mediasize;
3598 	bp->bio_length = 0;
3599 	bp->bio_done = softdep_synchronize_completed;
3600 	bp->bio_caller1 = caller1;
3601 	g_io_request(bp, ump->um_cp);
3602 }
3603 
3604 /*
3605  * Flush some journal records to disk.
3606  */
3607 static void
softdep_process_journal(struct mount * mp,struct worklist * needwk,int flags)3608 softdep_process_journal(struct mount *mp,
3609 	struct worklist *needwk,
3610 	int flags)
3611 {
3612 	struct jblocks *jblocks;
3613 	struct ufsmount *ump;
3614 	struct worklist *wk;
3615 	struct jseg *jseg;
3616 	struct buf *bp;
3617 	struct bio *bio;
3618 	uint8_t *data;
3619 	struct fs *fs;
3620 	int shouldflush;
3621 	int segwritten;
3622 	int jrecmin;	/* Minimum records per block. */
3623 	int jrecmax;	/* Maximum records per block. */
3624 	int size;
3625 	int cnt;
3626 	int off;
3627 	int devbsize;
3628 	int savef;
3629 
3630 	ump = VFSTOUFS(mp);
3631 	if (ump->um_softdep == NULL || ump->um_softdep->sd_jblocks == NULL)
3632 		return;
3633 	shouldflush = softdep_flushcache;
3634 	bio = NULL;
3635 	jseg = NULL;
3636 	LOCK_OWNED(ump);
3637 	fs = ump->um_fs;
3638 	jblocks = ump->softdep_jblocks;
3639 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3640 	savef = curthread_pflags_set(TDP_NORUNNINGBUF);
3641 
3642 	/*
3643 	 * We write anywhere between a disk block and fs block.  The upper
3644 	 * bound is picked to prevent buffer cache fragmentation and limit
3645 	 * processing time per I/O.
3646 	 */
3647 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3648 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3649 	segwritten = 0;
3650 	for (;;) {
3651 		cnt = ump->softdep_on_journal;
3652 		/*
3653 		 * Criteria for writing a segment:
3654 		 * 1) We have a full block.
3655 		 * 2) We're called from jwait() and haven't found the
3656 		 *    journal item yet.
3657 		 * 3) Always write if needseg is set.
3658 		 * 4) If we are called from process_worklist and have
3659 		 *    not yet written anything we write a partial block
3660 		 *    to enforce a 1 second maximum latency on journal
3661 		 *    entries.
3662 		 */
3663 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3664 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3665 			break;
3666 		cnt++;
3667 		/*
3668 		 * Verify some free journal space.  softdep_prealloc() should
3669 		 * guarantee that we don't run out so this is indicative of
3670 		 * a problem with the flow control.  Try to recover
3671 		 * gracefully in any event.
3672 		 */
3673 		while (jblocks->jb_free == 0) {
3674 			if (flags != MNT_WAIT)
3675 				break;
3676 			printf("softdep: Out of journal space!\n");
3677 			softdep_speedup(ump);
3678 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3679 		}
3680 		FREE_LOCK(ump);
3681 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3682 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3683 		LIST_INIT(&jseg->js_entries);
3684 		LIST_INIT(&jseg->js_indirs);
3685 		jseg->js_state = ATTACHED;
3686 		if (shouldflush == 0)
3687 			jseg->js_state |= COMPLETE;
3688 		else if (bio == NULL)
3689 			bio = g_alloc_bio();
3690 		jseg->js_jblocks = jblocks;
3691 		bp = geteblk(fs->fs_bsize, 0);
3692 		ACQUIRE_LOCK(ump);
3693 		/*
3694 		 * If there was a race while we were allocating the block
3695 		 * and jseg the entry we care about was likely written.
3696 		 * We bail out in both the WAIT and NOWAIT case and assume
3697 		 * the caller will loop if the entry it cares about is
3698 		 * not written.
3699 		 */
3700 		cnt = ump->softdep_on_journal;
3701 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3702 			bp->b_flags |= B_INVAL | B_NOCACHE;
3703 			WORKITEM_FREE(jseg, D_JSEG);
3704 			FREE_LOCK(ump);
3705 			brelse(bp);
3706 			ACQUIRE_LOCK(ump);
3707 			break;
3708 		}
3709 		/*
3710 		 * Calculate the disk block size required for the available
3711 		 * records rounded to the min size.
3712 		 */
3713 		if (cnt == 0)
3714 			size = devbsize;
3715 		else if (cnt < jrecmax)
3716 			size = howmany(cnt, jrecmin) * devbsize;
3717 		else
3718 			size = fs->fs_bsize;
3719 		/*
3720 		 * Allocate a disk block for this journal data and account
3721 		 * for truncation of the requested size if enough contiguous
3722 		 * space was not available.
3723 		 */
3724 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3725 		bp->b_lblkno = bp->b_blkno;
3726 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3727 		bp->b_bcount = size;
3728 		bp->b_flags &= ~B_INVAL;
3729 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3730 		/*
3731 		 * Initialize our jseg with cnt records.  Assign the next
3732 		 * sequence number to it and link it in-order.
3733 		 */
3734 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3735 		jseg->js_buf = bp;
3736 		jseg->js_cnt = cnt;
3737 		jseg->js_refs = cnt + 1;	/* Self ref. */
3738 		jseg->js_size = size;
3739 		jseg->js_seq = jblocks->jb_nextseq++;
3740 		if (jblocks->jb_oldestseg == NULL)
3741 			jblocks->jb_oldestseg = jseg;
3742 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3743 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3744 		if (jblocks->jb_writeseg == NULL)
3745 			jblocks->jb_writeseg = jseg;
3746 		/*
3747 		 * Start filling in records from the pending list.
3748 		 */
3749 		data = bp->b_data;
3750 		off = 0;
3751 
3752 		/*
3753 		 * Always put a header on the first block.
3754 		 * XXX As with below, there might not be a chance to get
3755 		 * into the loop.  Ensure that something valid is written.
3756 		 */
3757 		jseg_write(ump, jseg, data);
3758 		off += JREC_SIZE;
3759 		data = bp->b_data + off;
3760 
3761 		/*
3762 		 * XXX Something is wrong here.  There's no work to do,
3763 		 * but we need to perform and I/O and allow it to complete
3764 		 * anyways.
3765 		 */
3766 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3767 			stat_emptyjblocks++;
3768 
3769 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3770 		    != NULL) {
3771 			if (cnt == 0)
3772 				break;
3773 			/* Place a segment header on every device block. */
3774 			if ((off % devbsize) == 0) {
3775 				jseg_write(ump, jseg, data);
3776 				off += JREC_SIZE;
3777 				data = bp->b_data + off;
3778 			}
3779 			if (wk == needwk)
3780 				needwk = NULL;
3781 			remove_from_journal(wk);
3782 			wk->wk_state |= INPROGRESS;
3783 			WORKLIST_INSERT(&jseg->js_entries, wk);
3784 			switch (wk->wk_type) {
3785 			case D_JADDREF:
3786 				jaddref_write(WK_JADDREF(wk), jseg, data);
3787 				break;
3788 			case D_JREMREF:
3789 				jremref_write(WK_JREMREF(wk), jseg, data);
3790 				break;
3791 			case D_JMVREF:
3792 				jmvref_write(WK_JMVREF(wk), jseg, data);
3793 				break;
3794 			case D_JNEWBLK:
3795 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3796 				break;
3797 			case D_JFREEBLK:
3798 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3799 				break;
3800 			case D_JFREEFRAG:
3801 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3802 				break;
3803 			case D_JTRUNC:
3804 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3805 				break;
3806 			case D_JFSYNC:
3807 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3808 				break;
3809 			default:
3810 				panic("process_journal: Unknown type %s",
3811 				    TYPENAME(wk->wk_type));
3812 				/* NOTREACHED */
3813 			}
3814 			off += JREC_SIZE;
3815 			data = bp->b_data + off;
3816 			cnt--;
3817 		}
3818 
3819 		/* Clear any remaining space so we don't leak kernel data */
3820 		if (size > off)
3821 			bzero(data, size - off);
3822 
3823 		/*
3824 		 * Write this one buffer and continue.
3825 		 */
3826 		segwritten = 1;
3827 		jblocks->jb_needseg = 0;
3828 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3829 		FREE_LOCK(ump);
3830 		bp->b_xflags |= BX_CVTENXIO;
3831 		pbgetvp(ump->um_devvp, bp);
3832 		/*
3833 		 * We only do the blocking wait once we find the journal
3834 		 * entry we're looking for.
3835 		 */
3836 		if (needwk == NULL && flags == MNT_WAIT)
3837 			bwrite(bp);
3838 		else
3839 			bawrite(bp);
3840 		ACQUIRE_LOCK(ump);
3841 	}
3842 	/*
3843 	 * If we wrote a segment issue a synchronize cache so the journal
3844 	 * is reflected on disk before the data is written.  Since reclaiming
3845 	 * journal space also requires writing a journal record this
3846 	 * process also enforces a barrier before reclamation.
3847 	 */
3848 	if (segwritten && shouldflush) {
3849 		softdep_synchronize(bio, ump,
3850 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3851 	} else if (bio)
3852 		g_destroy_bio(bio);
3853 	/*
3854 	 * If we've suspended the filesystem because we ran out of journal
3855 	 * space either try to sync it here to make some progress or
3856 	 * unsuspend it if we already have.
3857 	 */
3858 	if (flags == 0 && jblocks->jb_suspended) {
3859 		if (journal_unsuspend(ump))
3860 			goto out;
3861 		FREE_LOCK(ump);
3862 		VFS_SYNC(mp, MNT_NOWAIT);
3863 		ffs_sbupdate(ump, MNT_WAIT, 0);
3864 		ACQUIRE_LOCK(ump);
3865 	}
3866 
3867 out:
3868 	curthread_pflags_restore(savef);
3869 }
3870 
3871 /*
3872  * Complete a jseg, allowing all dependencies awaiting journal writes
3873  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3874  * structures so that the journal segment can be freed to reclaim space.
3875  */
3876 static void
complete_jseg(struct jseg * jseg)3877 complete_jseg(struct jseg *jseg)
3878 {
3879 	struct worklist *wk;
3880 	struct jmvref *jmvref;
3881 #ifdef INVARIANTS
3882 	int i = 0;
3883 #endif
3884 
3885 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3886 		WORKLIST_REMOVE(wk);
3887 		wk->wk_state &= ~INPROGRESS;
3888 		wk->wk_state |= COMPLETE;
3889 		KASSERT(i++ < jseg->js_cnt,
3890 		    ("handle_written_jseg: overflow %d >= %d",
3891 		    i - 1, jseg->js_cnt));
3892 		switch (wk->wk_type) {
3893 		case D_JADDREF:
3894 			handle_written_jaddref(WK_JADDREF(wk));
3895 			break;
3896 		case D_JREMREF:
3897 			handle_written_jremref(WK_JREMREF(wk));
3898 			break;
3899 		case D_JMVREF:
3900 			rele_jseg(jseg);	/* No jsegdep. */
3901 			jmvref = WK_JMVREF(wk);
3902 			LIST_REMOVE(jmvref, jm_deps);
3903 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3904 				free_pagedep(jmvref->jm_pagedep);
3905 			WORKITEM_FREE(jmvref, D_JMVREF);
3906 			break;
3907 		case D_JNEWBLK:
3908 			handle_written_jnewblk(WK_JNEWBLK(wk));
3909 			break;
3910 		case D_JFREEBLK:
3911 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3912 			break;
3913 		case D_JTRUNC:
3914 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3915 			break;
3916 		case D_JFSYNC:
3917 			rele_jseg(jseg);	/* No jsegdep. */
3918 			WORKITEM_FREE(wk, D_JFSYNC);
3919 			break;
3920 		case D_JFREEFRAG:
3921 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
3922 			break;
3923 		default:
3924 			panic("handle_written_jseg: Unknown type %s",
3925 			    TYPENAME(wk->wk_type));
3926 			/* NOTREACHED */
3927 		}
3928 	}
3929 	/* Release the self reference so the structure may be freed. */
3930 	rele_jseg(jseg);
3931 }
3932 
3933 /*
3934  * Determine which jsegs are ready for completion processing.  Waits for
3935  * synchronize cache to complete as well as forcing in-order completion
3936  * of journal entries.
3937  */
3938 static void
complete_jsegs(struct jseg * jseg)3939 complete_jsegs(struct jseg *jseg)
3940 {
3941 	struct jblocks *jblocks;
3942 	struct jseg *jsegn;
3943 
3944 	jblocks = jseg->js_jblocks;
3945 	/*
3946 	 * Don't allow out of order completions.  If this isn't the first
3947 	 * block wait for it to write before we're done.
3948 	 */
3949 	if (jseg != jblocks->jb_writeseg)
3950 		return;
3951 	/* Iterate through available jsegs processing their entries. */
3952 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3953 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
3954 		jsegn = TAILQ_NEXT(jseg, js_next);
3955 		complete_jseg(jseg);
3956 		jseg = jsegn;
3957 	}
3958 	jblocks->jb_writeseg = jseg;
3959 	/*
3960 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
3961 	 */
3962 	free_jsegs(jblocks);
3963 }
3964 
3965 /*
3966  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3967  * the final completions.
3968  */
3969 static void
handle_written_jseg(struct jseg * jseg,struct buf * bp)3970 handle_written_jseg(struct jseg *jseg, struct buf *bp)
3971 {
3972 
3973 	if (jseg->js_refs == 0)
3974 		panic("handle_written_jseg: No self-reference on %p", jseg);
3975 	jseg->js_state |= DEPCOMPLETE;
3976 	/*
3977 	 * We'll never need this buffer again, set flags so it will be
3978 	 * discarded.
3979 	 */
3980 	bp->b_flags |= B_INVAL | B_NOCACHE;
3981 	pbrelvp(bp);
3982 	complete_jsegs(jseg);
3983 }
3984 
3985 static inline struct jsegdep *
inoref_jseg(struct inoref * inoref)3986 inoref_jseg(struct inoref *inoref)
3987 {
3988 	struct jsegdep *jsegdep;
3989 
3990 	jsegdep = inoref->if_jsegdep;
3991 	inoref->if_jsegdep = NULL;
3992 
3993 	return (jsegdep);
3994 }
3995 
3996 /*
3997  * Called once a jremref has made it to stable store.  The jremref is marked
3998  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3999  * for the jremref to complete will be awoken by free_jremref.
4000  */
4001 static void
handle_written_jremref(struct jremref * jremref)4002 handle_written_jremref(struct jremref *jremref)
4003 {
4004 	struct inodedep *inodedep;
4005 	struct jsegdep *jsegdep;
4006 	struct dirrem *dirrem;
4007 
4008 	/* Grab the jsegdep. */
4009 	jsegdep = inoref_jseg(&jremref->jr_ref);
4010 	/*
4011 	 * Remove us from the inoref list.
4012 	 */
4013 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
4014 	    0, &inodedep) == 0)
4015 		panic("handle_written_jremref: Lost inodedep");
4016 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
4017 	/*
4018 	 * Complete the dirrem.
4019 	 */
4020 	dirrem = jremref->jr_dirrem;
4021 	jremref->jr_dirrem = NULL;
4022 	LIST_REMOVE(jremref, jr_deps);
4023 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
4024 	jwork_insert(&dirrem->dm_jwork, jsegdep);
4025 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
4026 	    (dirrem->dm_state & COMPLETE) != 0)
4027 		add_to_worklist(&dirrem->dm_list, 0);
4028 	free_jremref(jremref);
4029 }
4030 
4031 /*
4032  * Called once a jaddref has made it to stable store.  The dependency is
4033  * marked complete and any dependent structures are added to the inode
4034  * bufwait list to be completed as soon as it is written.  If a bitmap write
4035  * depends on this entry we move the inode into the inodedephd of the
4036  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
4037  */
4038 static void
handle_written_jaddref(struct jaddref * jaddref)4039 handle_written_jaddref(struct jaddref *jaddref)
4040 {
4041 	struct jsegdep *jsegdep;
4042 	struct inodedep *inodedep;
4043 	struct diradd *diradd;
4044 	struct mkdir *mkdir;
4045 
4046 	/* Grab the jsegdep. */
4047 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4048 	mkdir = NULL;
4049 	diradd = NULL;
4050 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4051 	    0, &inodedep) == 0)
4052 		panic("handle_written_jaddref: Lost inodedep.");
4053 	if (jaddref->ja_diradd == NULL)
4054 		panic("handle_written_jaddref: No dependency");
4055 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
4056 		diradd = jaddref->ja_diradd;
4057 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
4058 	} else if (jaddref->ja_state & MKDIR_PARENT) {
4059 		mkdir = jaddref->ja_mkdir;
4060 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
4061 	} else if (jaddref->ja_state & MKDIR_BODY)
4062 		mkdir = jaddref->ja_mkdir;
4063 	else
4064 		panic("handle_written_jaddref: Unknown dependency %p",
4065 		    jaddref->ja_diradd);
4066 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
4067 	/*
4068 	 * Remove us from the inode list.
4069 	 */
4070 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
4071 	/*
4072 	 * The mkdir may be waiting on the jaddref to clear before freeing.
4073 	 */
4074 	if (mkdir) {
4075 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
4076 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
4077 		    TYPENAME(mkdir->md_list.wk_type)));
4078 		mkdir->md_jaddref = NULL;
4079 		diradd = mkdir->md_diradd;
4080 		mkdir->md_state |= DEPCOMPLETE;
4081 		complete_mkdir(mkdir);
4082 	}
4083 	jwork_insert(&diradd->da_jwork, jsegdep);
4084 	if (jaddref->ja_state & NEWBLOCK) {
4085 		inodedep->id_state |= ONDEPLIST;
4086 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
4087 		    inodedep, id_deps);
4088 	}
4089 	free_jaddref(jaddref);
4090 }
4091 
4092 /*
4093  * Called once a jnewblk journal is written.  The allocdirect or allocindir
4094  * is placed in the bmsafemap to await notification of a written bitmap.  If
4095  * the operation was canceled we add the segdep to the appropriate
4096  * dependency to free the journal space once the canceling operation
4097  * completes.
4098  */
4099 static void
handle_written_jnewblk(struct jnewblk * jnewblk)4100 handle_written_jnewblk(struct jnewblk *jnewblk)
4101 {
4102 	struct bmsafemap *bmsafemap;
4103 	struct freefrag *freefrag;
4104 	struct freework *freework;
4105 	struct jsegdep *jsegdep;
4106 	struct newblk *newblk;
4107 
4108 	/* Grab the jsegdep. */
4109 	jsegdep = jnewblk->jn_jsegdep;
4110 	jnewblk->jn_jsegdep = NULL;
4111 	if (jnewblk->jn_dep == NULL)
4112 		panic("handle_written_jnewblk: No dependency for the segdep.");
4113 	switch (jnewblk->jn_dep->wk_type) {
4114 	case D_NEWBLK:
4115 	case D_ALLOCDIRECT:
4116 	case D_ALLOCINDIR:
4117 		/*
4118 		 * Add the written block to the bmsafemap so it can
4119 		 * be notified when the bitmap is on disk.
4120 		 */
4121 		newblk = WK_NEWBLK(jnewblk->jn_dep);
4122 		newblk->nb_jnewblk = NULL;
4123 		if ((newblk->nb_state & GOINGAWAY) == 0) {
4124 			bmsafemap = newblk->nb_bmsafemap;
4125 			newblk->nb_state |= ONDEPLIST;
4126 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
4127 			    nb_deps);
4128 		}
4129 		jwork_insert(&newblk->nb_jwork, jsegdep);
4130 		break;
4131 	case D_FREEFRAG:
4132 		/*
4133 		 * A newblock being removed by a freefrag when replaced by
4134 		 * frag extension.
4135 		 */
4136 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
4137 		freefrag->ff_jdep = NULL;
4138 		jwork_insert(&freefrag->ff_jwork, jsegdep);
4139 		break;
4140 	case D_FREEWORK:
4141 		/*
4142 		 * A direct block was removed by truncate.
4143 		 */
4144 		freework = WK_FREEWORK(jnewblk->jn_dep);
4145 		freework->fw_jnewblk = NULL;
4146 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
4147 		break;
4148 	default:
4149 		panic("handle_written_jnewblk: Unknown type %d.",
4150 		    jnewblk->jn_dep->wk_type);
4151 	}
4152 	jnewblk->jn_dep = NULL;
4153 	free_jnewblk(jnewblk);
4154 }
4155 
4156 /*
4157  * Cancel a jfreefrag that won't be needed, probably due to colliding with
4158  * an in-flight allocation that has not yet been committed.  Divorce us
4159  * from the freefrag and mark it DEPCOMPLETE so that it may be added
4160  * to the worklist.
4161  */
4162 static void
cancel_jfreefrag(struct jfreefrag * jfreefrag)4163 cancel_jfreefrag(struct jfreefrag *jfreefrag)
4164 {
4165 	struct freefrag *freefrag;
4166 
4167 	if (jfreefrag->fr_jsegdep) {
4168 		free_jsegdep(jfreefrag->fr_jsegdep);
4169 		jfreefrag->fr_jsegdep = NULL;
4170 	}
4171 	freefrag = jfreefrag->fr_freefrag;
4172 	jfreefrag->fr_freefrag = NULL;
4173 	free_jfreefrag(jfreefrag);
4174 	freefrag->ff_state |= DEPCOMPLETE;
4175 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
4176 }
4177 
4178 /*
4179  * Free a jfreefrag when the parent freefrag is rendered obsolete.
4180  */
4181 static void
free_jfreefrag(struct jfreefrag * jfreefrag)4182 free_jfreefrag(struct jfreefrag *jfreefrag)
4183 {
4184 
4185 	if (jfreefrag->fr_state & INPROGRESS)
4186 		WORKLIST_REMOVE(&jfreefrag->fr_list);
4187 	else if (jfreefrag->fr_state & ONWORKLIST)
4188 		remove_from_journal(&jfreefrag->fr_list);
4189 	if (jfreefrag->fr_freefrag != NULL)
4190 		panic("free_jfreefrag:  Still attached to a freefrag.");
4191 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
4192 }
4193 
4194 /*
4195  * Called when the journal write for a jfreefrag completes.  The parent
4196  * freefrag is added to the worklist if this completes its dependencies.
4197  */
4198 static void
handle_written_jfreefrag(struct jfreefrag * jfreefrag)4199 handle_written_jfreefrag(struct jfreefrag *jfreefrag)
4200 {
4201 	struct jsegdep *jsegdep;
4202 	struct freefrag *freefrag;
4203 
4204 	/* Grab the jsegdep. */
4205 	jsegdep = jfreefrag->fr_jsegdep;
4206 	jfreefrag->fr_jsegdep = NULL;
4207 	freefrag = jfreefrag->fr_freefrag;
4208 	if (freefrag == NULL)
4209 		panic("handle_written_jfreefrag: No freefrag.");
4210 	freefrag->ff_state |= DEPCOMPLETE;
4211 	freefrag->ff_jdep = NULL;
4212 	jwork_insert(&freefrag->ff_jwork, jsegdep);
4213 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
4214 		add_to_worklist(&freefrag->ff_list, 0);
4215 	jfreefrag->fr_freefrag = NULL;
4216 	free_jfreefrag(jfreefrag);
4217 }
4218 
4219 /*
4220  * Called when the journal write for a jfreeblk completes.  The jfreeblk
4221  * is removed from the freeblks list of pending journal writes and the
4222  * jsegdep is moved to the freeblks jwork to be completed when all blocks
4223  * have been reclaimed.
4224  */
4225 static void
handle_written_jblkdep(struct jblkdep * jblkdep)4226 handle_written_jblkdep(struct jblkdep *jblkdep)
4227 {
4228 	struct freeblks *freeblks;
4229 	struct jsegdep *jsegdep;
4230 
4231 	/* Grab the jsegdep. */
4232 	jsegdep = jblkdep->jb_jsegdep;
4233 	jblkdep->jb_jsegdep = NULL;
4234 	freeblks = jblkdep->jb_freeblks;
4235 	LIST_REMOVE(jblkdep, jb_deps);
4236 	jwork_insert(&freeblks->fb_jwork, jsegdep);
4237 	/*
4238 	 * If the freeblks is all journaled, we can add it to the worklist.
4239 	 */
4240 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
4241 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
4242 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
4243 
4244 	free_jblkdep(jblkdep);
4245 }
4246 
4247 static struct jsegdep *
newjsegdep(struct worklist * wk)4248 newjsegdep(struct worklist *wk)
4249 {
4250 	struct jsegdep *jsegdep;
4251 
4252 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
4253 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
4254 	jsegdep->jd_seg = NULL;
4255 
4256 	return (jsegdep);
4257 }
4258 
4259 static struct jmvref *
newjmvref(struct inode * dp,ino_t ino,off_t oldoff,off_t newoff)4260 newjmvref(struct inode *dp,
4261 	ino_t ino,
4262 	off_t oldoff,
4263 	off_t newoff)
4264 {
4265 	struct jmvref *jmvref;
4266 
4267 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4268 	workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4269 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4270 	jmvref->jm_parent = dp->i_number;
4271 	jmvref->jm_ino = ino;
4272 	jmvref->jm_oldoff = oldoff;
4273 	jmvref->jm_newoff = newoff;
4274 
4275 	return (jmvref);
4276 }
4277 
4278 /*
4279  * Allocate a new jremref that tracks the removal of ip from dp with the
4280  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4281  * DEPCOMPLETE as we have all the information required for the journal write
4282  * and the directory has already been removed from the buffer.  The caller
4283  * is responsible for linking the jremref into the pagedep and adding it
4284  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4285  * a DOTDOT addition so handle_workitem_remove() can properly assign
4286  * the jsegdep when we're done.
4287  */
4288 static struct jremref *
newjremref(struct dirrem * dirrem,struct inode * dp,struct inode * ip,off_t diroff,nlink_t nlink)4289 newjremref(struct dirrem *dirrem,
4290 	struct inode *dp,
4291 	struct inode *ip,
4292 	off_t diroff,
4293 	nlink_t nlink)
4294 {
4295 	struct jremref *jremref;
4296 
4297 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4298 	workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4299 	jremref->jr_state = ATTACHED;
4300 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4301 	   nlink, ip->i_mode);
4302 	jremref->jr_dirrem = dirrem;
4303 
4304 	return (jremref);
4305 }
4306 
4307 static inline void
newinoref(struct inoref * inoref,ino_t ino,ino_t parent,off_t diroff,nlink_t nlink,uint16_t mode)4308 newinoref(struct inoref *inoref,
4309 	ino_t ino,
4310 	ino_t parent,
4311 	off_t diroff,
4312 	nlink_t nlink,
4313 	uint16_t mode)
4314 {
4315 
4316 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4317 	inoref->if_diroff = diroff;
4318 	inoref->if_ino = ino;
4319 	inoref->if_parent = parent;
4320 	inoref->if_nlink = nlink;
4321 	inoref->if_mode = mode;
4322 }
4323 
4324 /*
4325  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4326  * directory offset may not be known until later.  The caller is responsible
4327  * adding the entry to the journal when this information is available.  nlink
4328  * should be the link count prior to the addition and mode is only required
4329  * to have the correct FMT.
4330  */
4331 static struct jaddref *
newjaddref(struct inode * dp,ino_t ino,off_t diroff,int16_t nlink,uint16_t mode)4332 newjaddref(struct inode *dp,
4333 	ino_t ino,
4334 	off_t diroff,
4335 	int16_t nlink,
4336 	uint16_t mode)
4337 {
4338 	struct jaddref *jaddref;
4339 
4340 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4341 	workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4342 	jaddref->ja_state = ATTACHED;
4343 	jaddref->ja_mkdir = NULL;
4344 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4345 
4346 	return (jaddref);
4347 }
4348 
4349 /*
4350  * Create a new free dependency for a freework.  The caller is responsible
4351  * for adjusting the reference count when it has the lock held.  The freedep
4352  * will track an outstanding bitmap write that will ultimately clear the
4353  * freework to continue.
4354  */
4355 static struct freedep *
newfreedep(struct freework * freework)4356 newfreedep(struct freework *freework)
4357 {
4358 	struct freedep *freedep;
4359 
4360 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4361 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4362 	freedep->fd_freework = freework;
4363 
4364 	return (freedep);
4365 }
4366 
4367 /*
4368  * Free a freedep structure once the buffer it is linked to is written.  If
4369  * this is the last reference to the freework schedule it for completion.
4370  */
4371 static void
free_freedep(struct freedep * freedep)4372 free_freedep(struct freedep *freedep)
4373 {
4374 	struct freework *freework;
4375 
4376 	freework = freedep->fd_freework;
4377 	freework->fw_freeblks->fb_cgwait--;
4378 	if (--freework->fw_ref == 0)
4379 		freework_enqueue(freework);
4380 	WORKITEM_FREE(freedep, D_FREEDEP);
4381 }
4382 
4383 /*
4384  * Allocate a new freework structure that may be a level in an indirect
4385  * when parent is not NULL or a top level block when it is.  The top level
4386  * freework structures are allocated without the per-filesystem lock held
4387  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4388  */
4389 static struct freework *
newfreework(struct ufsmount * ump,struct freeblks * freeblks,struct freework * parent,ufs_lbn_t lbn,ufs2_daddr_t nb,int frags,int off,int journal)4390 newfreework(struct ufsmount *ump,
4391 	struct freeblks *freeblks,
4392 	struct freework *parent,
4393 	ufs_lbn_t lbn,
4394 	ufs2_daddr_t nb,
4395 	int frags,
4396 	int off,
4397 	int journal)
4398 {
4399 	struct freework *freework;
4400 
4401 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4402 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4403 	freework->fw_state = ATTACHED;
4404 	freework->fw_jnewblk = NULL;
4405 	freework->fw_freeblks = freeblks;
4406 	freework->fw_parent = parent;
4407 	freework->fw_lbn = lbn;
4408 	freework->fw_blkno = nb;
4409 	freework->fw_frags = frags;
4410 	freework->fw_indir = NULL;
4411 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4412 	    lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4413 	freework->fw_start = freework->fw_off = off;
4414 	if (journal)
4415 		newjfreeblk(freeblks, lbn, nb, frags);
4416 	if (parent == NULL) {
4417 		ACQUIRE_LOCK(ump);
4418 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4419 		freeblks->fb_ref++;
4420 		FREE_LOCK(ump);
4421 	}
4422 
4423 	return (freework);
4424 }
4425 
4426 /*
4427  * Eliminate a jfreeblk for a block that does not need journaling.
4428  */
4429 static void
cancel_jfreeblk(struct freeblks * freeblks,ufs2_daddr_t blkno)4430 cancel_jfreeblk(struct freeblks *freeblks, ufs2_daddr_t blkno)
4431 {
4432 	struct jfreeblk *jfreeblk;
4433 	struct jblkdep *jblkdep;
4434 
4435 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4436 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4437 			continue;
4438 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4439 		if (jfreeblk->jf_blkno == blkno)
4440 			break;
4441 	}
4442 	if (jblkdep == NULL)
4443 		return;
4444 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4445 	free_jsegdep(jblkdep->jb_jsegdep);
4446 	LIST_REMOVE(jblkdep, jb_deps);
4447 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4448 }
4449 
4450 /*
4451  * Allocate a new jfreeblk to journal top level block pointer when truncating
4452  * a file.  The caller must add this to the worklist when the per-filesystem
4453  * lock is held.
4454  */
4455 static struct jfreeblk *
newjfreeblk(struct freeblks * freeblks,ufs_lbn_t lbn,ufs2_daddr_t blkno,int frags)4456 newjfreeblk(struct freeblks *freeblks,
4457 	ufs_lbn_t lbn,
4458 	ufs2_daddr_t blkno,
4459 	int frags)
4460 {
4461 	struct jfreeblk *jfreeblk;
4462 
4463 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4464 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4465 	    freeblks->fb_list.wk_mp);
4466 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4467 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4468 	jfreeblk->jf_ino = freeblks->fb_inum;
4469 	jfreeblk->jf_lbn = lbn;
4470 	jfreeblk->jf_blkno = blkno;
4471 	jfreeblk->jf_frags = frags;
4472 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4473 
4474 	return (jfreeblk);
4475 }
4476 
4477 /*
4478  * The journal is only prepared to handle full-size block numbers, so we
4479  * have to adjust the record to reflect the change to a full-size block.
4480  * For example, suppose we have a block made up of fragments 8-15 and
4481  * want to free its last two fragments. We are given a request that says:
4482  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4483  * where frags are the number of fragments to free and oldfrags are the
4484  * number of fragments to keep. To block align it, we have to change it to
4485  * have a valid full-size blkno, so it becomes:
4486  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4487  */
4488 static void
adjust_newfreework(struct freeblks * freeblks,int frag_offset)4489 adjust_newfreework(struct freeblks *freeblks, int frag_offset)
4490 {
4491 	struct jfreeblk *jfreeblk;
4492 
4493 	KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4494 	    LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4495 	    ("adjust_newfreework: Missing freeblks dependency"));
4496 
4497 	jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4498 	jfreeblk->jf_blkno -= frag_offset;
4499 	jfreeblk->jf_frags += frag_offset;
4500 }
4501 
4502 /*
4503  * Allocate a new jtrunc to track a partial truncation.
4504  */
4505 static struct jtrunc *
newjtrunc(struct freeblks * freeblks,off_t size,int extsize)4506 newjtrunc(struct freeblks *freeblks,
4507 	off_t size,
4508 	int extsize)
4509 {
4510 	struct jtrunc *jtrunc;
4511 
4512 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4513 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4514 	    freeblks->fb_list.wk_mp);
4515 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4516 	jtrunc->jt_dep.jb_freeblks = freeblks;
4517 	jtrunc->jt_ino = freeblks->fb_inum;
4518 	jtrunc->jt_size = size;
4519 	jtrunc->jt_extsize = extsize;
4520 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4521 
4522 	return (jtrunc);
4523 }
4524 
4525 /*
4526  * If we're canceling a new bitmap we have to search for another ref
4527  * to move into the bmsafemap dep.  This might be better expressed
4528  * with another structure.
4529  */
4530 static void
move_newblock_dep(struct jaddref * jaddref,struct inodedep * inodedep)4531 move_newblock_dep(struct jaddref *jaddref, struct inodedep *inodedep)
4532 {
4533 	struct inoref *inoref;
4534 	struct jaddref *jaddrefn;
4535 
4536 	jaddrefn = NULL;
4537 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4538 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4539 		if ((jaddref->ja_state & NEWBLOCK) &&
4540 		    inoref->if_list.wk_type == D_JADDREF) {
4541 			jaddrefn = (struct jaddref *)inoref;
4542 			break;
4543 		}
4544 	}
4545 	if (jaddrefn == NULL)
4546 		return;
4547 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4548 	jaddrefn->ja_state |= jaddref->ja_state &
4549 	    (ATTACHED | UNDONE | NEWBLOCK);
4550 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4551 	jaddref->ja_state |= ATTACHED;
4552 	LIST_REMOVE(jaddref, ja_bmdeps);
4553 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4554 	    ja_bmdeps);
4555 }
4556 
4557 /*
4558  * Cancel a jaddref either before it has been written or while it is being
4559  * written.  This happens when a link is removed before the add reaches
4560  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4561  * and inode to prevent the link count or bitmap from reaching the disk
4562  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4563  * required.
4564  *
4565  * Returns 1 if the canceled addref requires journaling of the remove and
4566  * 0 otherwise.
4567  */
4568 static int
cancel_jaddref(struct jaddref * jaddref,struct inodedep * inodedep,struct workhead * wkhd)4569 cancel_jaddref(struct jaddref *jaddref,
4570 	struct inodedep *inodedep,
4571 	struct workhead *wkhd)
4572 {
4573 	struct inoref *inoref;
4574 	struct jsegdep *jsegdep;
4575 	int needsj;
4576 
4577 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4578 	    ("cancel_jaddref: Canceling complete jaddref"));
4579 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4580 		needsj = 1;
4581 	else
4582 		needsj = 0;
4583 	if (inodedep == NULL)
4584 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4585 		    0, &inodedep) == 0)
4586 			panic("cancel_jaddref: Lost inodedep");
4587 	/*
4588 	 * We must adjust the nlink of any reference operation that follows
4589 	 * us so that it is consistent with the in-memory reference.  This
4590 	 * ensures that inode nlink rollbacks always have the correct link.
4591 	 */
4592 	if (needsj == 0) {
4593 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4594 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4595 			if (inoref->if_state & GOINGAWAY)
4596 				break;
4597 			inoref->if_nlink--;
4598 		}
4599 	}
4600 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4601 	if (jaddref->ja_state & NEWBLOCK)
4602 		move_newblock_dep(jaddref, inodedep);
4603 	wake_worklist(&jaddref->ja_list);
4604 	jaddref->ja_mkdir = NULL;
4605 	if (jaddref->ja_state & INPROGRESS) {
4606 		jaddref->ja_state &= ~INPROGRESS;
4607 		WORKLIST_REMOVE(&jaddref->ja_list);
4608 		jwork_insert(wkhd, jsegdep);
4609 	} else {
4610 		free_jsegdep(jsegdep);
4611 		if (jaddref->ja_state & DEPCOMPLETE)
4612 			remove_from_journal(&jaddref->ja_list);
4613 	}
4614 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4615 	/*
4616 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4617 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4618 	 * no longer need this addref attached to the inoreflst and it
4619 	 * will incorrectly adjust nlink if we leave it.
4620 	 */
4621 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4622 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4623 		    if_deps);
4624 		jaddref->ja_state |= COMPLETE;
4625 		free_jaddref(jaddref);
4626 		return (needsj);
4627 	}
4628 	/*
4629 	 * Leave the head of the list for jsegdeps for fast merging.
4630 	 */
4631 	if (LIST_FIRST(wkhd) != NULL) {
4632 		jaddref->ja_state |= ONWORKLIST;
4633 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4634 	} else
4635 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4636 
4637 	return (needsj);
4638 }
4639 
4640 /*
4641  * Attempt to free a jaddref structure when some work completes.  This
4642  * should only succeed once the entry is written and all dependencies have
4643  * been notified.
4644  */
4645 static void
free_jaddref(struct jaddref * jaddref)4646 free_jaddref(struct jaddref *jaddref)
4647 {
4648 
4649 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4650 		return;
4651 	if (jaddref->ja_ref.if_jsegdep)
4652 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4653 		    jaddref, jaddref->ja_state);
4654 	if (jaddref->ja_state & NEWBLOCK)
4655 		LIST_REMOVE(jaddref, ja_bmdeps);
4656 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4657 		panic("free_jaddref: Bad state %p(0x%X)",
4658 		    jaddref, jaddref->ja_state);
4659 	if (jaddref->ja_mkdir != NULL)
4660 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4661 	WORKITEM_FREE(jaddref, D_JADDREF);
4662 }
4663 
4664 /*
4665  * Free a jremref structure once it has been written or discarded.
4666  */
4667 static void
free_jremref(struct jremref * jremref)4668 free_jremref(struct jremref *jremref)
4669 {
4670 
4671 	if (jremref->jr_ref.if_jsegdep)
4672 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4673 	if (jremref->jr_state & INPROGRESS)
4674 		panic("free_jremref: IO still pending");
4675 	WORKITEM_FREE(jremref, D_JREMREF);
4676 }
4677 
4678 /*
4679  * Free a jnewblk structure.
4680  */
4681 static void
free_jnewblk(struct jnewblk * jnewblk)4682 free_jnewblk(struct jnewblk *jnewblk)
4683 {
4684 
4685 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4686 		return;
4687 	LIST_REMOVE(jnewblk, jn_deps);
4688 	if (jnewblk->jn_dep != NULL)
4689 		panic("free_jnewblk: Dependency still attached.");
4690 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4691 }
4692 
4693 /*
4694  * Cancel a jnewblk which has been been made redundant by frag extension.
4695  */
4696 static void
cancel_jnewblk(struct jnewblk * jnewblk,struct workhead * wkhd)4697 cancel_jnewblk(struct jnewblk *jnewblk, struct workhead *wkhd)
4698 {
4699 	struct jsegdep *jsegdep;
4700 
4701 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4702 	jsegdep = jnewblk->jn_jsegdep;
4703 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4704 		panic("cancel_jnewblk: Invalid state");
4705 	jnewblk->jn_jsegdep  = NULL;
4706 	jnewblk->jn_dep = NULL;
4707 	jnewblk->jn_state |= GOINGAWAY;
4708 	if (jnewblk->jn_state & INPROGRESS) {
4709 		jnewblk->jn_state &= ~INPROGRESS;
4710 		WORKLIST_REMOVE(&jnewblk->jn_list);
4711 		jwork_insert(wkhd, jsegdep);
4712 	} else {
4713 		free_jsegdep(jsegdep);
4714 		remove_from_journal(&jnewblk->jn_list);
4715 	}
4716 	wake_worklist(&jnewblk->jn_list);
4717 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4718 }
4719 
4720 static void
free_jblkdep(struct jblkdep * jblkdep)4721 free_jblkdep(struct jblkdep *jblkdep)
4722 {
4723 
4724 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4725 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4726 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4727 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4728 	else
4729 		panic("free_jblkdep: Unexpected type %s",
4730 		    TYPENAME(jblkdep->jb_list.wk_type));
4731 }
4732 
4733 /*
4734  * Free a single jseg once it is no longer referenced in memory or on
4735  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4736  * to disappear.
4737  */
4738 static void
free_jseg(struct jseg * jseg,struct jblocks * jblocks)4739 free_jseg(struct jseg *jseg, struct jblocks *jblocks)
4740 {
4741 	struct freework *freework;
4742 
4743 	/*
4744 	 * Free freework structures that were lingering to indicate freed
4745 	 * indirect blocks that forced journal write ordering on reallocate.
4746 	 */
4747 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4748 		indirblk_remove(freework);
4749 	if (jblocks->jb_oldestseg == jseg)
4750 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4751 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4752 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4753 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4754 	    ("free_jseg: Freed jseg has valid entries."));
4755 	WORKITEM_FREE(jseg, D_JSEG);
4756 }
4757 
4758 /*
4759  * Free all jsegs that meet the criteria for being reclaimed and update
4760  * oldestseg.
4761  */
4762 static void
free_jsegs(struct jblocks * jblocks)4763 free_jsegs(struct jblocks *jblocks)
4764 {
4765 	struct jseg *jseg;
4766 
4767 	/*
4768 	 * Free only those jsegs which have none allocated before them to
4769 	 * preserve the journal space ordering.
4770 	 */
4771 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4772 		/*
4773 		 * Only reclaim space when nothing depends on this journal
4774 		 * set and another set has written that it is no longer
4775 		 * valid.
4776 		 */
4777 		if (jseg->js_refs != 0) {
4778 			jblocks->jb_oldestseg = jseg;
4779 			return;
4780 		}
4781 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4782 			break;
4783 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4784 			break;
4785 		/*
4786 		 * We can free jsegs that didn't write entries when
4787 		 * oldestwrseq == js_seq.
4788 		 */
4789 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4790 		    jseg->js_cnt != 0)
4791 			break;
4792 		free_jseg(jseg, jblocks);
4793 	}
4794 	/*
4795 	 * If we exited the loop above we still must discover the
4796 	 * oldest valid segment.
4797 	 */
4798 	if (jseg)
4799 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4800 		     jseg = TAILQ_NEXT(jseg, js_next))
4801 			if (jseg->js_refs != 0)
4802 				break;
4803 	jblocks->jb_oldestseg = jseg;
4804 	/*
4805 	 * The journal has no valid records but some jsegs may still be
4806 	 * waiting on oldestwrseq to advance.  We force a small record
4807 	 * out to permit these lingering records to be reclaimed.
4808 	 */
4809 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4810 		jblocks->jb_needseg = 1;
4811 }
4812 
4813 /*
4814  * Release one reference to a jseg and free it if the count reaches 0.  This
4815  * should eventually reclaim journal space as well.
4816  */
4817 static void
rele_jseg(struct jseg * jseg)4818 rele_jseg(struct jseg *jseg)
4819 {
4820 
4821 	KASSERT(jseg->js_refs > 0,
4822 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4823 	if (--jseg->js_refs != 0)
4824 		return;
4825 	free_jsegs(jseg->js_jblocks);
4826 }
4827 
4828 /*
4829  * Release a jsegdep and decrement the jseg count.
4830  */
4831 static void
free_jsegdep(struct jsegdep * jsegdep)4832 free_jsegdep(struct jsegdep *jsegdep)
4833 {
4834 
4835 	if (jsegdep->jd_seg)
4836 		rele_jseg(jsegdep->jd_seg);
4837 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4838 }
4839 
4840 /*
4841  * Wait for a journal item to make it to disk.  Initiate journal processing
4842  * if required.
4843  */
4844 static int
jwait(struct worklist * wk,int waitfor)4845 jwait(struct worklist *wk, int waitfor)
4846 {
4847 
4848 	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4849 	/*
4850 	 * Blocking journal waits cause slow synchronous behavior.  Record
4851 	 * stats on the frequency of these blocking operations.
4852 	 */
4853 	if (waitfor == MNT_WAIT) {
4854 		stat_journal_wait++;
4855 		switch (wk->wk_type) {
4856 		case D_JREMREF:
4857 		case D_JMVREF:
4858 			stat_jwait_filepage++;
4859 			break;
4860 		case D_JTRUNC:
4861 		case D_JFREEBLK:
4862 			stat_jwait_freeblks++;
4863 			break;
4864 		case D_JNEWBLK:
4865 			stat_jwait_newblk++;
4866 			break;
4867 		case D_JADDREF:
4868 			stat_jwait_inode++;
4869 			break;
4870 		default:
4871 			break;
4872 		}
4873 	}
4874 	/*
4875 	 * If IO has not started we process the journal.  We can't mark the
4876 	 * worklist item as IOWAITING because we drop the lock while
4877 	 * processing the journal and the worklist entry may be freed after
4878 	 * this point.  The caller may call back in and re-issue the request.
4879 	 */
4880 	if ((wk->wk_state & INPROGRESS) == 0) {
4881 		softdep_process_journal(wk->wk_mp, wk, waitfor);
4882 		if (waitfor != MNT_WAIT)
4883 			return (EBUSY);
4884 		return (0);
4885 	}
4886 	if (waitfor != MNT_WAIT)
4887 		return (EBUSY);
4888 	wait_worklist(wk, "jwait");
4889 	return (0);
4890 }
4891 
4892 /*
4893  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4894  * appropriate.  This is a convenience function to reduce duplicate code
4895  * for the setup and revert functions below.
4896  */
4897 static struct inodedep *
inodedep_lookup_ip(struct inode * ip)4898 inodedep_lookup_ip(struct inode *ip)
4899 {
4900 	struct inodedep *inodedep;
4901 
4902 	KASSERT(ip->i_nlink >= ip->i_effnlink,
4903 	    ("inodedep_lookup_ip: bad delta"));
4904 	(void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
4905 	    &inodedep);
4906 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4907 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4908 
4909 	return (inodedep);
4910 }
4911 
4912 /*
4913  * Called prior to creating a new inode and linking it to a directory.  The
4914  * jaddref structure must already be allocated by softdep_setup_inomapdep
4915  * and it is discovered here so we can initialize the mode and update
4916  * nlinkdelta.
4917  */
4918 void
softdep_setup_create(struct inode * dp,struct inode * ip)4919 softdep_setup_create(struct inode *dp, struct inode *ip)
4920 {
4921 	struct inodedep *inodedep;
4922 	struct jaddref *jaddref __diagused;
4923 	struct vnode *dvp;
4924 
4925 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4926 	    ("softdep_setup_create called on non-softdep filesystem"));
4927 	KASSERT(ip->i_nlink == 1,
4928 	    ("softdep_setup_create: Invalid link count."));
4929 	dvp = ITOV(dp);
4930 	ACQUIRE_LOCK(ITOUMP(dp));
4931 	inodedep = inodedep_lookup_ip(ip);
4932 	if (DOINGSUJ(dvp)) {
4933 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4934 		    inoreflst);
4935 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4936 		    ("softdep_setup_create: No addref structure present."));
4937 	}
4938 	FREE_LOCK(ITOUMP(dp));
4939 }
4940 
4941 /*
4942  * Create a jaddref structure to track the addition of a DOTDOT link when
4943  * we are reparenting an inode as part of a rename.  This jaddref will be
4944  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4945  * non-journaling softdep.
4946  */
4947 void
softdep_setup_dotdot_link(struct inode * dp,struct inode * ip)4948 softdep_setup_dotdot_link(struct inode *dp, struct inode *ip)
4949 {
4950 	struct inodedep *inodedep;
4951 	struct jaddref *jaddref;
4952 	struct vnode *dvp;
4953 
4954 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4955 	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4956 	dvp = ITOV(dp);
4957 	jaddref = NULL;
4958 	/*
4959 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4960 	 * is used as a normal link would be.
4961 	 */
4962 	if (DOINGSUJ(dvp))
4963 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4964 		    dp->i_effnlink - 1, dp->i_mode);
4965 	ACQUIRE_LOCK(ITOUMP(dp));
4966 	inodedep = inodedep_lookup_ip(dp);
4967 	if (jaddref)
4968 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4969 		    if_deps);
4970 	FREE_LOCK(ITOUMP(dp));
4971 }
4972 
4973 /*
4974  * Create a jaddref structure to track a new link to an inode.  The directory
4975  * offset is not known until softdep_setup_directory_add or
4976  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4977  * softdep.
4978  */
4979 void
softdep_setup_link(struct inode * dp,struct inode * ip)4980 softdep_setup_link(struct inode *dp, struct inode *ip)
4981 {
4982 	struct inodedep *inodedep;
4983 	struct jaddref *jaddref;
4984 	struct vnode *dvp;
4985 
4986 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4987 	    ("softdep_setup_link called on non-softdep filesystem"));
4988 	dvp = ITOV(dp);
4989 	jaddref = NULL;
4990 	if (DOINGSUJ(dvp))
4991 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4992 		    ip->i_mode);
4993 	ACQUIRE_LOCK(ITOUMP(dp));
4994 	inodedep = inodedep_lookup_ip(ip);
4995 	if (jaddref)
4996 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4997 		    if_deps);
4998 	FREE_LOCK(ITOUMP(dp));
4999 }
5000 
5001 /*
5002  * Called to create the jaddref structures to track . and .. references as
5003  * well as lookup and further initialize the incomplete jaddref created
5004  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
5005  * nlinkdelta for non-journaling softdep.
5006  */
5007 void
softdep_setup_mkdir(struct inode * dp,struct inode * ip)5008 softdep_setup_mkdir(struct inode *dp, struct inode *ip)
5009 {
5010 	struct inodedep *inodedep;
5011 	struct jaddref *dotdotaddref;
5012 	struct jaddref *dotaddref;
5013 	struct jaddref *jaddref;
5014 	struct vnode *dvp;
5015 
5016 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5017 	    ("softdep_setup_mkdir called on non-softdep filesystem"));
5018 	dvp = ITOV(dp);
5019 	dotaddref = dotdotaddref = NULL;
5020 	if (DOINGSUJ(dvp)) {
5021 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
5022 		    ip->i_mode);
5023 		dotaddref->ja_state |= MKDIR_BODY;
5024 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
5025 		    dp->i_effnlink - 1, dp->i_mode);
5026 		dotdotaddref->ja_state |= MKDIR_PARENT;
5027 	}
5028 	ACQUIRE_LOCK(ITOUMP(dp));
5029 	inodedep = inodedep_lookup_ip(ip);
5030 	if (DOINGSUJ(dvp)) {
5031 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5032 		    inoreflst);
5033 		KASSERT(jaddref != NULL,
5034 		    ("softdep_setup_mkdir: No addref structure present."));
5035 		KASSERT(jaddref->ja_parent == dp->i_number,
5036 		    ("softdep_setup_mkdir: bad parent %ju",
5037 		    (uintmax_t)jaddref->ja_parent));
5038 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
5039 		    if_deps);
5040 	}
5041 	inodedep = inodedep_lookup_ip(dp);
5042 	if (DOINGSUJ(dvp))
5043 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
5044 		    &dotdotaddref->ja_ref, if_deps);
5045 	FREE_LOCK(ITOUMP(dp));
5046 }
5047 
5048 /*
5049  * Called to track nlinkdelta of the inode and parent directories prior to
5050  * unlinking a directory.
5051  */
5052 void
softdep_setup_rmdir(struct inode * dp,struct inode * ip)5053 softdep_setup_rmdir(struct inode *dp, struct inode *ip)
5054 {
5055 
5056 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5057 	    ("softdep_setup_rmdir called on non-softdep filesystem"));
5058 	ACQUIRE_LOCK(ITOUMP(dp));
5059 	(void) inodedep_lookup_ip(ip);
5060 	(void) inodedep_lookup_ip(dp);
5061 	FREE_LOCK(ITOUMP(dp));
5062 }
5063 
5064 /*
5065  * Called to track nlinkdelta of the inode and parent directories prior to
5066  * unlink.
5067  */
5068 void
softdep_setup_unlink(struct inode * dp,struct inode * ip)5069 softdep_setup_unlink(struct inode *dp, struct inode *ip)
5070 {
5071 
5072 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5073 	    ("softdep_setup_unlink called on non-softdep filesystem"));
5074 	ACQUIRE_LOCK(ITOUMP(dp));
5075 	(void) inodedep_lookup_ip(ip);
5076 	(void) inodedep_lookup_ip(dp);
5077 	FREE_LOCK(ITOUMP(dp));
5078 }
5079 
5080 /*
5081  * Called to release the journal structures created by a failed non-directory
5082  * creation.  Adjusts nlinkdelta for non-journaling softdep.
5083  */
5084 void
softdep_revert_create(struct inode * dp,struct inode * ip)5085 softdep_revert_create(struct inode *dp, struct inode *ip)
5086 {
5087 	struct inodedep *inodedep;
5088 	struct jaddref *jaddref;
5089 	struct vnode *dvp;
5090 
5091 	KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
5092 	    ("softdep_revert_create called on non-softdep filesystem"));
5093 	dvp = ITOV(dp);
5094 	ACQUIRE_LOCK(ITOUMP(dp));
5095 	inodedep = inodedep_lookup_ip(ip);
5096 	if (DOINGSUJ(dvp)) {
5097 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5098 		    inoreflst);
5099 		KASSERT(jaddref->ja_parent == dp->i_number,
5100 		    ("softdep_revert_create: addref parent mismatch"));
5101 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5102 	}
5103 	FREE_LOCK(ITOUMP(dp));
5104 }
5105 
5106 /*
5107  * Called to release the journal structures created by a failed link
5108  * addition.  Adjusts nlinkdelta for non-journaling softdep.
5109  */
5110 void
softdep_revert_link(struct inode * dp,struct inode * ip)5111 softdep_revert_link(struct inode *dp, struct inode *ip)
5112 {
5113 	struct inodedep *inodedep;
5114 	struct jaddref *jaddref;
5115 	struct vnode *dvp;
5116 
5117 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5118 	    ("softdep_revert_link called on non-softdep filesystem"));
5119 	dvp = ITOV(dp);
5120 	ACQUIRE_LOCK(ITOUMP(dp));
5121 	inodedep = inodedep_lookup_ip(ip);
5122 	if (DOINGSUJ(dvp)) {
5123 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5124 		    inoreflst);
5125 		KASSERT(jaddref->ja_parent == dp->i_number,
5126 		    ("softdep_revert_link: addref parent mismatch"));
5127 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5128 	}
5129 	FREE_LOCK(ITOUMP(dp));
5130 }
5131 
5132 /*
5133  * Called to release the journal structures created by a failed mkdir
5134  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
5135  */
5136 void
softdep_revert_mkdir(struct inode * dp,struct inode * ip)5137 softdep_revert_mkdir(struct inode *dp, struct inode *ip)
5138 {
5139 	struct inodedep *inodedep;
5140 	struct jaddref *jaddref;
5141 	struct jaddref *dotaddref;
5142 	struct vnode *dvp;
5143 
5144 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5145 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
5146 	dvp = ITOV(dp);
5147 
5148 	ACQUIRE_LOCK(ITOUMP(dp));
5149 	inodedep = inodedep_lookup_ip(dp);
5150 	if (DOINGSUJ(dvp)) {
5151 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5152 		    inoreflst);
5153 		KASSERT(jaddref->ja_parent == ip->i_number,
5154 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
5155 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5156 	}
5157 	inodedep = inodedep_lookup_ip(ip);
5158 	if (DOINGSUJ(dvp)) {
5159 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5160 		    inoreflst);
5161 		KASSERT(jaddref->ja_parent == dp->i_number,
5162 		    ("softdep_revert_mkdir: addref parent mismatch"));
5163 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
5164 		    inoreflst, if_deps);
5165 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5166 		KASSERT(dotaddref->ja_parent == ip->i_number,
5167 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
5168 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
5169 	}
5170 	FREE_LOCK(ITOUMP(dp));
5171 }
5172 
5173 /*
5174  * Called to correct nlinkdelta after a failed rmdir.
5175  */
5176 void
softdep_revert_rmdir(struct inode * dp,struct inode * ip)5177 softdep_revert_rmdir(struct inode *dp, struct inode *ip)
5178 {
5179 
5180 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5181 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
5182 	ACQUIRE_LOCK(ITOUMP(dp));
5183 	(void) inodedep_lookup_ip(ip);
5184 	(void) inodedep_lookup_ip(dp);
5185 	FREE_LOCK(ITOUMP(dp));
5186 }
5187 
5188 /*
5189  * Protecting the freemaps (or bitmaps).
5190  *
5191  * To eliminate the need to execute fsck before mounting a filesystem
5192  * after a power failure, one must (conservatively) guarantee that the
5193  * on-disk copy of the bitmaps never indicate that a live inode or block is
5194  * free.  So, when a block or inode is allocated, the bitmap should be
5195  * updated (on disk) before any new pointers.  When a block or inode is
5196  * freed, the bitmap should not be updated until all pointers have been
5197  * reset.  The latter dependency is handled by the delayed de-allocation
5198  * approach described below for block and inode de-allocation.  The former
5199  * dependency is handled by calling the following procedure when a block or
5200  * inode is allocated. When an inode is allocated an "inodedep" is created
5201  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
5202  * Each "inodedep" is also inserted into the hash indexing structure so
5203  * that any additional link additions can be made dependent on the inode
5204  * allocation.
5205  *
5206  * The ufs filesystem maintains a number of free block counts (e.g., per
5207  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
5208  * in addition to the bitmaps.  These counts are used to improve efficiency
5209  * during allocation and therefore must be consistent with the bitmaps.
5210  * There is no convenient way to guarantee post-crash consistency of these
5211  * counts with simple update ordering, for two main reasons: (1) The counts
5212  * and bitmaps for a single cylinder group block are not in the same disk
5213  * sector.  If a disk write is interrupted (e.g., by power failure), one may
5214  * be written and the other not.  (2) Some of the counts are located in the
5215  * superblock rather than the cylinder group block. So, we focus our soft
5216  * updates implementation on protecting the bitmaps. When mounting a
5217  * filesystem, we recompute the auxiliary counts from the bitmaps.
5218  */
5219 
5220 /*
5221  * Called just after updating the cylinder group block to allocate an inode.
5222  */
5223 void
softdep_setup_inomapdep(struct buf * bp,struct inode * ip,ino_t newinum,int mode)5224 softdep_setup_inomapdep(
5225 	struct buf *bp,		/* buffer for cylgroup block with inode map */
5226 	struct inode *ip,	/* inode related to allocation */
5227 	ino_t newinum,		/* new inode number being allocated */
5228 	int mode)
5229 {
5230 	struct inodedep *inodedep;
5231 	struct bmsafemap *bmsafemap;
5232 	struct jaddref *jaddref;
5233 	struct mount *mp;
5234 	struct fs *fs;
5235 
5236 	mp = ITOVFS(ip);
5237 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5238 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5239 	fs = VFSTOUFS(mp)->um_fs;
5240 	jaddref = NULL;
5241 
5242 	/*
5243 	 * Allocate the journal reference add structure so that the bitmap
5244 	 * can be dependent on it.
5245 	 */
5246 	if (MOUNTEDSUJ(mp)) {
5247 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
5248 		jaddref->ja_state |= NEWBLOCK;
5249 	}
5250 
5251 	/*
5252 	 * Create a dependency for the newly allocated inode.
5253 	 * Panic if it already exists as something is seriously wrong.
5254 	 * Otherwise add it to the dependency list for the buffer holding
5255 	 * the cylinder group map from which it was allocated.
5256 	 *
5257 	 * We have to preallocate a bmsafemap entry in case it is needed
5258 	 * in bmsafemap_lookup since once we allocate the inodedep, we
5259 	 * have to finish initializing it before we can FREE_LOCK().
5260 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
5261 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5262 	 * creating the inodedep as it can be freed during the time
5263 	 * that we FREE_LOCK() while allocating the inodedep. We must
5264 	 * call workitem_alloc() before entering the locked section as
5265 	 * it also acquires the lock and we must avoid trying doing so
5266 	 * recursively.
5267 	 */
5268 	bmsafemap = malloc(sizeof(struct bmsafemap),
5269 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5270 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5271 	ACQUIRE_LOCK(ITOUMP(ip));
5272 	if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5273 		panic("softdep_setup_inomapdep: dependency %p for new"
5274 		    "inode already exists", inodedep);
5275 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5276 	if (jaddref) {
5277 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5278 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5279 		    if_deps);
5280 	} else {
5281 		inodedep->id_state |= ONDEPLIST;
5282 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5283 	}
5284 	inodedep->id_bmsafemap = bmsafemap;
5285 	inodedep->id_state &= ~DEPCOMPLETE;
5286 	FREE_LOCK(ITOUMP(ip));
5287 }
5288 
5289 /*
5290  * Called just after updating the cylinder group block to
5291  * allocate block or fragment.
5292  */
5293 void
softdep_setup_blkmapdep(struct buf * bp,struct mount * mp,ufs2_daddr_t newblkno,int frags,int oldfrags)5294 softdep_setup_blkmapdep(
5295 	struct buf *bp,		/* buffer for cylgroup block with block map */
5296 	struct mount *mp,	/* filesystem doing allocation */
5297 	ufs2_daddr_t newblkno,	/* number of newly allocated block */
5298 	int frags,		/* Number of fragments. */
5299 	int oldfrags)		/* Previous number of fragments for extend. */
5300 {
5301 	struct newblk *newblk;
5302 	struct bmsafemap *bmsafemap;
5303 	struct jnewblk *jnewblk;
5304 	struct ufsmount *ump;
5305 	struct fs *fs;
5306 
5307 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5308 	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5309 	ump = VFSTOUFS(mp);
5310 	fs = ump->um_fs;
5311 	jnewblk = NULL;
5312 	/*
5313 	 * Create a dependency for the newly allocated block.
5314 	 * Add it to the dependency list for the buffer holding
5315 	 * the cylinder group map from which it was allocated.
5316 	 */
5317 	if (MOUNTEDSUJ(mp)) {
5318 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5319 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5320 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5321 		jnewblk->jn_state = ATTACHED;
5322 		jnewblk->jn_blkno = newblkno;
5323 		jnewblk->jn_frags = frags;
5324 		jnewblk->jn_oldfrags = oldfrags;
5325 #ifdef INVARIANTS
5326 		{
5327 			struct cg *cgp;
5328 			uint8_t *blksfree;
5329 			long bno;
5330 			int i;
5331 
5332 			cgp = (struct cg *)bp->b_data;
5333 			blksfree = cg_blksfree(cgp);
5334 			bno = dtogd(fs, jnewblk->jn_blkno);
5335 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5336 			    i++) {
5337 				if (isset(blksfree, bno + i))
5338 					panic("softdep_setup_blkmapdep: "
5339 					    "free fragment %d from %d-%d "
5340 					    "state 0x%X dep %p", i,
5341 					    jnewblk->jn_oldfrags,
5342 					    jnewblk->jn_frags,
5343 					    jnewblk->jn_state,
5344 					    jnewblk->jn_dep);
5345 			}
5346 		}
5347 #endif
5348 	}
5349 
5350 	CTR3(KTR_SUJ,
5351 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5352 	    newblkno, frags, oldfrags);
5353 	ACQUIRE_LOCK(ump);
5354 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5355 		panic("softdep_setup_blkmapdep: found block");
5356 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5357 	    dtog(fs, newblkno), NULL);
5358 	if (jnewblk) {
5359 		jnewblk->jn_dep = (struct worklist *)newblk;
5360 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5361 	} else {
5362 		newblk->nb_state |= ONDEPLIST;
5363 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5364 	}
5365 	newblk->nb_bmsafemap = bmsafemap;
5366 	newblk->nb_jnewblk = jnewblk;
5367 	FREE_LOCK(ump);
5368 }
5369 
5370 #define	BMSAFEMAP_HASH(ump, cg) \
5371       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5372 
5373 static int
bmsafemap_find(struct bmsafemap_hashhead * bmsafemaphd,int cg,struct bmsafemap ** bmsafemapp)5374 bmsafemap_find(
5375 	struct bmsafemap_hashhead *bmsafemaphd,
5376 	int cg,
5377 	struct bmsafemap **bmsafemapp)
5378 {
5379 	struct bmsafemap *bmsafemap;
5380 
5381 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5382 		if (bmsafemap->sm_cg == cg)
5383 			break;
5384 	if (bmsafemap) {
5385 		*bmsafemapp = bmsafemap;
5386 		return (1);
5387 	}
5388 	*bmsafemapp = NULL;
5389 
5390 	return (0);
5391 }
5392 
5393 /*
5394  * Find the bmsafemap associated with a cylinder group buffer.
5395  * If none exists, create one. The buffer must be locked when
5396  * this routine is called and this routine must be called with
5397  * the softdep lock held. To avoid giving up the lock while
5398  * allocating a new bmsafemap, a preallocated bmsafemap may be
5399  * provided. If it is provided but not needed, it is freed.
5400  */
5401 static struct bmsafemap *
bmsafemap_lookup(struct mount * mp,struct buf * bp,int cg,struct bmsafemap * newbmsafemap)5402 bmsafemap_lookup(struct mount *mp,
5403 	struct buf *bp,
5404 	int cg,
5405 	struct bmsafemap *newbmsafemap)
5406 {
5407 	struct bmsafemap_hashhead *bmsafemaphd;
5408 	struct bmsafemap *bmsafemap, *collision;
5409 	struct worklist *wk;
5410 	struct ufsmount *ump;
5411 
5412 	ump = VFSTOUFS(mp);
5413 	LOCK_OWNED(ump);
5414 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5415 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5416 		if (wk->wk_type == D_BMSAFEMAP) {
5417 			if (newbmsafemap)
5418 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5419 			return (WK_BMSAFEMAP(wk));
5420 		}
5421 	}
5422 	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5423 	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5424 		if (newbmsafemap)
5425 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5426 		return (bmsafemap);
5427 	}
5428 	if (newbmsafemap) {
5429 		bmsafemap = newbmsafemap;
5430 	} else {
5431 		FREE_LOCK(ump);
5432 		bmsafemap = malloc(sizeof(struct bmsafemap),
5433 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5434 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5435 		ACQUIRE_LOCK(ump);
5436 	}
5437 	bmsafemap->sm_buf = bp;
5438 	LIST_INIT(&bmsafemap->sm_inodedephd);
5439 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5440 	LIST_INIT(&bmsafemap->sm_newblkhd);
5441 	LIST_INIT(&bmsafemap->sm_newblkwr);
5442 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5443 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5444 	LIST_INIT(&bmsafemap->sm_freehd);
5445 	LIST_INIT(&bmsafemap->sm_freewr);
5446 	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5447 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5448 		return (collision);
5449 	}
5450 	bmsafemap->sm_cg = cg;
5451 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5452 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5453 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5454 	return (bmsafemap);
5455 }
5456 
5457 /*
5458  * Direct block allocation dependencies.
5459  *
5460  * When a new block is allocated, the corresponding disk locations must be
5461  * initialized (with zeros or new data) before the on-disk inode points to
5462  * them.  Also, the freemap from which the block was allocated must be
5463  * updated (on disk) before the inode's pointer. These two dependencies are
5464  * independent of each other and are needed for all file blocks and indirect
5465  * blocks that are pointed to directly by the inode.  Just before the
5466  * "in-core" version of the inode is updated with a newly allocated block
5467  * number, a procedure (below) is called to setup allocation dependency
5468  * structures.  These structures are removed when the corresponding
5469  * dependencies are satisfied or when the block allocation becomes obsolete
5470  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5471  * fragment that gets upgraded).  All of these cases are handled in
5472  * procedures described later.
5473  *
5474  * When a file extension causes a fragment to be upgraded, either to a larger
5475  * fragment or to a full block, the on-disk location may change (if the
5476  * previous fragment could not simply be extended). In this case, the old
5477  * fragment must be de-allocated, but not until after the inode's pointer has
5478  * been updated. In most cases, this is handled by later procedures, which
5479  * will construct a "freefrag" structure to be added to the workitem queue
5480  * when the inode update is complete (or obsolete).  The main exception to
5481  * this is when an allocation occurs while a pending allocation dependency
5482  * (for the same block pointer) remains.  This case is handled in the main
5483  * allocation dependency setup procedure by immediately freeing the
5484  * unreferenced fragments.
5485  */
5486 void
softdep_setup_allocdirect(struct inode * ip,ufs_lbn_t off,ufs2_daddr_t newblkno,ufs2_daddr_t oldblkno,long newsize,long oldsize,struct buf * bp)5487 softdep_setup_allocdirect(
5488 	struct inode *ip,	/* inode to which block is being added */
5489 	ufs_lbn_t off,		/* block pointer within inode */
5490 	ufs2_daddr_t newblkno,	/* disk block number being added */
5491 	ufs2_daddr_t oldblkno,	/* previous block number, 0 unless frag */
5492 	long newsize,		/* size of new block */
5493 	long oldsize,		/* size of new block */
5494 	struct buf *bp)		/* bp for allocated block */
5495 {
5496 	struct allocdirect *adp, *oldadp;
5497 	struct allocdirectlst *adphead;
5498 	struct freefrag *freefrag;
5499 	struct inodedep *inodedep;
5500 	struct pagedep *pagedep;
5501 	struct jnewblk *jnewblk;
5502 	struct newblk *newblk;
5503 	struct mount *mp;
5504 	ufs_lbn_t lbn;
5505 
5506 	lbn = bp->b_lblkno;
5507 	mp = ITOVFS(ip);
5508 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5509 	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5510 	if (oldblkno && oldblkno != newblkno)
5511 		/*
5512 		 * The usual case is that a smaller fragment that
5513 		 * was just allocated has been replaced with a bigger
5514 		 * fragment or a full-size block. If it is marked as
5515 		 * B_DELWRI, the current contents have not been written
5516 		 * to disk. It is possible that the block was written
5517 		 * earlier, but very uncommon. If the block has never
5518 		 * been written, there is no need to send a BIO_DELETE
5519 		 * for it when it is freed. The gain from avoiding the
5520 		 * TRIMs for the common case of unwritten blocks far
5521 		 * exceeds the cost of the write amplification for the
5522 		 * uncommon case of failing to send a TRIM for a block
5523 		 * that had been written.
5524 		 */
5525 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5526 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5527 	else
5528 		freefrag = NULL;
5529 
5530 	CTR6(KTR_SUJ,
5531 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5532 	    "off %jd newsize %ld oldsize %d",
5533 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5534 	ACQUIRE_LOCK(ITOUMP(ip));
5535 	if (off >= UFS_NDADDR) {
5536 		if (lbn > 0)
5537 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5538 			    lbn, off);
5539 		/* allocating an indirect block */
5540 		if (oldblkno != 0)
5541 			panic("softdep_setup_allocdirect: non-zero indir");
5542 	} else {
5543 		if (off != lbn)
5544 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5545 			    lbn, off);
5546 		/*
5547 		 * Allocating a direct block.
5548 		 *
5549 		 * If we are allocating a directory block, then we must
5550 		 * allocate an associated pagedep to track additions and
5551 		 * deletions.
5552 		 */
5553 		if ((ip->i_mode & IFMT) == IFDIR)
5554 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5555 			    &pagedep);
5556 	}
5557 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5558 		panic("softdep_setup_allocdirect: lost block");
5559 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5560 	    ("softdep_setup_allocdirect: newblk already initialized"));
5561 	/*
5562 	 * Convert the newblk to an allocdirect.
5563 	 */
5564 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5565 	adp = (struct allocdirect *)newblk;
5566 	newblk->nb_freefrag = freefrag;
5567 	adp->ad_offset = off;
5568 	adp->ad_oldblkno = oldblkno;
5569 	adp->ad_newsize = newsize;
5570 	adp->ad_oldsize = oldsize;
5571 
5572 	/*
5573 	 * Finish initializing the journal.
5574 	 */
5575 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5576 		jnewblk->jn_ino = ip->i_number;
5577 		jnewblk->jn_lbn = lbn;
5578 		add_to_journal(&jnewblk->jn_list);
5579 	}
5580 	if (freefrag && freefrag->ff_jdep != NULL &&
5581 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5582 		add_to_journal(freefrag->ff_jdep);
5583 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5584 	adp->ad_inodedep = inodedep;
5585 
5586 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5587 	/*
5588 	 * The list of allocdirects must be kept in sorted and ascending
5589 	 * order so that the rollback routines can quickly determine the
5590 	 * first uncommitted block (the size of the file stored on disk
5591 	 * ends at the end of the lowest committed fragment, or if there
5592 	 * are no fragments, at the end of the highest committed block).
5593 	 * Since files generally grow, the typical case is that the new
5594 	 * block is to be added at the end of the list. We speed this
5595 	 * special case by checking against the last allocdirect in the
5596 	 * list before laboriously traversing the list looking for the
5597 	 * insertion point.
5598 	 */
5599 	adphead = &inodedep->id_newinoupdt;
5600 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5601 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5602 		/* insert at end of list */
5603 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5604 		if (oldadp != NULL && oldadp->ad_offset == off)
5605 			allocdirect_merge(adphead, adp, oldadp);
5606 		FREE_LOCK(ITOUMP(ip));
5607 		return;
5608 	}
5609 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5610 		if (oldadp->ad_offset >= off)
5611 			break;
5612 	}
5613 	if (oldadp == NULL)
5614 		panic("softdep_setup_allocdirect: lost entry");
5615 	/* insert in middle of list */
5616 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5617 	if (oldadp->ad_offset == off)
5618 		allocdirect_merge(adphead, adp, oldadp);
5619 
5620 	FREE_LOCK(ITOUMP(ip));
5621 }
5622 
5623 /*
5624  * Merge a newer and older journal record to be stored either in a
5625  * newblock or freefrag.  This handles aggregating journal records for
5626  * fragment allocation into a second record as well as replacing a
5627  * journal free with an aborted journal allocation.  A segment for the
5628  * oldest record will be placed on wkhd if it has been written.  If not
5629  * the segment for the newer record will suffice.
5630  */
5631 static struct worklist *
jnewblk_merge(struct worklist * new,struct worklist * old,struct workhead * wkhd)5632 jnewblk_merge(struct worklist *new,
5633 	struct worklist *old,
5634 	struct workhead *wkhd)
5635 {
5636 	struct jnewblk *njnewblk;
5637 	struct jnewblk *jnewblk;
5638 
5639 	/* Handle NULLs to simplify callers. */
5640 	if (new == NULL)
5641 		return (old);
5642 	if (old == NULL)
5643 		return (new);
5644 	/* Replace a jfreefrag with a jnewblk. */
5645 	if (new->wk_type == D_JFREEFRAG) {
5646 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5647 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5648 			    old, new);
5649 		cancel_jfreefrag(WK_JFREEFRAG(new));
5650 		return (old);
5651 	}
5652 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5653 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5654 		    old->wk_type, new->wk_type);
5655 	/*
5656 	 * Handle merging of two jnewblk records that describe
5657 	 * different sets of fragments in the same block.
5658 	 */
5659 	jnewblk = WK_JNEWBLK(old);
5660 	njnewblk = WK_JNEWBLK(new);
5661 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5662 		panic("jnewblk_merge: Merging disparate blocks.");
5663 	/*
5664 	 * The record may be rolled back in the cg.
5665 	 */
5666 	if (jnewblk->jn_state & UNDONE) {
5667 		jnewblk->jn_state &= ~UNDONE;
5668 		njnewblk->jn_state |= UNDONE;
5669 		njnewblk->jn_state &= ~ATTACHED;
5670 	}
5671 	/*
5672 	 * We modify the newer addref and free the older so that if neither
5673 	 * has been written the most up-to-date copy will be on disk.  If
5674 	 * both have been written but rolled back we only temporarily need
5675 	 * one of them to fix the bits when the cg write completes.
5676 	 */
5677 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5678 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5679 	cancel_jnewblk(jnewblk, wkhd);
5680 	WORKLIST_REMOVE(&jnewblk->jn_list);
5681 	free_jnewblk(jnewblk);
5682 	return (new);
5683 }
5684 
5685 /*
5686  * Replace an old allocdirect dependency with a newer one.
5687  */
5688 static void
allocdirect_merge(struct allocdirectlst * adphead,struct allocdirect * newadp,struct allocdirect * oldadp)5689 allocdirect_merge(
5690 	struct allocdirectlst *adphead,	/* head of list holding allocdirects */
5691 	struct allocdirect *newadp,	/* allocdirect being added */
5692 	struct allocdirect *oldadp)	/* existing allocdirect being checked */
5693 {
5694 	struct worklist *wk;
5695 	struct freefrag *freefrag;
5696 
5697 	freefrag = NULL;
5698 	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5699 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5700 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5701 	    newadp->ad_offset >= UFS_NDADDR)
5702 		panic("%s %jd != new %jd || old size %ld != new %ld",
5703 		    "allocdirect_merge: old blkno",
5704 		    (intmax_t)newadp->ad_oldblkno,
5705 		    (intmax_t)oldadp->ad_newblkno,
5706 		    newadp->ad_oldsize, oldadp->ad_newsize);
5707 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5708 	newadp->ad_oldsize = oldadp->ad_oldsize;
5709 	/*
5710 	 * If the old dependency had a fragment to free or had never
5711 	 * previously had a block allocated, then the new dependency
5712 	 * can immediately post its freefrag and adopt the old freefrag.
5713 	 * This action is done by swapping the freefrag dependencies.
5714 	 * The new dependency gains the old one's freefrag, and the
5715 	 * old one gets the new one and then immediately puts it on
5716 	 * the worklist when it is freed by free_newblk. It is
5717 	 * not possible to do this swap when the old dependency had a
5718 	 * non-zero size but no previous fragment to free. This condition
5719 	 * arises when the new block is an extension of the old block.
5720 	 * Here, the first part of the fragment allocated to the new
5721 	 * dependency is part of the block currently claimed on disk by
5722 	 * the old dependency, so cannot legitimately be freed until the
5723 	 * conditions for the new dependency are fulfilled.
5724 	 */
5725 	freefrag = newadp->ad_freefrag;
5726 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5727 		newadp->ad_freefrag = oldadp->ad_freefrag;
5728 		oldadp->ad_freefrag = freefrag;
5729 	}
5730 	/*
5731 	 * If we are tracking a new directory-block allocation,
5732 	 * move it from the old allocdirect to the new allocdirect.
5733 	 */
5734 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5735 		WORKLIST_REMOVE(wk);
5736 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5737 			panic("allocdirect_merge: extra newdirblk");
5738 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5739 	}
5740 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5741 	/*
5742 	 * We need to move any journal dependencies over to the freefrag
5743 	 * that releases this block if it exists.  Otherwise we are
5744 	 * extending an existing block and we'll wait until that is
5745 	 * complete to release the journal space and extend the
5746 	 * new journal to cover this old space as well.
5747 	 */
5748 	if (freefrag == NULL) {
5749 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5750 			panic("allocdirect_merge: %jd != %jd",
5751 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5752 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5753 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5754 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5755 		    &newadp->ad_block.nb_jwork);
5756 		oldadp->ad_block.nb_jnewblk = NULL;
5757 		cancel_newblk(&oldadp->ad_block, NULL,
5758 		    &newadp->ad_block.nb_jwork);
5759 	} else {
5760 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5761 		    &freefrag->ff_list, &freefrag->ff_jwork);
5762 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5763 		    &freefrag->ff_jwork);
5764 	}
5765 	free_newblk(&oldadp->ad_block);
5766 }
5767 
5768 /*
5769  * Allocate a jfreefrag structure to journal a single block free.
5770  */
5771 static struct jfreefrag *
newjfreefrag(struct freefrag * freefrag,struct inode * ip,ufs2_daddr_t blkno,long size,ufs_lbn_t lbn)5772 newjfreefrag(struct freefrag *freefrag,
5773 	struct inode *ip,
5774 	ufs2_daddr_t blkno,
5775 	long size,
5776 	ufs_lbn_t lbn)
5777 {
5778 	struct jfreefrag *jfreefrag;
5779 	struct fs *fs;
5780 
5781 	fs = ITOFS(ip);
5782 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5783 	    M_SOFTDEP_FLAGS);
5784 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5785 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5786 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5787 	jfreefrag->fr_ino = ip->i_number;
5788 	jfreefrag->fr_lbn = lbn;
5789 	jfreefrag->fr_blkno = blkno;
5790 	jfreefrag->fr_frags = numfrags(fs, size);
5791 	jfreefrag->fr_freefrag = freefrag;
5792 
5793 	return (jfreefrag);
5794 }
5795 
5796 /*
5797  * Allocate a new freefrag structure.
5798  */
5799 static struct freefrag *
newfreefrag(struct inode * ip,ufs2_daddr_t blkno,long size,ufs_lbn_t lbn,uint64_t key)5800 newfreefrag(struct inode *ip,
5801 	ufs2_daddr_t blkno,
5802 	long size,
5803 	ufs_lbn_t lbn,
5804 	uint64_t key)
5805 {
5806 	struct freefrag *freefrag;
5807 	struct ufsmount *ump;
5808 	struct fs *fs;
5809 
5810 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5811 	    ip->i_number, blkno, size, lbn);
5812 	ump = ITOUMP(ip);
5813 	fs = ump->um_fs;
5814 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5815 		panic("newfreefrag: frag size");
5816 	freefrag = malloc(sizeof(struct freefrag),
5817 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5818 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5819 	freefrag->ff_state = ATTACHED;
5820 	LIST_INIT(&freefrag->ff_jwork);
5821 	freefrag->ff_inum = ip->i_number;
5822 	freefrag->ff_vtype = ITOV(ip)->v_type;
5823 	freefrag->ff_blkno = blkno;
5824 	freefrag->ff_fragsize = size;
5825 	freefrag->ff_key = key;
5826 
5827 	if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5828 		freefrag->ff_jdep = (struct worklist *)
5829 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5830 	} else {
5831 		freefrag->ff_state |= DEPCOMPLETE;
5832 		freefrag->ff_jdep = NULL;
5833 	}
5834 
5835 	return (freefrag);
5836 }
5837 
5838 /*
5839  * This workitem de-allocates fragments that were replaced during
5840  * file block allocation.
5841  */
5842 static void
handle_workitem_freefrag(struct freefrag * freefrag)5843 handle_workitem_freefrag(struct freefrag *freefrag)
5844 {
5845 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5846 	struct workhead wkhd;
5847 
5848 	CTR3(KTR_SUJ,
5849 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5850 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5851 	/*
5852 	 * It would be illegal to add new completion items to the
5853 	 * freefrag after it was schedule to be done so it must be
5854 	 * safe to modify the list head here.
5855 	 */
5856 	LIST_INIT(&wkhd);
5857 	ACQUIRE_LOCK(ump);
5858 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5859 	/*
5860 	 * If the journal has not been written we must cancel it here.
5861 	 */
5862 	if (freefrag->ff_jdep) {
5863 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5864 			panic("handle_workitem_freefrag: Unexpected type %d\n",
5865 			    freefrag->ff_jdep->wk_type);
5866 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5867 	}
5868 	FREE_LOCK(ump);
5869 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5870 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
5871 	   &wkhd, freefrag->ff_key);
5872 	ACQUIRE_LOCK(ump);
5873 	WORKITEM_FREE(freefrag, D_FREEFRAG);
5874 	FREE_LOCK(ump);
5875 }
5876 
5877 /*
5878  * Set up a dependency structure for an external attributes data block.
5879  * This routine follows much of the structure of softdep_setup_allocdirect.
5880  * See the description of softdep_setup_allocdirect above for details.
5881  */
5882 void
softdep_setup_allocext(struct inode * ip,ufs_lbn_t off,ufs2_daddr_t newblkno,ufs2_daddr_t oldblkno,long newsize,long oldsize,struct buf * bp)5883 softdep_setup_allocext(
5884 	struct inode *ip,
5885 	ufs_lbn_t off,
5886 	ufs2_daddr_t newblkno,
5887 	ufs2_daddr_t oldblkno,
5888 	long newsize,
5889 	long oldsize,
5890 	struct buf *bp)
5891 {
5892 	struct allocdirect *adp, *oldadp;
5893 	struct allocdirectlst *adphead;
5894 	struct freefrag *freefrag;
5895 	struct inodedep *inodedep;
5896 	struct jnewblk *jnewblk;
5897 	struct newblk *newblk;
5898 	struct mount *mp;
5899 	struct ufsmount *ump;
5900 	ufs_lbn_t lbn;
5901 
5902 	mp = ITOVFS(ip);
5903 	ump = VFSTOUFS(mp);
5904 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5905 	    ("softdep_setup_allocext called on non-softdep filesystem"));
5906 	KASSERT(off < UFS_NXADDR,
5907 	    ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5908 
5909 	lbn = bp->b_lblkno;
5910 	if (oldblkno && oldblkno != newblkno)
5911 		/*
5912 		 * The usual case is that a smaller fragment that
5913 		 * was just allocated has been replaced with a bigger
5914 		 * fragment or a full-size block. If it is marked as
5915 		 * B_DELWRI, the current contents have not been written
5916 		 * to disk. It is possible that the block was written
5917 		 * earlier, but very uncommon. If the block has never
5918 		 * been written, there is no need to send a BIO_DELETE
5919 		 * for it when it is freed. The gain from avoiding the
5920 		 * TRIMs for the common case of unwritten blocks far
5921 		 * exceeds the cost of the write amplification for the
5922 		 * uncommon case of failing to send a TRIM for a block
5923 		 * that had been written.
5924 		 */
5925 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5926 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5927 	else
5928 		freefrag = NULL;
5929 
5930 	ACQUIRE_LOCK(ump);
5931 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5932 		panic("softdep_setup_allocext: lost block");
5933 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5934 	    ("softdep_setup_allocext: newblk already initialized"));
5935 	/*
5936 	 * Convert the newblk to an allocdirect.
5937 	 */
5938 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5939 	adp = (struct allocdirect *)newblk;
5940 	newblk->nb_freefrag = freefrag;
5941 	adp->ad_offset = off;
5942 	adp->ad_oldblkno = oldblkno;
5943 	adp->ad_newsize = newsize;
5944 	adp->ad_oldsize = oldsize;
5945 	adp->ad_state |=  EXTDATA;
5946 
5947 	/*
5948 	 * Finish initializing the journal.
5949 	 */
5950 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5951 		jnewblk->jn_ino = ip->i_number;
5952 		jnewblk->jn_lbn = lbn;
5953 		add_to_journal(&jnewblk->jn_list);
5954 	}
5955 	if (freefrag && freefrag->ff_jdep != NULL &&
5956 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5957 		add_to_journal(freefrag->ff_jdep);
5958 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5959 	adp->ad_inodedep = inodedep;
5960 
5961 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5962 	/*
5963 	 * The list of allocdirects must be kept in sorted and ascending
5964 	 * order so that the rollback routines can quickly determine the
5965 	 * first uncommitted block (the size of the file stored on disk
5966 	 * ends at the end of the lowest committed fragment, or if there
5967 	 * are no fragments, at the end of the highest committed block).
5968 	 * Since files generally grow, the typical case is that the new
5969 	 * block is to be added at the end of the list. We speed this
5970 	 * special case by checking against the last allocdirect in the
5971 	 * list before laboriously traversing the list looking for the
5972 	 * insertion point.
5973 	 */
5974 	adphead = &inodedep->id_newextupdt;
5975 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5976 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5977 		/* insert at end of list */
5978 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5979 		if (oldadp != NULL && oldadp->ad_offset == off)
5980 			allocdirect_merge(adphead, adp, oldadp);
5981 		FREE_LOCK(ump);
5982 		return;
5983 	}
5984 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5985 		if (oldadp->ad_offset >= off)
5986 			break;
5987 	}
5988 	if (oldadp == NULL)
5989 		panic("softdep_setup_allocext: lost entry");
5990 	/* insert in middle of list */
5991 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5992 	if (oldadp->ad_offset == off)
5993 		allocdirect_merge(adphead, adp, oldadp);
5994 	FREE_LOCK(ump);
5995 }
5996 
5997 /*
5998  * Indirect block allocation dependencies.
5999  *
6000  * The same dependencies that exist for a direct block also exist when
6001  * a new block is allocated and pointed to by an entry in a block of
6002  * indirect pointers. The undo/redo states described above are also
6003  * used here. Because an indirect block contains many pointers that
6004  * may have dependencies, a second copy of the entire in-memory indirect
6005  * block is kept. The buffer cache copy is always completely up-to-date.
6006  * The second copy, which is used only as a source for disk writes,
6007  * contains only the safe pointers (i.e., those that have no remaining
6008  * update dependencies). The second copy is freed when all pointers
6009  * are safe. The cache is not allowed to replace indirect blocks with
6010  * pending update dependencies. If a buffer containing an indirect
6011  * block with dependencies is written, these routines will mark it
6012  * dirty again. It can only be successfully written once all the
6013  * dependencies are removed. The ffs_fsync routine in conjunction with
6014  * softdep_sync_metadata work together to get all the dependencies
6015  * removed so that a file can be successfully written to disk. Three
6016  * procedures are used when setting up indirect block pointer
6017  * dependencies. The division is necessary because of the organization
6018  * of the "balloc" routine and because of the distinction between file
6019  * pages and file metadata blocks.
6020  */
6021 
6022 /*
6023  * Allocate a new allocindir structure.
6024  */
6025 static struct allocindir *
newallocindir(struct inode * ip,int ptrno,ufs2_daddr_t newblkno,ufs2_daddr_t oldblkno,ufs_lbn_t lbn)6026 newallocindir(
6027 	struct inode *ip,	/* inode for file being extended */
6028 	int ptrno,		/* offset of pointer in indirect block */
6029 	ufs2_daddr_t newblkno,	/* disk block number being added */
6030 	ufs2_daddr_t oldblkno,	/* previous block number, 0 if none */
6031 	ufs_lbn_t lbn)
6032 {
6033 	struct newblk *newblk;
6034 	struct allocindir *aip;
6035 	struct freefrag *freefrag;
6036 	struct jnewblk *jnewblk;
6037 
6038 	if (oldblkno)
6039 		freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
6040 		    SINGLETON_KEY);
6041 	else
6042 		freefrag = NULL;
6043 	ACQUIRE_LOCK(ITOUMP(ip));
6044 	if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
6045 		panic("new_allocindir: lost block");
6046 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
6047 	    ("newallocindir: newblk already initialized"));
6048 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
6049 	newblk->nb_freefrag = freefrag;
6050 	aip = (struct allocindir *)newblk;
6051 	aip->ai_offset = ptrno;
6052 	aip->ai_oldblkno = oldblkno;
6053 	aip->ai_lbn = lbn;
6054 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
6055 		jnewblk->jn_ino = ip->i_number;
6056 		jnewblk->jn_lbn = lbn;
6057 		add_to_journal(&jnewblk->jn_list);
6058 	}
6059 	if (freefrag && freefrag->ff_jdep != NULL &&
6060 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
6061 		add_to_journal(freefrag->ff_jdep);
6062 	return (aip);
6063 }
6064 
6065 /*
6066  * Called just before setting an indirect block pointer
6067  * to a newly allocated file page.
6068  */
6069 void
softdep_setup_allocindir_page(struct inode * ip,ufs_lbn_t lbn,struct buf * bp,int ptrno,ufs2_daddr_t newblkno,ufs2_daddr_t oldblkno,struct buf * nbp)6070 softdep_setup_allocindir_page(
6071 	struct inode *ip,	/* inode for file being extended */
6072 	ufs_lbn_t lbn,		/* allocated block number within file */
6073 	struct buf *bp,		/* buffer with indirect blk referencing page */
6074 	int ptrno,		/* offset of pointer in indirect block */
6075 	ufs2_daddr_t newblkno,	/* disk block number being added */
6076 	ufs2_daddr_t oldblkno,	/* previous block number, 0 if none */
6077 	struct buf *nbp)	/* buffer holding allocated page */
6078 {
6079 	struct inodedep *inodedep;
6080 	struct freefrag *freefrag;
6081 	struct allocindir *aip;
6082 	struct pagedep *pagedep;
6083 	struct mount *mp;
6084 	struct ufsmount *ump;
6085 
6086 	mp = ITOVFS(ip);
6087 	ump = VFSTOUFS(mp);
6088 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6089 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
6090 	KASSERT(lbn == nbp->b_lblkno,
6091 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
6092 	    lbn, bp->b_lblkno));
6093 	CTR4(KTR_SUJ,
6094 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
6095 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
6096 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
6097 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
6098 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6099 	/*
6100 	 * If we are allocating a directory page, then we must
6101 	 * allocate an associated pagedep to track additions and
6102 	 * deletions.
6103 	 */
6104 	if ((ip->i_mode & IFMT) == IFDIR)
6105 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
6106 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
6107 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
6108 	FREE_LOCK(ump);
6109 	if (freefrag)
6110 		handle_workitem_freefrag(freefrag);
6111 }
6112 
6113 /*
6114  * Called just before setting an indirect block pointer to a
6115  * newly allocated indirect block.
6116  */
6117 void
softdep_setup_allocindir_meta(struct buf * nbp,struct inode * ip,struct buf * bp,int ptrno,ufs2_daddr_t newblkno)6118 softdep_setup_allocindir_meta(
6119 	struct buf *nbp,	/* newly allocated indirect block */
6120 	struct inode *ip,	/* inode for file being extended */
6121 	struct buf *bp,		/* indirect block referencing allocated block */
6122 	int ptrno,		/* offset of pointer in indirect block */
6123 	ufs2_daddr_t newblkno)	/* disk block number being added */
6124 {
6125 	struct inodedep *inodedep;
6126 	struct allocindir *aip;
6127 	struct ufsmount *ump;
6128 	ufs_lbn_t lbn;
6129 
6130 	ump = ITOUMP(ip);
6131 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6132 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
6133 	CTR3(KTR_SUJ,
6134 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
6135 	    ip->i_number, newblkno, ptrno);
6136 	lbn = nbp->b_lblkno;
6137 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
6138 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
6139 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
6140 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
6141 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
6142 		panic("softdep_setup_allocindir_meta: Block already existed");
6143 	FREE_LOCK(ump);
6144 }
6145 
6146 static void
indirdep_complete(struct indirdep * indirdep)6147 indirdep_complete(struct indirdep *indirdep)
6148 {
6149 	struct allocindir *aip;
6150 
6151 	LIST_REMOVE(indirdep, ir_next);
6152 	indirdep->ir_state |= DEPCOMPLETE;
6153 
6154 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
6155 		LIST_REMOVE(aip, ai_next);
6156 		free_newblk(&aip->ai_block);
6157 	}
6158 	/*
6159 	 * If this indirdep is not attached to a buf it was simply waiting
6160 	 * on completion to clear completehd.  free_indirdep() asserts
6161 	 * that nothing is dangling.
6162 	 */
6163 	if ((indirdep->ir_state & ONWORKLIST) == 0)
6164 		free_indirdep(indirdep);
6165 }
6166 
6167 static struct indirdep *
indirdep_lookup(struct mount * mp,struct inode * ip,struct buf * bp)6168 indirdep_lookup(struct mount *mp,
6169 	struct inode *ip,
6170 	struct buf *bp)
6171 {
6172 	struct indirdep *indirdep, *newindirdep;
6173 	struct newblk *newblk;
6174 	struct ufsmount *ump;
6175 	struct worklist *wk;
6176 	struct fs *fs;
6177 	ufs2_daddr_t blkno;
6178 
6179 	ump = VFSTOUFS(mp);
6180 	LOCK_OWNED(ump);
6181 	indirdep = NULL;
6182 	newindirdep = NULL;
6183 	fs = ump->um_fs;
6184 	for (;;) {
6185 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
6186 			if (wk->wk_type != D_INDIRDEP)
6187 				continue;
6188 			indirdep = WK_INDIRDEP(wk);
6189 			break;
6190 		}
6191 		/* Found on the buffer worklist, no new structure to free. */
6192 		if (indirdep != NULL && newindirdep == NULL)
6193 			return (indirdep);
6194 		if (indirdep != NULL && newindirdep != NULL)
6195 			panic("indirdep_lookup: simultaneous create");
6196 		/* None found on the buffer and a new structure is ready. */
6197 		if (indirdep == NULL && newindirdep != NULL)
6198 			break;
6199 		/* None found and no new structure available. */
6200 		FREE_LOCK(ump);
6201 		newindirdep = malloc(sizeof(struct indirdep),
6202 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
6203 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
6204 		newindirdep->ir_state = ATTACHED;
6205 		if (I_IS_UFS1(ip))
6206 			newindirdep->ir_state |= UFS1FMT;
6207 		TAILQ_INIT(&newindirdep->ir_trunc);
6208 		newindirdep->ir_saveddata = NULL;
6209 		LIST_INIT(&newindirdep->ir_deplisthd);
6210 		LIST_INIT(&newindirdep->ir_donehd);
6211 		LIST_INIT(&newindirdep->ir_writehd);
6212 		LIST_INIT(&newindirdep->ir_completehd);
6213 		if (bp->b_blkno == bp->b_lblkno) {
6214 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6215 			    NULL, NULL);
6216 			bp->b_blkno = blkno;
6217 		}
6218 		newindirdep->ir_freeblks = NULL;
6219 		newindirdep->ir_savebp =
6220 		    getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6221 		newindirdep->ir_bp = bp;
6222 		BUF_KERNPROC(newindirdep->ir_savebp);
6223 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6224 		ACQUIRE_LOCK(ump);
6225 	}
6226 	indirdep = newindirdep;
6227 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6228 	/*
6229 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
6230 	 * that we don't free dependencies until the pointers are valid.
6231 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6232 	 * than using the hash.
6233 	 */
6234 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6235 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6236 	else
6237 		indirdep->ir_state |= DEPCOMPLETE;
6238 	return (indirdep);
6239 }
6240 
6241 /*
6242  * Called to finish the allocation of the "aip" allocated
6243  * by one of the two routines above.
6244  */
6245 static struct freefrag *
setup_allocindir_phase2(struct buf * bp,struct inode * ip,struct inodedep * inodedep,struct allocindir * aip,ufs_lbn_t lbn)6246 setup_allocindir_phase2(
6247 	struct buf *bp,		/* in-memory copy of the indirect block */
6248 	struct inode *ip,	/* inode for file being extended */
6249 	struct inodedep *inodedep, /* Inodedep for ip */
6250 	struct allocindir *aip,	/* allocindir allocated by the above routines */
6251 	ufs_lbn_t lbn)		/* Logical block number for this block. */
6252 {
6253 	struct fs *fs __diagused;
6254 	struct indirdep *indirdep;
6255 	struct allocindir *oldaip;
6256 	struct freefrag *freefrag;
6257 	struct mount *mp;
6258 	struct ufsmount *ump;
6259 
6260 	mp = ITOVFS(ip);
6261 	ump = VFSTOUFS(mp);
6262 	LOCK_OWNED(ump);
6263 	fs = ump->um_fs;
6264 	if (bp->b_lblkno >= 0)
6265 		panic("setup_allocindir_phase2: not indir blk");
6266 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6267 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6268 	indirdep = indirdep_lookup(mp, ip, bp);
6269 	KASSERT(indirdep->ir_savebp != NULL,
6270 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6271 	aip->ai_indirdep = indirdep;
6272 	/*
6273 	 * Check for an unwritten dependency for this indirect offset.  If
6274 	 * there is, merge the old dependency into the new one.  This happens
6275 	 * as a result of reallocblk only.
6276 	 */
6277 	freefrag = NULL;
6278 	if (aip->ai_oldblkno != 0) {
6279 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6280 			if (oldaip->ai_offset == aip->ai_offset) {
6281 				freefrag = allocindir_merge(aip, oldaip);
6282 				goto done;
6283 			}
6284 		}
6285 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6286 			if (oldaip->ai_offset == aip->ai_offset) {
6287 				freefrag = allocindir_merge(aip, oldaip);
6288 				goto done;
6289 			}
6290 		}
6291 	}
6292 done:
6293 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6294 	return (freefrag);
6295 }
6296 
6297 /*
6298  * Merge two allocindirs which refer to the same block.  Move newblock
6299  * dependencies and setup the freefrags appropriately.
6300  */
6301 static struct freefrag *
allocindir_merge(struct allocindir * aip,struct allocindir * oldaip)6302 allocindir_merge(
6303 	struct allocindir *aip,
6304 	struct allocindir *oldaip)
6305 {
6306 	struct freefrag *freefrag;
6307 	struct worklist *wk;
6308 
6309 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6310 		panic("allocindir_merge: blkno");
6311 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6312 	freefrag = aip->ai_freefrag;
6313 	aip->ai_freefrag = oldaip->ai_freefrag;
6314 	oldaip->ai_freefrag = NULL;
6315 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6316 	/*
6317 	 * If we are tracking a new directory-block allocation,
6318 	 * move it from the old allocindir to the new allocindir.
6319 	 */
6320 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6321 		WORKLIST_REMOVE(wk);
6322 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6323 			panic("allocindir_merge: extra newdirblk");
6324 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6325 	}
6326 	/*
6327 	 * We can skip journaling for this freefrag and just complete
6328 	 * any pending journal work for the allocindir that is being
6329 	 * removed after the freefrag completes.
6330 	 */
6331 	if (freefrag->ff_jdep)
6332 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6333 	LIST_REMOVE(oldaip, ai_next);
6334 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6335 	    &freefrag->ff_list, &freefrag->ff_jwork);
6336 	free_newblk(&oldaip->ai_block);
6337 
6338 	return (freefrag);
6339 }
6340 
6341 static inline void
setup_freedirect(struct freeblks * freeblks,struct inode * ip,int i,int needj)6342 setup_freedirect(
6343 	struct freeblks *freeblks,
6344 	struct inode *ip,
6345 	int i,
6346 	int needj)
6347 {
6348 	struct ufsmount *ump;
6349 	ufs2_daddr_t blkno;
6350 	int frags;
6351 
6352 	blkno = DIP(ip, i_db[i]);
6353 	if (blkno == 0)
6354 		return;
6355 	DIP_SET(ip, i_db[i], 0);
6356 	ump = ITOUMP(ip);
6357 	frags = sblksize(ump->um_fs, ip->i_size, i);
6358 	frags = numfrags(ump->um_fs, frags);
6359 	newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6360 }
6361 
6362 static inline void
setup_freeext(struct freeblks * freeblks,struct inode * ip,int i,int needj)6363 setup_freeext(
6364 	struct freeblks *freeblks,
6365 	struct inode *ip,
6366 	int i,
6367 	int needj)
6368 {
6369 	struct ufsmount *ump;
6370 	ufs2_daddr_t blkno;
6371 	int frags;
6372 
6373 	blkno = ip->i_din2->di_extb[i];
6374 	if (blkno == 0)
6375 		return;
6376 	ip->i_din2->di_extb[i] = 0;
6377 	ump = ITOUMP(ip);
6378 	frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6379 	frags = numfrags(ump->um_fs, frags);
6380 	newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6381 }
6382 
6383 static inline void
setup_freeindir(struct freeblks * freeblks,struct inode * ip,int i,ufs_lbn_t lbn,int needj)6384 setup_freeindir(
6385 	struct freeblks *freeblks,
6386 	struct inode *ip,
6387 	int i,
6388 	ufs_lbn_t lbn,
6389 	int needj)
6390 {
6391 	struct ufsmount *ump;
6392 	ufs2_daddr_t blkno;
6393 
6394 	blkno = DIP(ip, i_ib[i]);
6395 	if (blkno == 0)
6396 		return;
6397 	DIP_SET(ip, i_ib[i], 0);
6398 	ump = ITOUMP(ip);
6399 	newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6400 	    0, needj);
6401 }
6402 
6403 static inline struct freeblks *
newfreeblks(struct mount * mp,struct inode * ip)6404 newfreeblks(struct mount *mp, struct inode *ip)
6405 {
6406 	struct freeblks *freeblks;
6407 
6408 	freeblks = malloc(sizeof(struct freeblks),
6409 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6410 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6411 	LIST_INIT(&freeblks->fb_jblkdephd);
6412 	LIST_INIT(&freeblks->fb_jwork);
6413 	freeblks->fb_ref = 0;
6414 	freeblks->fb_cgwait = 0;
6415 	freeblks->fb_state = ATTACHED;
6416 	freeblks->fb_uid = ip->i_uid;
6417 	freeblks->fb_inum = ip->i_number;
6418 	freeblks->fb_vtype = ITOV(ip)->v_type;
6419 	freeblks->fb_modrev = DIP(ip, i_modrev);
6420 	freeblks->fb_devvp = ITODEVVP(ip);
6421 	freeblks->fb_chkcnt = 0;
6422 	freeblks->fb_len = 0;
6423 
6424 	return (freeblks);
6425 }
6426 
6427 static void
trunc_indirdep(struct indirdep * indirdep,struct freeblks * freeblks,struct buf * bp,int off)6428 trunc_indirdep(
6429 	struct indirdep *indirdep,
6430 	struct freeblks *freeblks,
6431 	struct buf *bp,
6432 	int off)
6433 {
6434 	struct allocindir *aip, *aipn;
6435 
6436 	/*
6437 	 * The first set of allocindirs won't be in savedbp.
6438 	 */
6439 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6440 		if (aip->ai_offset > off)
6441 			cancel_allocindir(aip, bp, freeblks, 1);
6442 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6443 		if (aip->ai_offset > off)
6444 			cancel_allocindir(aip, bp, freeblks, 1);
6445 	/*
6446 	 * These will exist in savedbp.
6447 	 */
6448 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6449 		if (aip->ai_offset > off)
6450 			cancel_allocindir(aip, NULL, freeblks, 0);
6451 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6452 		if (aip->ai_offset > off)
6453 			cancel_allocindir(aip, NULL, freeblks, 0);
6454 }
6455 
6456 /*
6457  * Follow the chain of indirects down to lastlbn creating a freework
6458  * structure for each.  This will be used to start indir_trunc() at
6459  * the right offset and create the journal records for the parrtial
6460  * truncation.  A second step will handle the truncated dependencies.
6461  */
6462 static int
setup_trunc_indir(struct freeblks * freeblks,struct inode * ip,ufs_lbn_t lbn,ufs_lbn_t lastlbn,ufs2_daddr_t blkno)6463 setup_trunc_indir(
6464 	struct freeblks *freeblks,
6465 	struct inode *ip,
6466 	ufs_lbn_t lbn,
6467 	ufs_lbn_t lastlbn,
6468 	ufs2_daddr_t blkno)
6469 {
6470 	struct indirdep *indirdep;
6471 	struct indirdep *indirn;
6472 	struct freework *freework;
6473 	struct newblk *newblk;
6474 	struct mount *mp;
6475 	struct ufsmount *ump;
6476 	struct buf *bp;
6477 	uint8_t *start;
6478 	uint8_t *end;
6479 	ufs_lbn_t lbnadd;
6480 	int level;
6481 	int error;
6482 	int off;
6483 
6484 	freework = NULL;
6485 	if (blkno == 0)
6486 		return (0);
6487 	mp = freeblks->fb_list.wk_mp;
6488 	ump = VFSTOUFS(mp);
6489 	/*
6490 	 * Here, calls to VOP_BMAP() will fail.  However, we already have
6491 	 * the on-disk address, so we just pass it to bread() instead of
6492 	 * having bread() attempt to calculate it using VOP_BMAP().
6493 	 */
6494 	error = ffs_breadz(ump, ITOV(ip), lbn, blkptrtodb(ump, blkno),
6495 	    (int)mp->mnt_stat.f_iosize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
6496 	if (error)
6497 		return (error);
6498 	level = lbn_level(lbn);
6499 	lbnadd = lbn_offset(ump->um_fs, level);
6500 	/*
6501 	 * Compute the offset of the last block we want to keep.  Store
6502 	 * in the freework the first block we want to completely free.
6503 	 */
6504 	off = (lastlbn - -(lbn + level)) / lbnadd;
6505 	if (off + 1 == NINDIR(ump->um_fs))
6506 		goto nowork;
6507 	freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6508 	/*
6509 	 * Link the freework into the indirdep.  This will prevent any new
6510 	 * allocations from proceeding until we are finished with the
6511 	 * truncate and the block is written.
6512 	 */
6513 	ACQUIRE_LOCK(ump);
6514 	indirdep = indirdep_lookup(mp, ip, bp);
6515 	if (indirdep->ir_freeblks)
6516 		panic("setup_trunc_indir: indirdep already truncated.");
6517 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6518 	freework->fw_indir = indirdep;
6519 	/*
6520 	 * Cancel any allocindirs that will not make it to disk.
6521 	 * We have to do this for all copies of the indirdep that
6522 	 * live on this newblk.
6523 	 */
6524 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6525 		if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6526 		    &newblk) == 0)
6527 			panic("setup_trunc_indir: lost block");
6528 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6529 			trunc_indirdep(indirn, freeblks, bp, off);
6530 	} else
6531 		trunc_indirdep(indirdep, freeblks, bp, off);
6532 	FREE_LOCK(ump);
6533 	/*
6534 	 * Creation is protected by the buf lock. The saveddata is only
6535 	 * needed if a full truncation follows a partial truncation but it
6536 	 * is difficult to allocate in that case so we fetch it anyway.
6537 	 */
6538 	if (indirdep->ir_saveddata == NULL)
6539 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6540 		    M_SOFTDEP_FLAGS);
6541 nowork:
6542 	/* Fetch the blkno of the child and the zero start offset. */
6543 	if (I_IS_UFS1(ip)) {
6544 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6545 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6546 	} else {
6547 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6548 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6549 	}
6550 	if (freework) {
6551 		/* Zero the truncated pointers. */
6552 		end = bp->b_data + bp->b_bcount;
6553 		bzero(start, end - start);
6554 		bdwrite(bp);
6555 	} else
6556 		bqrelse(bp);
6557 	if (level == 0)
6558 		return (0);
6559 	lbn++; /* adjust level */
6560 	lbn -= (off * lbnadd);
6561 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6562 }
6563 
6564 /*
6565  * Complete the partial truncation of an indirect block setup by
6566  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6567  * copy and writes them to disk before the freeblks is allowed to complete.
6568  */
6569 static void
complete_trunc_indir(struct freework * freework)6570 complete_trunc_indir(struct freework *freework)
6571 {
6572 	struct freework *fwn;
6573 	struct indirdep *indirdep;
6574 	struct ufsmount *ump;
6575 	struct buf *bp;
6576 	uintptr_t start;
6577 	int count;
6578 
6579 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6580 	LOCK_OWNED(ump);
6581 	indirdep = freework->fw_indir;
6582 	for (;;) {
6583 		bp = indirdep->ir_bp;
6584 		/* See if the block was discarded. */
6585 		if (bp == NULL)
6586 			break;
6587 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6588 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6589 			break;
6590 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6591 		    LOCK_PTR(ump)) == 0)
6592 			BUF_UNLOCK(bp);
6593 		ACQUIRE_LOCK(ump);
6594 	}
6595 	freework->fw_state |= DEPCOMPLETE;
6596 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6597 	/*
6598 	 * Zero the pointers in the saved copy.
6599 	 */
6600 	if (indirdep->ir_state & UFS1FMT)
6601 		start = sizeof(ufs1_daddr_t);
6602 	else
6603 		start = sizeof(ufs2_daddr_t);
6604 	start *= freework->fw_start;
6605 	count = indirdep->ir_savebp->b_bcount - start;
6606 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6607 	bzero((char *)start, count);
6608 	/*
6609 	 * We need to start the next truncation in the list if it has not
6610 	 * been started yet.
6611 	 */
6612 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6613 	if (fwn != NULL) {
6614 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6615 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6616 		if ((fwn->fw_state & ONWORKLIST) == 0)
6617 			freework_enqueue(fwn);
6618 	}
6619 	/*
6620 	 * If bp is NULL the block was fully truncated, restore
6621 	 * the saved block list otherwise free it if it is no
6622 	 * longer needed.
6623 	 */
6624 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6625 		if (bp == NULL)
6626 			bcopy(indirdep->ir_saveddata,
6627 			    indirdep->ir_savebp->b_data,
6628 			    indirdep->ir_savebp->b_bcount);
6629 		free(indirdep->ir_saveddata, M_INDIRDEP);
6630 		indirdep->ir_saveddata = NULL;
6631 	}
6632 	/*
6633 	 * When bp is NULL there is a full truncation pending.  We
6634 	 * must wait for this full truncation to be journaled before
6635 	 * we can release this freework because the disk pointers will
6636 	 * never be written as zero.
6637 	 */
6638 	if (bp == NULL)  {
6639 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6640 			handle_written_freework(freework);
6641 		else
6642 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6643 			   &freework->fw_list);
6644 		if (fwn == NULL) {
6645 			freework->fw_indir = (void *)0x0000deadbeef0000;
6646 			bp = indirdep->ir_savebp;
6647 			indirdep->ir_savebp = NULL;
6648 			free_indirdep(indirdep);
6649 			FREE_LOCK(ump);
6650 			brelse(bp);
6651 			ACQUIRE_LOCK(ump);
6652 		}
6653 	} else {
6654 		/* Complete when the real copy is written. */
6655 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6656 		BUF_UNLOCK(bp);
6657 	}
6658 }
6659 
6660 /*
6661  * Calculate the number of blocks we are going to release where datablocks
6662  * is the current total and length is the new file size.
6663  */
6664 static ufs2_daddr_t
blkcount(struct fs * fs,ufs2_daddr_t datablocks,off_t length)6665 blkcount(struct fs *fs,
6666 	ufs2_daddr_t datablocks,
6667 	off_t length)
6668 {
6669 	off_t totblks, numblks;
6670 
6671 	totblks = 0;
6672 	numblks = howmany(length, fs->fs_bsize);
6673 	if (numblks <= UFS_NDADDR) {
6674 		totblks = howmany(length, fs->fs_fsize);
6675 		goto out;
6676 	}
6677         totblks = blkstofrags(fs, numblks);
6678 	numblks -= UFS_NDADDR;
6679 	/*
6680 	 * Count all single, then double, then triple indirects required.
6681 	 * Subtracting one indirects worth of blocks for each pass
6682 	 * acknowledges one of each pointed to by the inode.
6683 	 */
6684 	for (;;) {
6685 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6686 		numblks -= NINDIR(fs);
6687 		if (numblks <= 0)
6688 			break;
6689 		numblks = howmany(numblks, NINDIR(fs));
6690 	}
6691 out:
6692 	totblks = fsbtodb(fs, totblks);
6693 	/*
6694 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6695 	 * references.  We will correct it later in handle_complete_freeblks()
6696 	 * when we know the real count.
6697 	 */
6698 	if (totblks > datablocks)
6699 		return (0);
6700 	return (datablocks - totblks);
6701 }
6702 
6703 /*
6704  * Handle freeblocks for journaled softupdate filesystems.
6705  *
6706  * Contrary to normal softupdates, we must preserve the block pointers in
6707  * indirects until their subordinates are free.  This is to avoid journaling
6708  * every block that is freed which may consume more space than the journal
6709  * itself.  The recovery program will see the free block journals at the
6710  * base of the truncated area and traverse them to reclaim space.  The
6711  * pointers in the inode may be cleared immediately after the journal
6712  * records are written because each direct and indirect pointer in the
6713  * inode is recorded in a journal.  This permits full truncation to proceed
6714  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6715  *
6716  * The algorithm is as follows:
6717  * 1) Traverse the in-memory state and create journal entries to release
6718  *    the relevant blocks and full indirect trees.
6719  * 2) Traverse the indirect block chain adding partial truncation freework
6720  *    records to indirects in the path to lastlbn.  The freework will
6721  *    prevent new allocation dependencies from being satisfied in this
6722  *    indirect until the truncation completes.
6723  * 3) Read and lock the inode block, performing an update with the new size
6724  *    and pointers.  This prevents truncated data from becoming valid on
6725  *    disk through step 4.
6726  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6727  *    eliminate journal work for those records that do not require it.
6728  * 5) Schedule the journal records to be written followed by the inode block.
6729  * 6) Allocate any necessary frags for the end of file.
6730  * 7) Zero any partially truncated blocks.
6731  *
6732  * From this truncation proceeds asynchronously using the freework and
6733  * indir_trunc machinery.  The file will not be extended again into a
6734  * partially truncated indirect block until all work is completed but
6735  * the normal dependency mechanism ensures that it is rolled back/forward
6736  * as appropriate.  Further truncation may occur without delay and is
6737  * serialized in indir_trunc().
6738  */
6739 void
softdep_journal_freeblocks(struct inode * ip,struct ucred * cred,off_t length,int flags)6740 softdep_journal_freeblocks(
6741 	struct inode *ip,	/* The inode whose length is to be reduced */
6742 	struct ucred *cred,
6743 	off_t length,		/* The new length for the file */
6744 	int flags)		/* IO_EXT and/or IO_NORMAL */
6745 {
6746 	struct freeblks *freeblks, *fbn;
6747 	struct worklist *wk, *wkn;
6748 	struct inodedep *inodedep;
6749 	struct jblkdep *jblkdep;
6750 	struct allocdirect *adp, *adpn;
6751 	struct ufsmount *ump;
6752 	struct fs *fs;
6753 	struct buf *bp;
6754 	struct vnode *vp;
6755 	struct mount *mp;
6756 	daddr_t dbn;
6757 	ufs2_daddr_t extblocks, datablocks;
6758 	ufs_lbn_t tmpval, lbn, lastlbn;
6759 	int frags, lastoff, iboff, allocblock, needj, error, i;
6760 
6761 	ump = ITOUMP(ip);
6762 	mp = UFSTOVFS(ump);
6763 	fs = ump->um_fs;
6764 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6765 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6766 	vp = ITOV(ip);
6767 	needj = 1;
6768 	iboff = -1;
6769 	allocblock = 0;
6770 	extblocks = 0;
6771 	datablocks = 0;
6772 	frags = 0;
6773 	freeblks = newfreeblks(mp, ip);
6774 	ACQUIRE_LOCK(ump);
6775 	/*
6776 	 * If we're truncating a removed file that will never be written
6777 	 * we don't need to journal the block frees.  The canceled journals
6778 	 * for the allocations will suffice.
6779 	 */
6780 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6781 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6782 	    length == 0)
6783 		needj = 0;
6784 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6785 	    ip->i_number, length, needj);
6786 	FREE_LOCK(ump);
6787 	/*
6788 	 * Calculate the lbn that we are truncating to.  This results in -1
6789 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6790 	 * to keep, not the first lbn we want to truncate.
6791 	 */
6792 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6793 	lastoff = blkoff(fs, length);
6794 	/*
6795 	 * Compute frags we are keeping in lastlbn.  0 means all.
6796 	 */
6797 	if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6798 		frags = fragroundup(fs, lastoff);
6799 		/* adp offset of last valid allocdirect. */
6800 		iboff = lastlbn;
6801 	} else if (lastlbn > 0)
6802 		iboff = UFS_NDADDR;
6803 	if (fs->fs_magic == FS_UFS2_MAGIC)
6804 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6805 	/*
6806 	 * Handle normal data blocks and indirects.  This section saves
6807 	 * values used after the inode update to complete frag and indirect
6808 	 * truncation.
6809 	 */
6810 	if ((flags & IO_NORMAL) != 0) {
6811 		/*
6812 		 * Handle truncation of whole direct and indirect blocks.
6813 		 */
6814 		for (i = iboff + 1; i < UFS_NDADDR; i++)
6815 			setup_freedirect(freeblks, ip, i, needj);
6816 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6817 		    i < UFS_NIADDR;
6818 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6819 			/* Release a whole indirect tree. */
6820 			if (lbn > lastlbn) {
6821 				setup_freeindir(freeblks, ip, i, -lbn -i,
6822 				    needj);
6823 				continue;
6824 			}
6825 			iboff = i + UFS_NDADDR;
6826 			/*
6827 			 * Traverse partially truncated indirect tree.
6828 			 */
6829 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6830 				setup_trunc_indir(freeblks, ip, -lbn - i,
6831 				    lastlbn, DIP(ip, i_ib[i]));
6832 		}
6833 		/*
6834 		 * Handle partial truncation to a frag boundary.
6835 		 */
6836 		if (frags) {
6837 			ufs2_daddr_t blkno;
6838 			long oldfrags;
6839 
6840 			oldfrags = blksize(fs, ip, lastlbn);
6841 			blkno = DIP(ip, i_db[lastlbn]);
6842 			if (blkno && oldfrags != frags) {
6843 				oldfrags -= frags;
6844 				oldfrags = numfrags(fs, oldfrags);
6845 				blkno += numfrags(fs, frags);
6846 				newfreework(ump, freeblks, NULL, lastlbn,
6847 				    blkno, oldfrags, 0, needj);
6848 				if (needj)
6849 					adjust_newfreework(freeblks,
6850 					    numfrags(fs, frags));
6851 			} else if (blkno == 0)
6852 				allocblock = 1;
6853 		}
6854 		/*
6855 		 * Add a journal record for partial truncate if we are
6856 		 * handling indirect blocks.  Non-indirects need no extra
6857 		 * journaling.
6858 		 */
6859 		if (length != 0 && lastlbn >= UFS_NDADDR) {
6860 			UFS_INODE_SET_FLAG(ip, IN_TRUNCATED);
6861 			newjtrunc(freeblks, length, 0);
6862 		}
6863 		ip->i_size = length;
6864 		DIP_SET(ip, i_size, ip->i_size);
6865 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
6866 		datablocks = DIP(ip, i_blocks) - extblocks;
6867 		if (length != 0)
6868 			datablocks = blkcount(fs, datablocks, length);
6869 		freeblks->fb_len = length;
6870 	}
6871 	if ((flags & IO_EXT) != 0) {
6872 		for (i = 0; i < UFS_NXADDR; i++)
6873 			setup_freeext(freeblks, ip, i, needj);
6874 		ip->i_din2->di_extsize = 0;
6875 		datablocks += extblocks;
6876 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
6877 	}
6878 #ifdef QUOTA
6879 	/* Reference the quotas in case the block count is wrong in the end. */
6880 	quotaref(vp, freeblks->fb_quota);
6881 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
6882 #endif
6883 	freeblks->fb_chkcnt = -datablocks;
6884 	UFS_LOCK(ump);
6885 	fs->fs_pendingblocks += datablocks;
6886 	UFS_UNLOCK(ump);
6887 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6888 	/*
6889 	 * Handle truncation of incomplete alloc direct dependencies.  We
6890 	 * hold the inode block locked to prevent incomplete dependencies
6891 	 * from reaching the disk while we are eliminating those that
6892 	 * have been truncated.  This is a partially inlined ffs_update().
6893 	 */
6894 	ufs_itimes(vp);
6895 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6896 	dbn = fsbtodb(fs, ino_to_fsba(fs, ip->i_number));
6897 	error = ffs_breadz(ump, ump->um_devvp, dbn, dbn, (int)fs->fs_bsize,
6898 	    NULL, NULL, 0, cred, 0, NULL, &bp);
6899 	if (error) {
6900 		softdep_error("softdep_journal_freeblocks", error);
6901 		return;
6902 	}
6903 	if (bp->b_bufsize == fs->fs_bsize)
6904 		bp->b_flags |= B_CLUSTEROK;
6905 	softdep_update_inodeblock(ip, bp, 0);
6906 	if (ump->um_fstype == UFS1) {
6907 		*((struct ufs1_dinode *)bp->b_data +
6908 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6909 	} else {
6910 		ffs_update_dinode_ckhash(fs, ip->i_din2);
6911 		*((struct ufs2_dinode *)bp->b_data +
6912 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6913 	}
6914 	ACQUIRE_LOCK(ump);
6915 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6916 	if ((inodedep->id_state & IOSTARTED) != 0)
6917 		panic("softdep_setup_freeblocks: inode busy");
6918 	/*
6919 	 * Add the freeblks structure to the list of operations that
6920 	 * must await the zero'ed inode being written to disk. If we
6921 	 * still have a bitmap dependency (needj), then the inode
6922 	 * has never been written to disk, so we can process the
6923 	 * freeblks below once we have deleted the dependencies.
6924 	 */
6925 	if (needj)
6926 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6927 	else
6928 		freeblks->fb_state |= COMPLETE;
6929 	if ((flags & IO_NORMAL) != 0) {
6930 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6931 			if (adp->ad_offset > iboff)
6932 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
6933 				    freeblks);
6934 			/*
6935 			 * Truncate the allocdirect.  We could eliminate
6936 			 * or modify journal records as well.
6937 			 */
6938 			else if (adp->ad_offset == iboff && frags)
6939 				adp->ad_newsize = frags;
6940 		}
6941 	}
6942 	if ((flags & IO_EXT) != 0)
6943 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6944 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6945 			    freeblks);
6946 	/*
6947 	 * Scan the bufwait list for newblock dependencies that will never
6948 	 * make it to disk.
6949 	 */
6950 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6951 		if (wk->wk_type != D_ALLOCDIRECT)
6952 			continue;
6953 		adp = WK_ALLOCDIRECT(wk);
6954 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6955 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6956 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
6957 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6958 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6959 		}
6960 	}
6961 	/*
6962 	 * Add journal work.
6963 	 */
6964 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6965 		add_to_journal(&jblkdep->jb_list);
6966 	FREE_LOCK(ump);
6967 	bdwrite(bp);
6968 	/*
6969 	 * Truncate dependency structures beyond length.
6970 	 */
6971 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6972 	/*
6973 	 * This is only set when we need to allocate a fragment because
6974 	 * none existed at the end of a frag-sized file.  It handles only
6975 	 * allocating a new, zero filled block.
6976 	 */
6977 	if (allocblock) {
6978 		ip->i_size = length - lastoff;
6979 		DIP_SET(ip, i_size, ip->i_size);
6980 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6981 		if (error != 0) {
6982 			softdep_error("softdep_journal_freeblks", error);
6983 			return;
6984 		}
6985 		ip->i_size = length;
6986 		DIP_SET(ip, i_size, length);
6987 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
6988 		allocbuf(bp, frags);
6989 		ffs_update(vp, 0);
6990 		bawrite(bp);
6991 	} else if (lastoff != 0 && vp->v_type != VDIR) {
6992 		int size;
6993 
6994 		/*
6995 		 * Zero the end of a truncated frag or block.
6996 		 */
6997 		size = sblksize(fs, length, lastlbn);
6998 		error = bread(vp, lastlbn, size, cred, &bp);
6999 		if (error == 0) {
7000 			bzero((char *)bp->b_data + lastoff, size - lastoff);
7001 			bawrite(bp);
7002 		} else if (!ffs_fsfail_cleanup(ump, error)) {
7003 			softdep_error("softdep_journal_freeblks", error);
7004 			return;
7005 		}
7006 	}
7007 	ACQUIRE_LOCK(ump);
7008 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7009 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
7010 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
7011 	/*
7012 	 * We zero earlier truncations so they don't erroneously
7013 	 * update i_blocks.
7014 	 */
7015 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
7016 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
7017 			fbn->fb_len = 0;
7018 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
7019 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7020 		freeblks->fb_state |= INPROGRESS;
7021 	else
7022 		freeblks = NULL;
7023 	FREE_LOCK(ump);
7024 	if (freeblks)
7025 		handle_workitem_freeblocks(freeblks, 0);
7026 	trunc_pages(ip, length, extblocks, flags);
7027 
7028 }
7029 
7030 /*
7031  * Flush a JOP_SYNC to the journal.
7032  */
7033 void
softdep_journal_fsync(struct inode * ip)7034 softdep_journal_fsync(struct inode *ip)
7035 {
7036 	struct jfsync *jfsync;
7037 	struct ufsmount *ump;
7038 
7039 	ump = ITOUMP(ip);
7040 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7041 	    ("softdep_journal_fsync called on non-softdep filesystem"));
7042 	if ((ip->i_flag & IN_TRUNCATED) == 0)
7043 		return;
7044 	ip->i_flag &= ~IN_TRUNCATED;
7045 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
7046 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
7047 	jfsync->jfs_size = ip->i_size;
7048 	jfsync->jfs_ino = ip->i_number;
7049 	ACQUIRE_LOCK(ump);
7050 	add_to_journal(&jfsync->jfs_list);
7051 	jwait(&jfsync->jfs_list, MNT_WAIT);
7052 	FREE_LOCK(ump);
7053 }
7054 
7055 /*
7056  * Block de-allocation dependencies.
7057  *
7058  * When blocks are de-allocated, the on-disk pointers must be nullified before
7059  * the blocks are made available for use by other files.  (The true
7060  * requirement is that old pointers must be nullified before new on-disk
7061  * pointers are set.  We chose this slightly more stringent requirement to
7062  * reduce complexity.) Our implementation handles this dependency by updating
7063  * the inode (or indirect block) appropriately but delaying the actual block
7064  * de-allocation (i.e., freemap and free space count manipulation) until
7065  * after the updated versions reach stable storage.  After the disk is
7066  * updated, the blocks can be safely de-allocated whenever it is convenient.
7067  * This implementation handles only the common case of reducing a file's
7068  * length to zero. Other cases are handled by the conventional synchronous
7069  * write approach.
7070  *
7071  * The ffs implementation with which we worked double-checks
7072  * the state of the block pointers and file size as it reduces
7073  * a file's length.  Some of this code is replicated here in our
7074  * soft updates implementation.  The freeblks->fb_chkcnt field is
7075  * used to transfer a part of this information to the procedure
7076  * that eventually de-allocates the blocks.
7077  *
7078  * This routine should be called from the routine that shortens
7079  * a file's length, before the inode's size or block pointers
7080  * are modified. It will save the block pointer information for
7081  * later release and zero the inode so that the calling routine
7082  * can release it.
7083  */
7084 void
softdep_setup_freeblocks(struct inode * ip,off_t length,int flags)7085 softdep_setup_freeblocks(
7086 	struct inode *ip,	/* The inode whose length is to be reduced */
7087 	off_t length,		/* The new length for the file */
7088 	int flags)		/* IO_EXT and/or IO_NORMAL */
7089 {
7090 	struct ufs1_dinode *dp1;
7091 	struct ufs2_dinode *dp2;
7092 	struct freeblks *freeblks;
7093 	struct inodedep *inodedep;
7094 	struct allocdirect *adp;
7095 	struct ufsmount *ump;
7096 	struct buf *bp;
7097 	struct fs *fs;
7098 	ufs2_daddr_t extblocks, datablocks;
7099 	struct mount *mp;
7100 	int i, delay, error;
7101 	ufs_lbn_t tmpval;
7102 	ufs_lbn_t lbn;
7103 
7104 	ump = ITOUMP(ip);
7105 	mp = UFSTOVFS(ump);
7106 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
7107 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
7108 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
7109 	    ip->i_number, length);
7110 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
7111 	fs = ump->um_fs;
7112 	if ((error = bread(ump->um_devvp,
7113 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
7114 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
7115 		if (!ffs_fsfail_cleanup(ump, error))
7116 			softdep_error("softdep_setup_freeblocks", error);
7117 		return;
7118 	}
7119 	freeblks = newfreeblks(mp, ip);
7120 	extblocks = 0;
7121 	datablocks = 0;
7122 	if (fs->fs_magic == FS_UFS2_MAGIC)
7123 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
7124 	if ((flags & IO_NORMAL) != 0) {
7125 		for (i = 0; i < UFS_NDADDR; i++)
7126 			setup_freedirect(freeblks, ip, i, 0);
7127 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
7128 		    i < UFS_NIADDR;
7129 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
7130 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
7131 		ip->i_size = 0;
7132 		DIP_SET(ip, i_size, 0);
7133 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7134 		datablocks = DIP(ip, i_blocks) - extblocks;
7135 	}
7136 	if ((flags & IO_EXT) != 0) {
7137 		for (i = 0; i < UFS_NXADDR; i++)
7138 			setup_freeext(freeblks, ip, i, 0);
7139 		ip->i_din2->di_extsize = 0;
7140 		datablocks += extblocks;
7141 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7142 	}
7143 #ifdef QUOTA
7144 	/* Reference the quotas in case the block count is wrong in the end. */
7145 	quotaref(ITOV(ip), freeblks->fb_quota);
7146 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
7147 #endif
7148 	freeblks->fb_chkcnt = -datablocks;
7149 	UFS_LOCK(ump);
7150 	fs->fs_pendingblocks += datablocks;
7151 	UFS_UNLOCK(ump);
7152 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
7153 	/*
7154 	 * Push the zero'ed inode to its disk buffer so that we are free
7155 	 * to delete its dependencies below. Once the dependencies are gone
7156 	 * the buffer can be safely released.
7157 	 */
7158 	if (ump->um_fstype == UFS1) {
7159 		dp1 = ((struct ufs1_dinode *)bp->b_data +
7160 		    ino_to_fsbo(fs, ip->i_number));
7161 		ip->i_din1->di_freelink = dp1->di_freelink;
7162 		*dp1 = *ip->i_din1;
7163 	} else {
7164 		dp2 = ((struct ufs2_dinode *)bp->b_data +
7165 		    ino_to_fsbo(fs, ip->i_number));
7166 		ip->i_din2->di_freelink = dp2->di_freelink;
7167 		ffs_update_dinode_ckhash(fs, ip->i_din2);
7168 		*dp2 = *ip->i_din2;
7169 	}
7170 	/*
7171 	 * Find and eliminate any inode dependencies.
7172 	 */
7173 	ACQUIRE_LOCK(ump);
7174 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7175 	if ((inodedep->id_state & IOSTARTED) != 0)
7176 		panic("softdep_setup_freeblocks: inode busy");
7177 	/*
7178 	 * Add the freeblks structure to the list of operations that
7179 	 * must await the zero'ed inode being written to disk. If we
7180 	 * still have a bitmap dependency (delay == 0), then the inode
7181 	 * has never been written to disk, so we can process the
7182 	 * freeblks below once we have deleted the dependencies.
7183 	 */
7184 	delay = (inodedep->id_state & DEPCOMPLETE);
7185 	if (delay)
7186 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
7187 	else
7188 		freeblks->fb_state |= COMPLETE;
7189 	/*
7190 	 * Because the file length has been truncated to zero, any
7191 	 * pending block allocation dependency structures associated
7192 	 * with this inode are obsolete and can simply be de-allocated.
7193 	 * We must first merge the two dependency lists to get rid of
7194 	 * any duplicate freefrag structures, then purge the merged list.
7195 	 * If we still have a bitmap dependency, then the inode has never
7196 	 * been written to disk, so we can free any fragments without delay.
7197 	 */
7198 	if (flags & IO_NORMAL) {
7199 		merge_inode_lists(&inodedep->id_newinoupdt,
7200 		    &inodedep->id_inoupdt);
7201 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
7202 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
7203 			    freeblks);
7204 	}
7205 	if (flags & IO_EXT) {
7206 		merge_inode_lists(&inodedep->id_newextupdt,
7207 		    &inodedep->id_extupdt);
7208 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7209 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7210 			    freeblks);
7211 	}
7212 	FREE_LOCK(ump);
7213 	bdwrite(bp);
7214 	trunc_dependencies(ip, freeblks, -1, 0, flags);
7215 	ACQUIRE_LOCK(ump);
7216 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7217 		(void) free_inodedep(inodedep);
7218 	freeblks->fb_state |= DEPCOMPLETE;
7219 	/*
7220 	 * If the inode with zeroed block pointers is now on disk
7221 	 * we can start freeing blocks.
7222 	 */
7223 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7224 		freeblks->fb_state |= INPROGRESS;
7225 	else
7226 		freeblks = NULL;
7227 	FREE_LOCK(ump);
7228 	if (freeblks)
7229 		handle_workitem_freeblocks(freeblks, 0);
7230 	trunc_pages(ip, length, extblocks, flags);
7231 }
7232 
7233 /*
7234  * Eliminate pages from the page cache that back parts of this inode and
7235  * adjust the vnode pager's idea of our size.  This prevents stale data
7236  * from hanging around in the page cache.
7237  */
7238 static void
trunc_pages(struct inode * ip,off_t length,ufs2_daddr_t extblocks,int flags)7239 trunc_pages(
7240 	struct inode *ip,
7241 	off_t length,
7242 	ufs2_daddr_t extblocks,
7243 	int flags)
7244 {
7245 	struct vnode *vp;
7246 	struct fs *fs;
7247 	ufs_lbn_t lbn;
7248 	off_t end, extend;
7249 
7250 	vp = ITOV(ip);
7251 	fs = ITOFS(ip);
7252 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7253 	if ((flags & IO_EXT) != 0)
7254 		vn_pages_remove(vp, extend, 0);
7255 	if ((flags & IO_NORMAL) == 0)
7256 		return;
7257 	BO_LOCK(&vp->v_bufobj);
7258 	drain_output(vp);
7259 	BO_UNLOCK(&vp->v_bufobj);
7260 	/*
7261 	 * The vnode pager eliminates file pages we eliminate indirects
7262 	 * below.
7263 	 */
7264 	vnode_pager_setsize(vp, length);
7265 	/*
7266 	 * Calculate the end based on the last indirect we want to keep.  If
7267 	 * the block extends into indirects we can just use the negative of
7268 	 * its lbn.  Doubles and triples exist at lower numbers so we must
7269 	 * be careful not to remove those, if they exist.  double and triple
7270 	 * indirect lbns do not overlap with others so it is not important
7271 	 * to verify how many levels are required.
7272 	 */
7273 	lbn = lblkno(fs, length);
7274 	if (lbn >= UFS_NDADDR) {
7275 		/* Calculate the virtual lbn of the triple indirect. */
7276 		lbn = -lbn - (UFS_NIADDR - 1);
7277 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7278 	} else
7279 		end = extend;
7280 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7281 }
7282 
7283 /*
7284  * See if the buf bp is in the range eliminated by truncation.
7285  */
7286 static int
trunc_check_buf(struct buf * bp,int * blkoffp,ufs_lbn_t lastlbn,int lastoff,int flags)7287 trunc_check_buf(
7288 	struct buf *bp,
7289 	int *blkoffp,
7290 	ufs_lbn_t lastlbn,
7291 	int lastoff,
7292 	int flags)
7293 {
7294 	ufs_lbn_t lbn;
7295 
7296 	*blkoffp = 0;
7297 	/* Only match ext/normal blocks as appropriate. */
7298 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7299 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7300 		return (0);
7301 	/* ALTDATA is always a full truncation. */
7302 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7303 		return (1);
7304 	/* -1 is full truncation. */
7305 	if (lastlbn == -1)
7306 		return (1);
7307 	/*
7308 	 * If this is a partial truncate we only want those
7309 	 * blocks and indirect blocks that cover the range
7310 	 * we're after.
7311 	 */
7312 	lbn = bp->b_lblkno;
7313 	if (lbn < 0)
7314 		lbn = -(lbn + lbn_level(lbn));
7315 	if (lbn < lastlbn)
7316 		return (0);
7317 	/* Here we only truncate lblkno if it's partial. */
7318 	if (lbn == lastlbn) {
7319 		if (lastoff == 0)
7320 			return (0);
7321 		*blkoffp = lastoff;
7322 	}
7323 	return (1);
7324 }
7325 
7326 /*
7327  * Eliminate any dependencies that exist in memory beyond lblkno:off
7328  */
7329 static void
trunc_dependencies(struct inode * ip,struct freeblks * freeblks,ufs_lbn_t lastlbn,int lastoff,int flags)7330 trunc_dependencies(
7331 	struct inode *ip,
7332 	struct freeblks *freeblks,
7333 	ufs_lbn_t lastlbn,
7334 	int lastoff,
7335 	int flags)
7336 {
7337 	struct bufobj *bo;
7338 	struct vnode *vp;
7339 	struct buf *bp;
7340 	int blkoff;
7341 
7342 	/*
7343 	 * We must wait for any I/O in progress to finish so that
7344 	 * all potential buffers on the dirty list will be visible.
7345 	 * Once they are all there, walk the list and get rid of
7346 	 * any dependencies.
7347 	 */
7348 	vp = ITOV(ip);
7349 	bo = &vp->v_bufobj;
7350 	BO_LOCK(bo);
7351 	drain_output(vp);
7352 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7353 		bp->b_vflags &= ~BV_SCANNED;
7354 restart:
7355 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7356 		if (bp->b_vflags & BV_SCANNED)
7357 			continue;
7358 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7359 			bp->b_vflags |= BV_SCANNED;
7360 			continue;
7361 		}
7362 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7363 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7364 			goto restart;
7365 		BO_UNLOCK(bo);
7366 		if (deallocate_dependencies(bp, freeblks, blkoff))
7367 			bqrelse(bp);
7368 		else
7369 			brelse(bp);
7370 		BO_LOCK(bo);
7371 		goto restart;
7372 	}
7373 	/*
7374 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7375 	 */
7376 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7377 		bp->b_vflags &= ~BV_SCANNED;
7378 cleanrestart:
7379 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7380 		if (bp->b_vflags & BV_SCANNED)
7381 			continue;
7382 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7383 			bp->b_vflags |= BV_SCANNED;
7384 			continue;
7385 		}
7386 		if (BUF_LOCK(bp,
7387 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7388 		    BO_LOCKPTR(bo)) == ENOLCK) {
7389 			BO_LOCK(bo);
7390 			goto cleanrestart;
7391 		}
7392 		BO_LOCK(bo);
7393 		bp->b_vflags |= BV_SCANNED;
7394 		BO_UNLOCK(bo);
7395 		bremfree(bp);
7396 		if (blkoff != 0) {
7397 			allocbuf(bp, blkoff);
7398 			bqrelse(bp);
7399 		} else {
7400 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7401 			brelse(bp);
7402 		}
7403 		BO_LOCK(bo);
7404 		goto cleanrestart;
7405 	}
7406 	drain_output(vp);
7407 	BO_UNLOCK(bo);
7408 }
7409 
7410 static int
cancel_pagedep(struct pagedep * pagedep,struct freeblks * freeblks,int blkoff)7411 cancel_pagedep(
7412 	struct pagedep *pagedep,
7413 	struct freeblks *freeblks,
7414 	int blkoff)
7415 {
7416 	struct jremref *jremref;
7417 	struct jmvref *jmvref;
7418 	struct dirrem *dirrem, *tmp;
7419 	int i;
7420 
7421 	/*
7422 	 * Copy any directory remove dependencies to the list
7423 	 * to be processed after the freeblks proceeds.  If
7424 	 * directory entry never made it to disk they
7425 	 * can be dumped directly onto the work list.
7426 	 */
7427 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7428 		/* Skip this directory removal if it is intended to remain. */
7429 		if (dirrem->dm_offset < blkoff)
7430 			continue;
7431 		/*
7432 		 * If there are any dirrems we wait for the journal write
7433 		 * to complete and then restart the buf scan as the lock
7434 		 * has been dropped.
7435 		 */
7436 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7437 			jwait(&jremref->jr_list, MNT_WAIT);
7438 			return (ERESTART);
7439 		}
7440 		LIST_REMOVE(dirrem, dm_next);
7441 		dirrem->dm_dirinum = pagedep->pd_ino;
7442 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7443 	}
7444 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7445 		jwait(&jmvref->jm_list, MNT_WAIT);
7446 		return (ERESTART);
7447 	}
7448 	/*
7449 	 * When we're partially truncating a pagedep we just want to flush
7450 	 * journal entries and return.  There can not be any adds in the
7451 	 * truncated portion of the directory and newblk must remain if
7452 	 * part of the block remains.
7453 	 */
7454 	if (blkoff != 0) {
7455 		struct diradd *dap;
7456 
7457 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7458 			if (dap->da_offset > blkoff)
7459 				panic("cancel_pagedep: diradd %p off %d > %d",
7460 				    dap, dap->da_offset, blkoff);
7461 		for (i = 0; i < DAHASHSZ; i++)
7462 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7463 				if (dap->da_offset > blkoff)
7464 					panic("cancel_pagedep: diradd %p off %d > %d",
7465 					    dap, dap->da_offset, blkoff);
7466 		return (0);
7467 	}
7468 	/*
7469 	 * There should be no directory add dependencies present
7470 	 * as the directory could not be truncated until all
7471 	 * children were removed.
7472 	 */
7473 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7474 	    ("deallocate_dependencies: pendinghd != NULL"));
7475 	for (i = 0; i < DAHASHSZ; i++)
7476 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7477 		    ("deallocate_dependencies: diraddhd != NULL"));
7478 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7479 		free_newdirblk(pagedep->pd_newdirblk);
7480 	if (free_pagedep(pagedep) == 0)
7481 		panic("Failed to free pagedep %p", pagedep);
7482 	return (0);
7483 }
7484 
7485 /*
7486  * Reclaim any dependency structures from a buffer that is about to
7487  * be reallocated to a new vnode. The buffer must be locked, thus,
7488  * no I/O completion operations can occur while we are manipulating
7489  * its associated dependencies. The mutex is held so that other I/O's
7490  * associated with related dependencies do not occur.
7491  */
7492 static int
deallocate_dependencies(struct buf * bp,struct freeblks * freeblks,int off)7493 deallocate_dependencies(
7494 	struct buf *bp,
7495 	struct freeblks *freeblks,
7496 	int off)
7497 {
7498 	struct indirdep *indirdep;
7499 	struct pagedep *pagedep;
7500 	struct worklist *wk, *wkn;
7501 	struct ufsmount *ump;
7502 
7503 	ump = softdep_bp_to_mp(bp);
7504 	if (ump == NULL)
7505 		goto done;
7506 	ACQUIRE_LOCK(ump);
7507 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7508 		switch (wk->wk_type) {
7509 		case D_INDIRDEP:
7510 			indirdep = WK_INDIRDEP(wk);
7511 			if (bp->b_lblkno >= 0 ||
7512 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7513 				panic("deallocate_dependencies: not indir");
7514 			cancel_indirdep(indirdep, bp, freeblks);
7515 			continue;
7516 
7517 		case D_PAGEDEP:
7518 			pagedep = WK_PAGEDEP(wk);
7519 			if (cancel_pagedep(pagedep, freeblks, off)) {
7520 				FREE_LOCK(ump);
7521 				return (ERESTART);
7522 			}
7523 			continue;
7524 
7525 		case D_ALLOCINDIR:
7526 			/*
7527 			 * Simply remove the allocindir, we'll find it via
7528 			 * the indirdep where we can clear pointers if
7529 			 * needed.
7530 			 */
7531 			WORKLIST_REMOVE(wk);
7532 			continue;
7533 
7534 		case D_FREEWORK:
7535 			/*
7536 			 * A truncation is waiting for the zero'd pointers
7537 			 * to be written.  It can be freed when the freeblks
7538 			 * is journaled.
7539 			 */
7540 			WORKLIST_REMOVE(wk);
7541 			wk->wk_state |= ONDEPLIST;
7542 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7543 			break;
7544 
7545 		case D_ALLOCDIRECT:
7546 			if (off != 0)
7547 				continue;
7548 			/* FALLTHROUGH */
7549 		default:
7550 			panic("deallocate_dependencies: Unexpected type %s",
7551 			    TYPENAME(wk->wk_type));
7552 			/* NOTREACHED */
7553 		}
7554 	}
7555 	FREE_LOCK(ump);
7556 done:
7557 	/*
7558 	 * Don't throw away this buf, we were partially truncating and
7559 	 * some deps may always remain.
7560 	 */
7561 	if (off) {
7562 		allocbuf(bp, off);
7563 		bp->b_vflags |= BV_SCANNED;
7564 		return (EBUSY);
7565 	}
7566 	bp->b_flags |= B_INVAL | B_NOCACHE;
7567 
7568 	return (0);
7569 }
7570 
7571 /*
7572  * An allocdirect is being canceled due to a truncate.  We must make sure
7573  * the journal entry is released in concert with the blkfree that releases
7574  * the storage.  Completed journal entries must not be released until the
7575  * space is no longer pointed to by the inode or in the bitmap.
7576  */
7577 static void
cancel_allocdirect(struct allocdirectlst * adphead,struct allocdirect * adp,struct freeblks * freeblks)7578 cancel_allocdirect(
7579 	struct allocdirectlst *adphead,
7580 	struct allocdirect *adp,
7581 	struct freeblks *freeblks)
7582 {
7583 	struct freework *freework;
7584 	struct newblk *newblk;
7585 	struct worklist *wk;
7586 
7587 	TAILQ_REMOVE(adphead, adp, ad_next);
7588 	newblk = (struct newblk *)adp;
7589 	freework = NULL;
7590 	/*
7591 	 * Find the correct freework structure.
7592 	 */
7593 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7594 		if (wk->wk_type != D_FREEWORK)
7595 			continue;
7596 		freework = WK_FREEWORK(wk);
7597 		if (freework->fw_blkno == newblk->nb_newblkno)
7598 			break;
7599 	}
7600 	if (freework == NULL)
7601 		panic("cancel_allocdirect: Freework not found");
7602 	/*
7603 	 * If a newblk exists at all we still have the journal entry that
7604 	 * initiated the allocation so we do not need to journal the free.
7605 	 */
7606 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7607 	/*
7608 	 * If the journal hasn't been written the jnewblk must be passed
7609 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7610 	 * this by linking the journal dependency into the freework to be
7611 	 * freed when freework_freeblock() is called.  If the journal has
7612 	 * been written we can simply reclaim the journal space when the
7613 	 * freeblks work is complete.
7614 	 */
7615 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7616 	    &freeblks->fb_jwork);
7617 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7618 }
7619 
7620 /*
7621  * Cancel a new block allocation.  May be an indirect or direct block.  We
7622  * remove it from various lists and return any journal record that needs to
7623  * be resolved by the caller.
7624  *
7625  * A special consideration is made for indirects which were never pointed
7626  * at on disk and will never be found once this block is released.
7627  */
7628 static struct jnewblk *
cancel_newblk(struct newblk * newblk,struct worklist * wk,struct workhead * wkhd)7629 cancel_newblk(
7630 	struct newblk *newblk,
7631 	struct worklist *wk,
7632 	struct workhead *wkhd)
7633 {
7634 	struct jnewblk *jnewblk;
7635 
7636 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7637 
7638 	newblk->nb_state |= GOINGAWAY;
7639 	/*
7640 	 * Previously we traversed the completedhd on each indirdep
7641 	 * attached to this newblk to cancel them and gather journal
7642 	 * work.  Since we need only the oldest journal segment and
7643 	 * the lowest point on the tree will always have the oldest
7644 	 * journal segment we are free to release the segments
7645 	 * of any subordinates and may leave the indirdep list to
7646 	 * indirdep_complete() when this newblk is freed.
7647 	 */
7648 	if (newblk->nb_state & ONDEPLIST) {
7649 		newblk->nb_state &= ~ONDEPLIST;
7650 		LIST_REMOVE(newblk, nb_deps);
7651 	}
7652 	if (newblk->nb_state & ONWORKLIST)
7653 		WORKLIST_REMOVE(&newblk->nb_list);
7654 	/*
7655 	 * If the journal entry hasn't been written we save a pointer to
7656 	 * the dependency that frees it until it is written or the
7657 	 * superseding operation completes.
7658 	 */
7659 	jnewblk = newblk->nb_jnewblk;
7660 	if (jnewblk != NULL && wk != NULL) {
7661 		newblk->nb_jnewblk = NULL;
7662 		jnewblk->jn_dep = wk;
7663 	}
7664 	if (!LIST_EMPTY(&newblk->nb_jwork))
7665 		jwork_move(wkhd, &newblk->nb_jwork);
7666 	/*
7667 	 * When truncating we must free the newdirblk early to remove
7668 	 * the pagedep from the hash before returning.
7669 	 */
7670 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7671 		free_newdirblk(WK_NEWDIRBLK(wk));
7672 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7673 		panic("cancel_newblk: extra newdirblk");
7674 
7675 	return (jnewblk);
7676 }
7677 
7678 /*
7679  * Schedule the freefrag associated with a newblk to be released once
7680  * the pointers are written and the previous block is no longer needed.
7681  */
7682 static void
newblk_freefrag(struct newblk * newblk)7683 newblk_freefrag(struct newblk *newblk)
7684 {
7685 	struct freefrag *freefrag;
7686 
7687 	if (newblk->nb_freefrag == NULL)
7688 		return;
7689 	freefrag = newblk->nb_freefrag;
7690 	newblk->nb_freefrag = NULL;
7691 	freefrag->ff_state |= COMPLETE;
7692 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7693 		add_to_worklist(&freefrag->ff_list, 0);
7694 }
7695 
7696 /*
7697  * Free a newblk. Generate a new freefrag work request if appropriate.
7698  * This must be called after the inode pointer and any direct block pointers
7699  * are valid or fully removed via truncate or frag extension.
7700  */
7701 static void
free_newblk(struct newblk * newblk)7702 free_newblk(struct newblk *newblk)
7703 {
7704 	struct indirdep *indirdep;
7705 	struct worklist *wk;
7706 
7707 	KASSERT(newblk->nb_jnewblk == NULL,
7708 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7709 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7710 	    ("free_newblk: unclaimed newblk"));
7711 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7712 	newblk_freefrag(newblk);
7713 	if (newblk->nb_state & ONDEPLIST)
7714 		LIST_REMOVE(newblk, nb_deps);
7715 	if (newblk->nb_state & ONWORKLIST)
7716 		WORKLIST_REMOVE(&newblk->nb_list);
7717 	LIST_REMOVE(newblk, nb_hash);
7718 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7719 		free_newdirblk(WK_NEWDIRBLK(wk));
7720 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7721 		panic("free_newblk: extra newdirblk");
7722 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7723 		indirdep_complete(indirdep);
7724 	handle_jwork(&newblk->nb_jwork);
7725 	WORKITEM_FREE(newblk, D_NEWBLK);
7726 }
7727 
7728 /*
7729  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7730  */
7731 static void
free_newdirblk(struct newdirblk * newdirblk)7732 free_newdirblk(struct newdirblk *newdirblk)
7733 {
7734 	struct pagedep *pagedep;
7735 	struct diradd *dap;
7736 	struct worklist *wk;
7737 
7738 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7739 	WORKLIST_REMOVE(&newdirblk->db_list);
7740 	/*
7741 	 * If the pagedep is still linked onto the directory buffer
7742 	 * dependency chain, then some of the entries on the
7743 	 * pd_pendinghd list may not be committed to disk yet. In
7744 	 * this case, we will simply clear the NEWBLOCK flag and
7745 	 * let the pd_pendinghd list be processed when the pagedep
7746 	 * is next written. If the pagedep is no longer on the buffer
7747 	 * dependency chain, then all the entries on the pd_pending
7748 	 * list are committed to disk and we can free them here.
7749 	 */
7750 	pagedep = newdirblk->db_pagedep;
7751 	pagedep->pd_state &= ~NEWBLOCK;
7752 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7753 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7754 			free_diradd(dap, NULL);
7755 		/*
7756 		 * If no dependencies remain, the pagedep will be freed.
7757 		 */
7758 		free_pagedep(pagedep);
7759 	}
7760 	/* Should only ever be one item in the list. */
7761 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7762 		WORKLIST_REMOVE(wk);
7763 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7764 	}
7765 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7766 }
7767 
7768 /*
7769  * Prepare an inode to be freed. The actual free operation is not
7770  * done until the zero'ed inode has been written to disk.
7771  */
7772 void
softdep_freefile(struct vnode * pvp,ino_t ino,int mode)7773 softdep_freefile(
7774 	struct vnode *pvp,
7775 	ino_t ino,
7776 	int mode)
7777 {
7778 	struct inode *ip = VTOI(pvp);
7779 	struct inodedep *inodedep;
7780 	struct freefile *freefile;
7781 	struct freeblks *freeblks;
7782 	struct ufsmount *ump;
7783 
7784 	ump = ITOUMP(ip);
7785 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7786 	    ("softdep_freefile called on non-softdep filesystem"));
7787 	/*
7788 	 * This sets up the inode de-allocation dependency.
7789 	 */
7790 	freefile = malloc(sizeof(struct freefile),
7791 		M_FREEFILE, M_SOFTDEP_FLAGS);
7792 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7793 	freefile->fx_mode = mode;
7794 	freefile->fx_oldinum = ino;
7795 	freefile->fx_devvp = ump->um_devvp;
7796 	LIST_INIT(&freefile->fx_jwork);
7797 	UFS_LOCK(ump);
7798 	ump->um_fs->fs_pendinginodes += 1;
7799 	UFS_UNLOCK(ump);
7800 
7801 	/*
7802 	 * If the inodedep does not exist, then the zero'ed inode has
7803 	 * been written to disk. If the allocated inode has never been
7804 	 * written to disk, then the on-disk inode is zero'ed. In either
7805 	 * case we can free the file immediately.  If the journal was
7806 	 * canceled before being written the inode will never make it to
7807 	 * disk and we must send the canceled journal entrys to
7808 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7809 	 * Any blocks waiting on the inode to write can be safely freed
7810 	 * here as it will never been written.
7811 	 */
7812 	ACQUIRE_LOCK(ump);
7813 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7814 	if (inodedep) {
7815 		/*
7816 		 * Clear out freeblks that no longer need to reference
7817 		 * this inode.
7818 		 */
7819 		while ((freeblks =
7820 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7821 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7822 			    fb_next);
7823 			freeblks->fb_state &= ~ONDEPLIST;
7824 		}
7825 		/*
7826 		 * Remove this inode from the unlinked list.
7827 		 */
7828 		if (inodedep->id_state & UNLINKED) {
7829 			/*
7830 			 * Save the journal work to be freed with the bitmap
7831 			 * before we clear UNLINKED.  Otherwise it can be lost
7832 			 * if the inode block is written.
7833 			 */
7834 			handle_bufwait(inodedep, &freefile->fx_jwork);
7835 			clear_unlinked_inodedep(inodedep);
7836 			/*
7837 			 * Re-acquire inodedep as we've dropped the
7838 			 * per-filesystem lock in clear_unlinked_inodedep().
7839 			 */
7840 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7841 		}
7842 	}
7843 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7844 		FREE_LOCK(ump);
7845 		handle_workitem_freefile(freefile);
7846 		return;
7847 	}
7848 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
7849 		inodedep->id_state |= GOINGAWAY;
7850 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7851 	FREE_LOCK(ump);
7852 	if (ip->i_number == ino)
7853 		UFS_INODE_SET_FLAG(ip, IN_MODIFIED);
7854 }
7855 
7856 /*
7857  * Check to see if an inode has never been written to disk. If
7858  * so free the inodedep and return success, otherwise return failure.
7859  *
7860  * If we still have a bitmap dependency, then the inode has never
7861  * been written to disk. Drop the dependency as it is no longer
7862  * necessary since the inode is being deallocated. We set the
7863  * ALLCOMPLETE flags since the bitmap now properly shows that the
7864  * inode is not allocated. Even if the inode is actively being
7865  * written, it has been rolled back to its zero'ed state, so we
7866  * are ensured that a zero inode is what is on the disk. For short
7867  * lived files, this change will usually result in removing all the
7868  * dependencies from the inode so that it can be freed immediately.
7869  */
7870 static int
check_inode_unwritten(struct inodedep * inodedep)7871 check_inode_unwritten(struct inodedep *inodedep)
7872 {
7873 
7874 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7875 
7876 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7877 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7878 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7879 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7880 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7881 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7882 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7883 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7884 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7885 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7886 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7887 	    inodedep->id_mkdiradd != NULL ||
7888 	    inodedep->id_nlinkdelta != 0)
7889 		return (0);
7890 	/*
7891 	 * Another process might be in initiate_write_inodeblock_ufs[12]
7892 	 * trying to allocate memory without holding "Softdep Lock".
7893 	 */
7894 	if ((inodedep->id_state & IOSTARTED) != 0 &&
7895 	    inodedep->id_savedino1 == NULL)
7896 		return (0);
7897 
7898 	if (inodedep->id_state & ONDEPLIST)
7899 		LIST_REMOVE(inodedep, id_deps);
7900 	inodedep->id_state &= ~ONDEPLIST;
7901 	inodedep->id_state |= ALLCOMPLETE;
7902 	inodedep->id_bmsafemap = NULL;
7903 	if (inodedep->id_state & ONWORKLIST)
7904 		WORKLIST_REMOVE(&inodedep->id_list);
7905 	if (inodedep->id_savedino1 != NULL) {
7906 		free(inodedep->id_savedino1, M_SAVEDINO);
7907 		inodedep->id_savedino1 = NULL;
7908 	}
7909 	if (free_inodedep(inodedep) == 0)
7910 		panic("check_inode_unwritten: busy inode");
7911 	return (1);
7912 }
7913 
7914 static int
check_inodedep_free(struct inodedep * inodedep)7915 check_inodedep_free(struct inodedep *inodedep)
7916 {
7917 
7918 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7919 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7920 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7921 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7922 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7923 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7924 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7925 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7926 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7927 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7928 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7929 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7930 	    inodedep->id_mkdiradd != NULL ||
7931 	    inodedep->id_nlinkdelta != 0 ||
7932 	    inodedep->id_savedino1 != NULL)
7933 		return (0);
7934 	return (1);
7935 }
7936 
7937 /*
7938  * Try to free an inodedep structure. Return 1 if it could be freed.
7939  */
7940 static int
free_inodedep(struct inodedep * inodedep)7941 free_inodedep(struct inodedep *inodedep)
7942 {
7943 
7944 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7945 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7946 	    !check_inodedep_free(inodedep))
7947 		return (0);
7948 	if (inodedep->id_state & ONDEPLIST)
7949 		LIST_REMOVE(inodedep, id_deps);
7950 	LIST_REMOVE(inodedep, id_hash);
7951 	WORKITEM_FREE(inodedep, D_INODEDEP);
7952 	return (1);
7953 }
7954 
7955 /*
7956  * Free the block referenced by a freework structure.  The parent freeblks
7957  * structure is released and completed when the final cg bitmap reaches
7958  * the disk.  This routine may be freeing a jnewblk which never made it to
7959  * disk in which case we do not have to wait as the operation is undone
7960  * in memory immediately.
7961  */
7962 static void
freework_freeblock(struct freework * freework,uint64_t key)7963 freework_freeblock(struct freework *freework, uint64_t key)
7964 {
7965 	struct freeblks *freeblks;
7966 	struct jnewblk *jnewblk;
7967 	struct ufsmount *ump;
7968 	struct workhead wkhd;
7969 	struct fs *fs;
7970 	int bsize;
7971 	int needj;
7972 
7973 	ump = VFSTOUFS(freework->fw_list.wk_mp);
7974 	LOCK_OWNED(ump);
7975 	/*
7976 	 * Handle partial truncate separately.
7977 	 */
7978 	if (freework->fw_indir) {
7979 		complete_trunc_indir(freework);
7980 		return;
7981 	}
7982 	freeblks = freework->fw_freeblks;
7983 	fs = ump->um_fs;
7984 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7985 	bsize = lfragtosize(fs, freework->fw_frags);
7986 	LIST_INIT(&wkhd);
7987 	/*
7988 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7989 	 * on the indirblk hashtable and prevents premature freeing.
7990 	 */
7991 	freework->fw_state |= DEPCOMPLETE;
7992 	/*
7993 	 * SUJ needs to wait for the segment referencing freed indirect
7994 	 * blocks to expire so that we know the checker will not confuse
7995 	 * a re-allocated indirect block with its old contents.
7996 	 */
7997 	if (needj && freework->fw_lbn <= -UFS_NDADDR)
7998 		indirblk_insert(freework);
7999 	/*
8000 	 * If we are canceling an existing jnewblk pass it to the free
8001 	 * routine, otherwise pass the freeblk which will ultimately
8002 	 * release the freeblks.  If we're not journaling, we can just
8003 	 * free the freeblks immediately.
8004 	 */
8005 	jnewblk = freework->fw_jnewblk;
8006 	if (jnewblk != NULL) {
8007 		cancel_jnewblk(jnewblk, &wkhd);
8008 		needj = 0;
8009 	} else if (needj) {
8010 		freework->fw_state |= DELAYEDFREE;
8011 		freeblks->fb_cgwait++;
8012 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
8013 	}
8014 	FREE_LOCK(ump);
8015 	freeblks_free(ump, freeblks, btodb(bsize));
8016 	CTR4(KTR_SUJ,
8017 	    "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
8018 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
8019 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
8020 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
8021 	ACQUIRE_LOCK(ump);
8022 	/*
8023 	 * The jnewblk will be discarded and the bits in the map never
8024 	 * made it to disk.  We can immediately free the freeblk.
8025 	 */
8026 	if (needj == 0)
8027 		handle_written_freework(freework);
8028 }
8029 
8030 /*
8031  * We enqueue freework items that need processing back on the freeblks and
8032  * add the freeblks to the worklist.  This makes it easier to find all work
8033  * required to flush a truncation in process_truncates().
8034  */
8035 static void
freework_enqueue(struct freework * freework)8036 freework_enqueue(struct freework *freework)
8037 {
8038 	struct freeblks *freeblks;
8039 
8040 	freeblks = freework->fw_freeblks;
8041 	if ((freework->fw_state & INPROGRESS) == 0)
8042 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
8043 	if ((freeblks->fb_state &
8044 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
8045 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
8046 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
8047 }
8048 
8049 /*
8050  * Start, continue, or finish the process of freeing an indirect block tree.
8051  * The free operation may be paused at any point with fw_off containing the
8052  * offset to restart from.  This enables us to implement some flow control
8053  * for large truncates which may fan out and generate a huge number of
8054  * dependencies.
8055  */
8056 static void
handle_workitem_indirblk(struct freework * freework)8057 handle_workitem_indirblk(struct freework *freework)
8058 {
8059 	struct freeblks *freeblks;
8060 	struct ufsmount *ump;
8061 	struct fs *fs;
8062 
8063 	freeblks = freework->fw_freeblks;
8064 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8065 	fs = ump->um_fs;
8066 	if (freework->fw_state & DEPCOMPLETE) {
8067 		handle_written_freework(freework);
8068 		return;
8069 	}
8070 	if (freework->fw_off == NINDIR(fs)) {
8071 		freework_freeblock(freework, SINGLETON_KEY);
8072 		return;
8073 	}
8074 	freework->fw_state |= INPROGRESS;
8075 	FREE_LOCK(ump);
8076 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
8077 	    freework->fw_lbn);
8078 	ACQUIRE_LOCK(ump);
8079 }
8080 
8081 /*
8082  * Called when a freework structure attached to a cg buf is written.  The
8083  * ref on either the parent or the freeblks structure is released and
8084  * the freeblks is added back to the worklist if there is more work to do.
8085  */
8086 static void
handle_written_freework(struct freework * freework)8087 handle_written_freework(struct freework *freework)
8088 {
8089 	struct freeblks *freeblks;
8090 	struct freework *parent;
8091 
8092 	freeblks = freework->fw_freeblks;
8093 	parent = freework->fw_parent;
8094 	if (freework->fw_state & DELAYEDFREE)
8095 		freeblks->fb_cgwait--;
8096 	freework->fw_state |= COMPLETE;
8097 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
8098 		WORKITEM_FREE(freework, D_FREEWORK);
8099 	if (parent) {
8100 		if (--parent->fw_ref == 0)
8101 			freework_enqueue(parent);
8102 		return;
8103 	}
8104 	if (--freeblks->fb_ref != 0)
8105 		return;
8106 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
8107 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
8108 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
8109 }
8110 
8111 /*
8112  * This workitem routine performs the block de-allocation.
8113  * The workitem is added to the pending list after the updated
8114  * inode block has been written to disk.  As mentioned above,
8115  * checks regarding the number of blocks de-allocated (compared
8116  * to the number of blocks allocated for the file) are also
8117  * performed in this function.
8118  */
8119 static int
handle_workitem_freeblocks(struct freeblks * freeblks,int flags)8120 handle_workitem_freeblocks(struct freeblks *freeblks, int flags)
8121 {
8122 	struct freework *freework;
8123 	struct newblk *newblk;
8124 	struct allocindir *aip;
8125 	struct ufsmount *ump;
8126 	struct worklist *wk;
8127 	uint64_t key;
8128 
8129 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
8130 	    ("handle_workitem_freeblocks: Journal entries not written."));
8131 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8132 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8133 	ACQUIRE_LOCK(ump);
8134 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
8135 		WORKLIST_REMOVE(wk);
8136 		switch (wk->wk_type) {
8137 		case D_DIRREM:
8138 			wk->wk_state |= COMPLETE;
8139 			add_to_worklist(wk, 0);
8140 			continue;
8141 
8142 		case D_ALLOCDIRECT:
8143 			free_newblk(WK_NEWBLK(wk));
8144 			continue;
8145 
8146 		case D_ALLOCINDIR:
8147 			aip = WK_ALLOCINDIR(wk);
8148 			freework = NULL;
8149 			if (aip->ai_state & DELAYEDFREE) {
8150 				FREE_LOCK(ump);
8151 				freework = newfreework(ump, freeblks, NULL,
8152 				    aip->ai_lbn, aip->ai_newblkno,
8153 				    ump->um_fs->fs_frag, 0, 0);
8154 				ACQUIRE_LOCK(ump);
8155 			}
8156 			newblk = WK_NEWBLK(wk);
8157 			if (newblk->nb_jnewblk) {
8158 				freework->fw_jnewblk = newblk->nb_jnewblk;
8159 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
8160 				newblk->nb_jnewblk = NULL;
8161 			}
8162 			free_newblk(newblk);
8163 			continue;
8164 
8165 		case D_FREEWORK:
8166 			freework = WK_FREEWORK(wk);
8167 			if (freework->fw_lbn <= -UFS_NDADDR)
8168 				handle_workitem_indirblk(freework);
8169 			else
8170 				freework_freeblock(freework, key);
8171 			continue;
8172 		default:
8173 			panic("handle_workitem_freeblocks: Unknown type %s",
8174 			    TYPENAME(wk->wk_type));
8175 		}
8176 	}
8177 	if (freeblks->fb_ref != 0) {
8178 		freeblks->fb_state &= ~INPROGRESS;
8179 		wake_worklist(&freeblks->fb_list);
8180 		freeblks = NULL;
8181 	}
8182 	FREE_LOCK(ump);
8183 	ffs_blkrelease_finish(ump, key);
8184 	if (freeblks)
8185 		return handle_complete_freeblocks(freeblks, flags);
8186 	return (0);
8187 }
8188 
8189 /*
8190  * Handle completion of block free via truncate.  This allows fs_pending
8191  * to track the actual free block count more closely than if we only updated
8192  * it at the end.  We must be careful to handle cases where the block count
8193  * on free was incorrect.
8194  */
8195 static void
freeblks_free(struct ufsmount * ump,struct freeblks * freeblks,int blocks)8196 freeblks_free(struct ufsmount *ump,
8197 	struct freeblks *freeblks,
8198 	int blocks)
8199 {
8200 	struct fs *fs;
8201 	ufs2_daddr_t remain;
8202 
8203 	UFS_LOCK(ump);
8204 	remain = -freeblks->fb_chkcnt;
8205 	freeblks->fb_chkcnt += blocks;
8206 	if (remain > 0) {
8207 		if (remain < blocks)
8208 			blocks = remain;
8209 		fs = ump->um_fs;
8210 		fs->fs_pendingblocks -= blocks;
8211 	}
8212 	UFS_UNLOCK(ump);
8213 }
8214 
8215 /*
8216  * Once all of the freework workitems are complete we can retire the
8217  * freeblocks dependency and any journal work awaiting completion.  This
8218  * can not be called until all other dependencies are stable on disk.
8219  */
8220 static int
handle_complete_freeblocks(struct freeblks * freeblks,int flags)8221 handle_complete_freeblocks(struct freeblks *freeblks, int flags)
8222 {
8223 	struct inodedep *inodedep;
8224 	struct inode *ip;
8225 	struct vnode *vp;
8226 	struct fs *fs;
8227 	struct ufsmount *ump;
8228 	ufs2_daddr_t spare;
8229 
8230 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8231 	fs = ump->um_fs;
8232 	flags = LK_EXCLUSIVE | flags;
8233 	spare = freeblks->fb_chkcnt;
8234 
8235 	/*
8236 	 * If we did not release the expected number of blocks we may have
8237 	 * to adjust the inode block count here.  Only do so if it wasn't
8238 	 * a truncation to zero and the modrev still matches.
8239 	 */
8240 	if (spare && freeblks->fb_len != 0) {
8241 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8242 		    flags, &vp, FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP) != 0)
8243 			return (EBUSY);
8244 		ip = VTOI(vp);
8245 		if (ip->i_mode == 0) {
8246 			vgone(vp);
8247 		} else if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8248 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8249 			UFS_INODE_SET_FLAG(ip, IN_CHANGE);
8250 			/*
8251 			 * We must wait so this happens before the
8252 			 * journal is reclaimed.
8253 			 */
8254 			ffs_update(vp, 1);
8255 		}
8256 		vput(vp);
8257 	}
8258 	if (spare < 0) {
8259 		UFS_LOCK(ump);
8260 		fs->fs_pendingblocks += spare;
8261 		UFS_UNLOCK(ump);
8262 	}
8263 #ifdef QUOTA
8264 	/* Handle spare. */
8265 	if (spare)
8266 		quotaadj(freeblks->fb_quota, ump, -spare);
8267 	quotarele(freeblks->fb_quota);
8268 #endif
8269 	ACQUIRE_LOCK(ump);
8270 	if (freeblks->fb_state & ONDEPLIST) {
8271 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8272 		    0, &inodedep);
8273 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8274 		freeblks->fb_state &= ~ONDEPLIST;
8275 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8276 			free_inodedep(inodedep);
8277 	}
8278 	/*
8279 	 * All of the freeblock deps must be complete prior to this call
8280 	 * so it's now safe to complete earlier outstanding journal entries.
8281 	 */
8282 	handle_jwork(&freeblks->fb_jwork);
8283 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8284 	FREE_LOCK(ump);
8285 	return (0);
8286 }
8287 
8288 /*
8289  * Release blocks associated with the freeblks and stored in the indirect
8290  * block dbn. If level is greater than SINGLE, the block is an indirect block
8291  * and recursive calls to indirtrunc must be used to cleanse other indirect
8292  * blocks.
8293  *
8294  * This handles partial and complete truncation of blocks.  Partial is noted
8295  * with goingaway == 0.  In this case the freework is completed after the
8296  * zero'd indirects are written to disk.  For full truncation the freework
8297  * is completed after the block is freed.
8298  */
8299 static void
indir_trunc(struct freework * freework,ufs2_daddr_t dbn,ufs_lbn_t lbn)8300 indir_trunc(struct freework *freework,
8301 	ufs2_daddr_t dbn,
8302 	ufs_lbn_t lbn)
8303 {
8304 	struct freework *nfreework;
8305 	struct workhead wkhd;
8306 	struct freeblks *freeblks;
8307 	struct buf *bp;
8308 	struct fs *fs;
8309 	struct indirdep *indirdep;
8310 	struct mount *mp;
8311 	struct ufsmount *ump;
8312 	ufs1_daddr_t *bap1;
8313 	ufs2_daddr_t nb, nnb, *bap2;
8314 	ufs_lbn_t lbnadd, nlbn;
8315 	uint64_t key;
8316 	int nblocks, ufs1fmt, freedblocks;
8317 	int goingaway, freedeps, needj, level, cnt, i, error;
8318 
8319 	freeblks = freework->fw_freeblks;
8320 	mp = freeblks->fb_list.wk_mp;
8321 	ump = VFSTOUFS(mp);
8322 	fs = ump->um_fs;
8323 	/*
8324 	 * Get buffer of block pointers to be freed.  There are three cases:
8325 	 *
8326 	 * 1) Partial truncate caches the indirdep pointer in the freework
8327 	 *    which provides us a back copy to the save bp which holds the
8328 	 *    pointers we want to clear.  When this completes the zero
8329 	 *    pointers are written to the real copy.
8330 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8331 	 *    eliminated the real copy and placed the indirdep on the saved
8332 	 *    copy.  The indirdep and buf are discarded when this completes.
8333 	 * 3) The indirect was not in memory, we read a copy off of the disk
8334 	 *    using the devvp and drop and invalidate the buffer when we're
8335 	 *    done.
8336 	 */
8337 	goingaway = 1;
8338 	indirdep = NULL;
8339 	if (freework->fw_indir != NULL) {
8340 		goingaway = 0;
8341 		indirdep = freework->fw_indir;
8342 		bp = indirdep->ir_savebp;
8343 		if (bp == NULL || bp->b_blkno != dbn)
8344 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8345 			    bp, (intmax_t)dbn);
8346 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8347 		/*
8348 		 * The lock prevents the buf dep list from changing and
8349 	 	 * indirects on devvp should only ever have one dependency.
8350 		 */
8351 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8352 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8353 			panic("indir_trunc: Bad indirdep %p from buf %p",
8354 			    indirdep, bp);
8355 	} else {
8356 		error = ffs_breadz(ump, freeblks->fb_devvp, dbn, dbn,
8357 		    (int)fs->fs_bsize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
8358 		if (error)
8359 			return;
8360 	}
8361 	ACQUIRE_LOCK(ump);
8362 	/* Protects against a race with complete_trunc_indir(). */
8363 	freework->fw_state &= ~INPROGRESS;
8364 	/*
8365 	 * If we have an indirdep we need to enforce the truncation order
8366 	 * and discard it when it is complete.
8367 	 */
8368 	if (indirdep) {
8369 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8370 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8371 			/*
8372 			 * Add the complete truncate to the list on the
8373 			 * indirdep to enforce in-order processing.
8374 			 */
8375 			if (freework->fw_indir == NULL)
8376 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8377 				    freework, fw_next);
8378 			FREE_LOCK(ump);
8379 			return;
8380 		}
8381 		/*
8382 		 * If we're goingaway, free the indirdep.  Otherwise it will
8383 		 * linger until the write completes.
8384 		 */
8385 		if (goingaway) {
8386 			KASSERT(indirdep->ir_savebp == bp,
8387 			    ("indir_trunc: losing ir_savebp %p",
8388 			    indirdep->ir_savebp));
8389 			indirdep->ir_savebp = NULL;
8390 			free_indirdep(indirdep);
8391 		}
8392 	}
8393 	FREE_LOCK(ump);
8394 	/* Initialize pointers depending on block size. */
8395 	if (ump->um_fstype == UFS1) {
8396 		bap1 = (ufs1_daddr_t *)bp->b_data;
8397 		nb = bap1[freework->fw_off];
8398 		ufs1fmt = 1;
8399 		bap2 = NULL;
8400 	} else {
8401 		bap2 = (ufs2_daddr_t *)bp->b_data;
8402 		nb = bap2[freework->fw_off];
8403 		ufs1fmt = 0;
8404 		bap1 = NULL;
8405 	}
8406 	level = lbn_level(lbn);
8407 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8408 	lbnadd = lbn_offset(fs, level);
8409 	nblocks = btodb(fs->fs_bsize);
8410 	nfreework = freework;
8411 	freedeps = 0;
8412 	cnt = 0;
8413 	/*
8414 	 * Reclaim blocks.  Traverses into nested indirect levels and
8415 	 * arranges for the current level to be freed when subordinates
8416 	 * are free when journaling.
8417 	 */
8418 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8419 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8420 		if (UFS_CHECK_BLKNO(mp, freeblks->fb_inum, nb,
8421 		    fs->fs_bsize) != 0)
8422 			nb = 0;
8423 		if (i != NINDIR(fs) - 1) {
8424 			if (ufs1fmt)
8425 				nnb = bap1[i+1];
8426 			else
8427 				nnb = bap2[i+1];
8428 		} else
8429 			nnb = 0;
8430 		if (nb == 0)
8431 			continue;
8432 		cnt++;
8433 		if (level != 0) {
8434 			nlbn = (lbn + 1) - (i * lbnadd);
8435 			if (needj != 0) {
8436 				nfreework = newfreework(ump, freeblks, freework,
8437 				    nlbn, nb, fs->fs_frag, 0, 0);
8438 				freedeps++;
8439 			}
8440 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8441 		} else {
8442 			struct freedep *freedep;
8443 
8444 			/*
8445 			 * Attempt to aggregate freedep dependencies for
8446 			 * all blocks being released to the same CG.
8447 			 */
8448 			LIST_INIT(&wkhd);
8449 			if (needj != 0 &&
8450 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8451 				freedep = newfreedep(freework);
8452 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8453 				    &freedep->fd_list);
8454 				freedeps++;
8455 			}
8456 			CTR3(KTR_SUJ,
8457 			    "indir_trunc: ino %jd blkno %jd size %d",
8458 			    freeblks->fb_inum, nb, fs->fs_bsize);
8459 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8460 			    fs->fs_bsize, freeblks->fb_inum,
8461 			    freeblks->fb_vtype, &wkhd, key);
8462 		}
8463 	}
8464 	ffs_blkrelease_finish(ump, key);
8465 	if (goingaway) {
8466 		bp->b_flags |= B_INVAL | B_NOCACHE;
8467 		brelse(bp);
8468 	}
8469 	freedblocks = 0;
8470 	if (level == 0)
8471 		freedblocks = (nblocks * cnt);
8472 	if (needj == 0)
8473 		freedblocks += nblocks;
8474 	freeblks_free(ump, freeblks, freedblocks);
8475 	/*
8476 	 * If we are journaling set up the ref counts and offset so this
8477 	 * indirect can be completed when its children are free.
8478 	 */
8479 	if (needj) {
8480 		ACQUIRE_LOCK(ump);
8481 		freework->fw_off = i;
8482 		freework->fw_ref += freedeps;
8483 		freework->fw_ref -= NINDIR(fs) + 1;
8484 		if (level == 0)
8485 			freeblks->fb_cgwait += freedeps;
8486 		if (freework->fw_ref == 0)
8487 			freework_freeblock(freework, SINGLETON_KEY);
8488 		FREE_LOCK(ump);
8489 		return;
8490 	}
8491 	/*
8492 	 * If we're not journaling we can free the indirect now.
8493 	 */
8494 	dbn = dbtofsb(fs, dbn);
8495 	CTR3(KTR_SUJ,
8496 	    "indir_trunc 2: ino %jd blkno %jd size %d",
8497 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8498 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8499 	    freeblks->fb_inum, freeblks->fb_vtype, NULL, SINGLETON_KEY);
8500 	/* Non SUJ softdep does single-threaded truncations. */
8501 	if (freework->fw_blkno == dbn) {
8502 		freework->fw_state |= ALLCOMPLETE;
8503 		ACQUIRE_LOCK(ump);
8504 		handle_written_freework(freework);
8505 		FREE_LOCK(ump);
8506 	}
8507 	return;
8508 }
8509 
8510 /*
8511  * Cancel an allocindir when it is removed via truncation.  When bp is not
8512  * NULL the indirect never appeared on disk and is scheduled to be freed
8513  * independently of the indir so we can more easily track journal work.
8514  */
8515 static void
cancel_allocindir(struct allocindir * aip,struct buf * bp,struct freeblks * freeblks,int trunc)8516 cancel_allocindir(
8517 	struct allocindir *aip,
8518 	struct buf *bp,
8519 	struct freeblks *freeblks,
8520 	int trunc)
8521 {
8522 	struct indirdep *indirdep;
8523 	struct freefrag *freefrag;
8524 	struct newblk *newblk;
8525 
8526 	newblk = (struct newblk *)aip;
8527 	LIST_REMOVE(aip, ai_next);
8528 	/*
8529 	 * We must eliminate the pointer in bp if it must be freed on its
8530 	 * own due to partial truncate or pending journal work.
8531 	 */
8532 	if (bp && (trunc || newblk->nb_jnewblk)) {
8533 		/*
8534 		 * Clear the pointer and mark the aip to be freed
8535 		 * directly if it never existed on disk.
8536 		 */
8537 		aip->ai_state |= DELAYEDFREE;
8538 		indirdep = aip->ai_indirdep;
8539 		if (indirdep->ir_state & UFS1FMT)
8540 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8541 		else
8542 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8543 	}
8544 	/*
8545 	 * When truncating the previous pointer will be freed via
8546 	 * savedbp.  Eliminate the freefrag which would dup free.
8547 	 */
8548 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8549 		newblk->nb_freefrag = NULL;
8550 		if (freefrag->ff_jdep)
8551 			cancel_jfreefrag(
8552 			    WK_JFREEFRAG(freefrag->ff_jdep));
8553 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8554 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8555 	}
8556 	/*
8557 	 * If the journal hasn't been written the jnewblk must be passed
8558 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8559 	 * this by leaving the journal dependency on the newblk to be freed
8560 	 * when a freework is created in handle_workitem_freeblocks().
8561 	 */
8562 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8563 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8564 }
8565 
8566 /*
8567  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8568  * in to a newdirblk so any subsequent additions are tracked properly.  The
8569  * caller is responsible for adding the mkdir1 dependency to the journal
8570  * and updating id_mkdiradd.  This function returns with the per-filesystem
8571  * lock held.
8572  */
8573 static struct mkdir *
setup_newdir(struct diradd * dap,ino_t newinum,ino_t dinum,struct buf * newdirbp,struct mkdir ** mkdirp)8574 setup_newdir(
8575 	struct diradd *dap,
8576 	ino_t newinum,
8577 	ino_t dinum,
8578 	struct buf *newdirbp,
8579 	struct mkdir **mkdirp)
8580 {
8581 	struct newblk *newblk;
8582 	struct pagedep *pagedep;
8583 	struct inodedep *inodedep;
8584 	struct newdirblk *newdirblk;
8585 	struct mkdir *mkdir1, *mkdir2;
8586 	struct worklist *wk;
8587 	struct jaddref *jaddref;
8588 	struct ufsmount *ump;
8589 	struct mount *mp;
8590 
8591 	mp = dap->da_list.wk_mp;
8592 	ump = VFSTOUFS(mp);
8593 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8594 	    M_SOFTDEP_FLAGS);
8595 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8596 	LIST_INIT(&newdirblk->db_mkdir);
8597 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8598 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8599 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8600 	mkdir1->md_diradd = dap;
8601 	mkdir1->md_jaddref = NULL;
8602 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8603 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8604 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8605 	mkdir2->md_diradd = dap;
8606 	mkdir2->md_jaddref = NULL;
8607 	if (MOUNTEDSUJ(mp) == 0) {
8608 		mkdir1->md_state |= DEPCOMPLETE;
8609 		mkdir2->md_state |= DEPCOMPLETE;
8610 	}
8611 	/*
8612 	 * Dependency on "." and ".." being written to disk.
8613 	 */
8614 	mkdir1->md_buf = newdirbp;
8615 	ACQUIRE_LOCK(VFSTOUFS(mp));
8616 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8617 	/*
8618 	 * We must link the pagedep, allocdirect, and newdirblk for
8619 	 * the initial file page so the pointer to the new directory
8620 	 * is not written until the directory contents are live and
8621 	 * any subsequent additions are not marked live until the
8622 	 * block is reachable via the inode.
8623 	 */
8624 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8625 		panic("setup_newdir: lost pagedep");
8626 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8627 		if (wk->wk_type == D_ALLOCDIRECT)
8628 			break;
8629 	if (wk == NULL)
8630 		panic("setup_newdir: lost allocdirect");
8631 	if (pagedep->pd_state & NEWBLOCK)
8632 		panic("setup_newdir: NEWBLOCK already set");
8633 	newblk = WK_NEWBLK(wk);
8634 	pagedep->pd_state |= NEWBLOCK;
8635 	pagedep->pd_newdirblk = newdirblk;
8636 	newdirblk->db_pagedep = pagedep;
8637 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8638 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8639 	/*
8640 	 * Look up the inodedep for the parent directory so that we
8641 	 * can link mkdir2 into the pending dotdot jaddref or
8642 	 * the inode write if there is none.  If the inode is
8643 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8644 	 * been satisfied and mkdir2 can be freed.
8645 	 */
8646 	inodedep_lookup(mp, dinum, 0, &inodedep);
8647 	if (MOUNTEDSUJ(mp)) {
8648 		if (inodedep == NULL)
8649 			panic("setup_newdir: Lost parent.");
8650 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8651 		    inoreflst);
8652 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8653 		    (jaddref->ja_state & MKDIR_PARENT),
8654 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8655 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8656 		mkdir2->md_jaddref = jaddref;
8657 		jaddref->ja_mkdir = mkdir2;
8658 	} else if (inodedep == NULL ||
8659 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8660 		dap->da_state &= ~MKDIR_PARENT;
8661 		WORKITEM_FREE(mkdir2, D_MKDIR);
8662 		mkdir2 = NULL;
8663 	} else {
8664 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8665 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8666 	}
8667 	*mkdirp = mkdir2;
8668 
8669 	return (mkdir1);
8670 }
8671 
8672 /*
8673  * Directory entry addition dependencies.
8674  *
8675  * When adding a new directory entry, the inode (with its incremented link
8676  * count) must be written to disk before the directory entry's pointer to it.
8677  * Also, if the inode is newly allocated, the corresponding freemap must be
8678  * updated (on disk) before the directory entry's pointer. These requirements
8679  * are met via undo/redo on the directory entry's pointer, which consists
8680  * simply of the inode number.
8681  *
8682  * As directory entries are added and deleted, the free space within a
8683  * directory block can become fragmented.  The ufs filesystem will compact
8684  * a fragmented directory block to make space for a new entry. When this
8685  * occurs, the offsets of previously added entries change. Any "diradd"
8686  * dependency structures corresponding to these entries must be updated with
8687  * the new offsets.
8688  */
8689 
8690 /*
8691  * This routine is called after the in-memory inode's link
8692  * count has been incremented, but before the directory entry's
8693  * pointer to the inode has been set.
8694  */
8695 int
softdep_setup_directory_add(struct buf * bp,struct inode * dp,off_t diroffset,ino_t newinum,struct buf * newdirbp,int isnewblk)8696 softdep_setup_directory_add(
8697 	struct buf *bp,		/* buffer containing directory block */
8698 	struct inode *dp,	/* inode for directory */
8699 	off_t diroffset,	/* offset of new entry in directory */
8700 	ino_t newinum,		/* inode referenced by new directory entry */
8701 	struct buf *newdirbp,	/* non-NULL => contents of new mkdir */
8702 	int isnewblk)		/* entry is in a newly allocated block */
8703 {
8704 	int offset;		/* offset of new entry within directory block */
8705 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8706 	struct fs *fs;
8707 	struct diradd *dap;
8708 	struct newblk *newblk;
8709 	struct pagedep *pagedep;
8710 	struct inodedep *inodedep;
8711 	struct newdirblk *newdirblk;
8712 	struct mkdir *mkdir1, *mkdir2;
8713 	struct jaddref *jaddref;
8714 	struct ufsmount *ump;
8715 	struct mount *mp;
8716 	int isindir;
8717 
8718 	mp = ITOVFS(dp);
8719 	ump = VFSTOUFS(mp);
8720 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8721 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8722 	/*
8723 	 * Whiteouts have no dependencies.
8724 	 */
8725 	if (newinum == UFS_WINO) {
8726 		if (newdirbp != NULL)
8727 			bdwrite(newdirbp);
8728 		return (0);
8729 	}
8730 	jaddref = NULL;
8731 	mkdir1 = mkdir2 = NULL;
8732 	fs = ump->um_fs;
8733 	lbn = lblkno(fs, diroffset);
8734 	offset = blkoff(fs, diroffset);
8735 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8736 		M_SOFTDEP_FLAGS|M_ZERO);
8737 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8738 	dap->da_offset = offset;
8739 	dap->da_newinum = newinum;
8740 	dap->da_state = ATTACHED;
8741 	LIST_INIT(&dap->da_jwork);
8742 	isindir = bp->b_lblkno >= UFS_NDADDR;
8743 	newdirblk = NULL;
8744 	if (isnewblk &&
8745 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8746 		newdirblk = malloc(sizeof(struct newdirblk),
8747 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8748 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8749 		LIST_INIT(&newdirblk->db_mkdir);
8750 	}
8751 	/*
8752 	 * If we're creating a new directory setup the dependencies and set
8753 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8754 	 * we can move on.
8755 	 */
8756 	if (newdirbp == NULL) {
8757 		dap->da_state |= DEPCOMPLETE;
8758 		ACQUIRE_LOCK(ump);
8759 	} else {
8760 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8761 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8762 		    &mkdir2);
8763 	}
8764 	/*
8765 	 * Link into parent directory pagedep to await its being written.
8766 	 */
8767 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8768 #ifdef INVARIANTS
8769 	if (diradd_lookup(pagedep, offset) != NULL)
8770 		panic("softdep_setup_directory_add: %p already at off %d\n",
8771 		    diradd_lookup(pagedep, offset), offset);
8772 #endif
8773 	dap->da_pagedep = pagedep;
8774 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8775 	    da_pdlist);
8776 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8777 	/*
8778 	 * If we're journaling, link the diradd into the jaddref so it
8779 	 * may be completed after the journal entry is written.  Otherwise,
8780 	 * link the diradd into its inodedep.  If the inode is not yet
8781 	 * written place it on the bufwait list, otherwise do the post-inode
8782 	 * write processing to put it on the id_pendinghd list.
8783 	 */
8784 	if (MOUNTEDSUJ(mp)) {
8785 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8786 		    inoreflst);
8787 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8788 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8789 		jaddref->ja_diroff = diroffset;
8790 		jaddref->ja_diradd = dap;
8791 		add_to_journal(&jaddref->ja_list);
8792 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8793 		diradd_inode_written(dap, inodedep);
8794 	else
8795 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8796 	/*
8797 	 * Add the journal entries for . and .. links now that the primary
8798 	 * link is written.
8799 	 */
8800 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8801 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8802 		    inoreflst, if_deps);
8803 		KASSERT(jaddref != NULL &&
8804 		    jaddref->ja_ino == jaddref->ja_parent &&
8805 		    (jaddref->ja_state & MKDIR_BODY),
8806 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8807 		    jaddref));
8808 		mkdir1->md_jaddref = jaddref;
8809 		jaddref->ja_mkdir = mkdir1;
8810 		/*
8811 		 * It is important that the dotdot journal entry
8812 		 * is added prior to the dot entry since dot writes
8813 		 * both the dot and dotdot links.  These both must
8814 		 * be added after the primary link for the journal
8815 		 * to remain consistent.
8816 		 */
8817 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8818 		add_to_journal(&jaddref->ja_list);
8819 	}
8820 	/*
8821 	 * If we are adding a new directory remember this diradd so that if
8822 	 * we rename it we can keep the dot and dotdot dependencies.  If
8823 	 * we are adding a new name for an inode that has a mkdiradd we
8824 	 * must be in rename and we have to move the dot and dotdot
8825 	 * dependencies to this new name.  The old name is being orphaned
8826 	 * soon.
8827 	 */
8828 	if (mkdir1 != NULL) {
8829 		if (inodedep->id_mkdiradd != NULL)
8830 			panic("softdep_setup_directory_add: Existing mkdir");
8831 		inodedep->id_mkdiradd = dap;
8832 	} else if (inodedep->id_mkdiradd)
8833 		merge_diradd(inodedep, dap);
8834 	if (newdirblk != NULL) {
8835 		/*
8836 		 * There is nothing to do if we are already tracking
8837 		 * this block.
8838 		 */
8839 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
8840 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8841 			FREE_LOCK(ump);
8842 			return (0);
8843 		}
8844 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8845 		    == 0)
8846 			panic("softdep_setup_directory_add: lost entry");
8847 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8848 		pagedep->pd_state |= NEWBLOCK;
8849 		pagedep->pd_newdirblk = newdirblk;
8850 		newdirblk->db_pagedep = pagedep;
8851 		FREE_LOCK(ump);
8852 		/*
8853 		 * If we extended into an indirect signal direnter to sync.
8854 		 */
8855 		if (isindir)
8856 			return (1);
8857 		return (0);
8858 	}
8859 	FREE_LOCK(ump);
8860 	return (0);
8861 }
8862 
8863 /*
8864  * This procedure is called to change the offset of a directory
8865  * entry when compacting a directory block which must be owned
8866  * exclusively by the caller. Note that the actual entry movement
8867  * must be done in this procedure to ensure that no I/O completions
8868  * occur while the move is in progress.
8869  */
8870 void
softdep_change_directoryentry_offset(struct buf * bp,struct inode * dp,caddr_t base,caddr_t oldloc,caddr_t newloc,int entrysize)8871 softdep_change_directoryentry_offset(
8872 	struct buf *bp,		/* Buffer holding directory block. */
8873 	struct inode *dp,	/* inode for directory */
8874 	caddr_t base,		/* address of dp->i_offset */
8875 	caddr_t oldloc,		/* address of old directory location */
8876 	caddr_t newloc,		/* address of new directory location */
8877 	int entrysize)		/* size of directory entry */
8878 {
8879 	int offset, oldoffset, newoffset;
8880 	struct pagedep *pagedep;
8881 	struct jmvref *jmvref;
8882 	struct diradd *dap;
8883 	struct direct *de;
8884 	struct mount *mp;
8885 	struct ufsmount *ump;
8886 	ufs_lbn_t lbn;
8887 	int flags;
8888 
8889 	mp = ITOVFS(dp);
8890 	ump = VFSTOUFS(mp);
8891 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8892 	    ("softdep_change_directoryentry_offset called on "
8893 	     "non-softdep filesystem"));
8894 	de = (struct direct *)oldloc;
8895 	jmvref = NULL;
8896 	flags = 0;
8897 	/*
8898 	 * Moves are always journaled as it would be too complex to
8899 	 * determine if any affected adds or removes are present in the
8900 	 * journal.
8901 	 */
8902 	if (MOUNTEDSUJ(mp)) {
8903 		flags = DEPALLOC;
8904 		jmvref = newjmvref(dp, de->d_ino,
8905 		    I_OFFSET(dp) + (oldloc - base),
8906 		    I_OFFSET(dp) + (newloc - base));
8907 	}
8908 	lbn = lblkno(ump->um_fs, I_OFFSET(dp));
8909 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
8910 	oldoffset = offset + (oldloc - base);
8911 	newoffset = offset + (newloc - base);
8912 	ACQUIRE_LOCK(ump);
8913 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8914 		goto done;
8915 	dap = diradd_lookup(pagedep, oldoffset);
8916 	if (dap) {
8917 		dap->da_offset = newoffset;
8918 		newoffset = DIRADDHASH(newoffset);
8919 		oldoffset = DIRADDHASH(oldoffset);
8920 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8921 		    newoffset != oldoffset) {
8922 			LIST_REMOVE(dap, da_pdlist);
8923 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8924 			    dap, da_pdlist);
8925 		}
8926 	}
8927 done:
8928 	if (jmvref) {
8929 		jmvref->jm_pagedep = pagedep;
8930 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8931 		add_to_journal(&jmvref->jm_list);
8932 	}
8933 	bcopy(oldloc, newloc, entrysize);
8934 	FREE_LOCK(ump);
8935 }
8936 
8937 /*
8938  * Move the mkdir dependencies and journal work from one diradd to another
8939  * when renaming a directory.  The new name must depend on the mkdir deps
8940  * completing as the old name did.  Directories can only have one valid link
8941  * at a time so one must be canonical.
8942  */
8943 static void
merge_diradd(struct inodedep * inodedep,struct diradd * newdap)8944 merge_diradd(struct inodedep *inodedep, struct diradd *newdap)
8945 {
8946 	struct diradd *olddap;
8947 	struct mkdir *mkdir, *nextmd;
8948 	struct ufsmount *ump;
8949 	short state;
8950 
8951 	olddap = inodedep->id_mkdiradd;
8952 	inodedep->id_mkdiradd = newdap;
8953 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8954 		newdap->da_state &= ~DEPCOMPLETE;
8955 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
8956 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8957 		     mkdir = nextmd) {
8958 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8959 			if (mkdir->md_diradd != olddap)
8960 				continue;
8961 			mkdir->md_diradd = newdap;
8962 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8963 			newdap->da_state |= state;
8964 			olddap->da_state &= ~state;
8965 			if ((olddap->da_state &
8966 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
8967 				break;
8968 		}
8969 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8970 			panic("merge_diradd: unfound ref");
8971 	}
8972 	/*
8973 	 * Any mkdir related journal items are not safe to be freed until
8974 	 * the new name is stable.
8975 	 */
8976 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8977 	olddap->da_state |= DEPCOMPLETE;
8978 	complete_diradd(olddap);
8979 }
8980 
8981 /*
8982  * Move the diradd to the pending list when all diradd dependencies are
8983  * complete.
8984  */
8985 static void
complete_diradd(struct diradd * dap)8986 complete_diradd(struct diradd *dap)
8987 {
8988 	struct pagedep *pagedep;
8989 
8990 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8991 		if (dap->da_state & DIRCHG)
8992 			pagedep = dap->da_previous->dm_pagedep;
8993 		else
8994 			pagedep = dap->da_pagedep;
8995 		LIST_REMOVE(dap, da_pdlist);
8996 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8997 	}
8998 }
8999 
9000 /*
9001  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
9002  * add entries and conditionally journal the remove.
9003  */
9004 static void
cancel_diradd(struct diradd * dap,struct dirrem * dirrem,struct jremref * jremref,struct jremref * dotremref,struct jremref * dotdotremref)9005 cancel_diradd(
9006 	struct diradd *dap,
9007 	struct dirrem *dirrem,
9008 	struct jremref *jremref,
9009 	struct jremref *dotremref,
9010 	struct jremref *dotdotremref)
9011 {
9012 	struct inodedep *inodedep;
9013 	struct jaddref *jaddref;
9014 	struct inoref *inoref;
9015 	struct ufsmount *ump;
9016 	struct mkdir *mkdir;
9017 
9018 	/*
9019 	 * If no remove references were allocated we're on a non-journaled
9020 	 * filesystem and can skip the cancel step.
9021 	 */
9022 	if (jremref == NULL) {
9023 		free_diradd(dap, NULL);
9024 		return;
9025 	}
9026 	/*
9027 	 * Cancel the primary name an free it if it does not require
9028 	 * journaling.
9029 	 */
9030 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
9031 	    0, &inodedep) != 0) {
9032 		/* Abort the addref that reference this diradd.  */
9033 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
9034 			if (inoref->if_list.wk_type != D_JADDREF)
9035 				continue;
9036 			jaddref = (struct jaddref *)inoref;
9037 			if (jaddref->ja_diradd != dap)
9038 				continue;
9039 			if (cancel_jaddref(jaddref, inodedep,
9040 			    &dirrem->dm_jwork) == 0) {
9041 				free_jremref(jremref);
9042 				jremref = NULL;
9043 			}
9044 			break;
9045 		}
9046 	}
9047 	/*
9048 	 * Cancel subordinate names and free them if they do not require
9049 	 * journaling.
9050 	 */
9051 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9052 		ump = VFSTOUFS(dap->da_list.wk_mp);
9053 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
9054 			if (mkdir->md_diradd != dap)
9055 				continue;
9056 			if ((jaddref = mkdir->md_jaddref) == NULL)
9057 				continue;
9058 			mkdir->md_jaddref = NULL;
9059 			if (mkdir->md_state & MKDIR_PARENT) {
9060 				if (cancel_jaddref(jaddref, NULL,
9061 				    &dirrem->dm_jwork) == 0) {
9062 					free_jremref(dotdotremref);
9063 					dotdotremref = NULL;
9064 				}
9065 			} else {
9066 				if (cancel_jaddref(jaddref, inodedep,
9067 				    &dirrem->dm_jwork) == 0) {
9068 					free_jremref(dotremref);
9069 					dotremref = NULL;
9070 				}
9071 			}
9072 		}
9073 	}
9074 
9075 	if (jremref)
9076 		journal_jremref(dirrem, jremref, inodedep);
9077 	if (dotremref)
9078 		journal_jremref(dirrem, dotremref, inodedep);
9079 	if (dotdotremref)
9080 		journal_jremref(dirrem, dotdotremref, NULL);
9081 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
9082 	free_diradd(dap, &dirrem->dm_jwork);
9083 }
9084 
9085 /*
9086  * Free a diradd dependency structure.
9087  */
9088 static void
free_diradd(struct diradd * dap,struct workhead * wkhd)9089 free_diradd(struct diradd *dap, struct workhead *wkhd)
9090 {
9091 	struct dirrem *dirrem;
9092 	struct pagedep *pagedep;
9093 	struct inodedep *inodedep;
9094 	struct mkdir *mkdir, *nextmd;
9095 	struct ufsmount *ump;
9096 
9097 	ump = VFSTOUFS(dap->da_list.wk_mp);
9098 	LOCK_OWNED(ump);
9099 	LIST_REMOVE(dap, da_pdlist);
9100 	if (dap->da_state & ONWORKLIST)
9101 		WORKLIST_REMOVE(&dap->da_list);
9102 	if ((dap->da_state & DIRCHG) == 0) {
9103 		pagedep = dap->da_pagedep;
9104 	} else {
9105 		dirrem = dap->da_previous;
9106 		pagedep = dirrem->dm_pagedep;
9107 		dirrem->dm_dirinum = pagedep->pd_ino;
9108 		dirrem->dm_state |= COMPLETE;
9109 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9110 			add_to_worklist(&dirrem->dm_list, 0);
9111 	}
9112 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
9113 	    0, &inodedep) != 0)
9114 		if (inodedep->id_mkdiradd == dap)
9115 			inodedep->id_mkdiradd = NULL;
9116 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9117 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9118 		     mkdir = nextmd) {
9119 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
9120 			if (mkdir->md_diradd != dap)
9121 				continue;
9122 			dap->da_state &=
9123 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
9124 			LIST_REMOVE(mkdir, md_mkdirs);
9125 			if (mkdir->md_state & ONWORKLIST)
9126 				WORKLIST_REMOVE(&mkdir->md_list);
9127 			if (mkdir->md_jaddref != NULL)
9128 				panic("free_diradd: Unexpected jaddref");
9129 			WORKITEM_FREE(mkdir, D_MKDIR);
9130 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
9131 				break;
9132 		}
9133 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
9134 			panic("free_diradd: unfound ref");
9135 	}
9136 	if (inodedep)
9137 		free_inodedep(inodedep);
9138 	/*
9139 	 * Free any journal segments waiting for the directory write.
9140 	 */
9141 	handle_jwork(&dap->da_jwork);
9142 	WORKITEM_FREE(dap, D_DIRADD);
9143 }
9144 
9145 /*
9146  * Directory entry removal dependencies.
9147  *
9148  * When removing a directory entry, the entry's inode pointer must be
9149  * zero'ed on disk before the corresponding inode's link count is decremented
9150  * (possibly freeing the inode for re-use). This dependency is handled by
9151  * updating the directory entry but delaying the inode count reduction until
9152  * after the directory block has been written to disk. After this point, the
9153  * inode count can be decremented whenever it is convenient.
9154  */
9155 
9156 /*
9157  * This routine should be called immediately after removing
9158  * a directory entry.  The inode's link count should not be
9159  * decremented by the calling procedure -- the soft updates
9160  * code will do this task when it is safe.
9161  */
9162 void
softdep_setup_remove(struct buf * bp,struct inode * dp,struct inode * ip,int isrmdir)9163 softdep_setup_remove(
9164 	struct buf *bp,		/* buffer containing directory block */
9165 	struct inode *dp,	/* inode for the directory being modified */
9166 	struct inode *ip,	/* inode for directory entry being removed */
9167 	int isrmdir)		/* indicates if doing RMDIR */
9168 {
9169 	struct dirrem *dirrem, *prevdirrem;
9170 	struct inodedep *inodedep;
9171 	struct ufsmount *ump;
9172 	int direct;
9173 
9174 	ump = ITOUMP(ip);
9175 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9176 	    ("softdep_setup_remove called on non-softdep filesystem"));
9177 	/*
9178 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
9179 	 * newdirrem() to setup the full directory remove which requires
9180 	 * isrmdir > 1.
9181 	 */
9182 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9183 	/*
9184 	 * Add the dirrem to the inodedep's pending remove list for quick
9185 	 * discovery later.
9186 	 */
9187 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
9188 		panic("softdep_setup_remove: Lost inodedep.");
9189 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
9190 	dirrem->dm_state |= ONDEPLIST;
9191 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9192 
9193 	/*
9194 	 * If the COMPLETE flag is clear, then there were no active
9195 	 * entries and we want to roll back to a zeroed entry until
9196 	 * the new inode is committed to disk. If the COMPLETE flag is
9197 	 * set then we have deleted an entry that never made it to
9198 	 * disk. If the entry we deleted resulted from a name change,
9199 	 * then the old name still resides on disk. We cannot delete
9200 	 * its inode (returned to us in prevdirrem) until the zeroed
9201 	 * directory entry gets to disk. The new inode has never been
9202 	 * referenced on the disk, so can be deleted immediately.
9203 	 */
9204 	if ((dirrem->dm_state & COMPLETE) == 0) {
9205 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9206 		    dm_next);
9207 		FREE_LOCK(ump);
9208 	} else {
9209 		if (prevdirrem != NULL)
9210 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9211 			    prevdirrem, dm_next);
9212 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9213 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9214 		FREE_LOCK(ump);
9215 		if (direct)
9216 			handle_workitem_remove(dirrem, 0);
9217 	}
9218 }
9219 
9220 /*
9221  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9222  * pd_pendinghd list of a pagedep.
9223  */
9224 static struct diradd *
diradd_lookup(struct pagedep * pagedep,int offset)9225 diradd_lookup(struct pagedep *pagedep, int offset)
9226 {
9227 	struct diradd *dap;
9228 
9229 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9230 		if (dap->da_offset == offset)
9231 			return (dap);
9232 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9233 		if (dap->da_offset == offset)
9234 			return (dap);
9235 	return (NULL);
9236 }
9237 
9238 /*
9239  * Search for a .. diradd dependency in a directory that is being removed.
9240  * If the directory was renamed to a new parent we have a diradd rather
9241  * than a mkdir for the .. entry.  We need to cancel it now before
9242  * it is found in truncate().
9243  */
9244 static struct jremref *
cancel_diradd_dotdot(struct inode * ip,struct dirrem * dirrem,struct jremref * jremref)9245 cancel_diradd_dotdot(struct inode *ip,
9246 	struct dirrem *dirrem,
9247 	struct jremref *jremref)
9248 {
9249 	struct pagedep *pagedep;
9250 	struct diradd *dap;
9251 	struct worklist *wk;
9252 
9253 	if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9254 		return (jremref);
9255 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9256 	if (dap == NULL)
9257 		return (jremref);
9258 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9259 	/*
9260 	 * Mark any journal work as belonging to the parent so it is freed
9261 	 * with the .. reference.
9262 	 */
9263 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9264 		wk->wk_state |= MKDIR_PARENT;
9265 	return (NULL);
9266 }
9267 
9268 /*
9269  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9270  * replace it with a dirrem/diradd pair as a result of re-parenting a
9271  * directory.  This ensures that we don't simultaneously have a mkdir and
9272  * a diradd for the same .. entry.
9273  */
9274 static struct jremref *
cancel_mkdir_dotdot(struct inode * ip,struct dirrem * dirrem,struct jremref * jremref)9275 cancel_mkdir_dotdot(struct inode *ip,
9276 	struct dirrem *dirrem,
9277 	struct jremref *jremref)
9278 {
9279 	struct inodedep *inodedep;
9280 	struct jaddref *jaddref;
9281 	struct ufsmount *ump;
9282 	struct mkdir *mkdir;
9283 	struct diradd *dap;
9284 	struct mount *mp;
9285 
9286 	mp = ITOVFS(ip);
9287 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9288 		return (jremref);
9289 	dap = inodedep->id_mkdiradd;
9290 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9291 		return (jremref);
9292 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9293 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9294 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9295 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9296 			break;
9297 	if (mkdir == NULL)
9298 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9299 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9300 		mkdir->md_jaddref = NULL;
9301 		jaddref->ja_state &= ~MKDIR_PARENT;
9302 		if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9303 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9304 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9305 			journal_jremref(dirrem, jremref, inodedep);
9306 			jremref = NULL;
9307 		}
9308 	}
9309 	if (mkdir->md_state & ONWORKLIST)
9310 		WORKLIST_REMOVE(&mkdir->md_list);
9311 	mkdir->md_state |= ALLCOMPLETE;
9312 	complete_mkdir(mkdir);
9313 	return (jremref);
9314 }
9315 
9316 static void
journal_jremref(struct dirrem * dirrem,struct jremref * jremref,struct inodedep * inodedep)9317 journal_jremref(struct dirrem *dirrem,
9318 	struct jremref *jremref,
9319 	struct inodedep *inodedep)
9320 {
9321 
9322 	if (inodedep == NULL)
9323 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9324 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9325 			panic("journal_jremref: Lost inodedep");
9326 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9327 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9328 	add_to_journal(&jremref->jr_list);
9329 }
9330 
9331 static void
dirrem_journal(struct dirrem * dirrem,struct jremref * jremref,struct jremref * dotremref,struct jremref * dotdotremref)9332 dirrem_journal(
9333 	struct dirrem *dirrem,
9334 	struct jremref *jremref,
9335 	struct jremref *dotremref,
9336 	struct jremref *dotdotremref)
9337 {
9338 	struct inodedep *inodedep;
9339 
9340 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9341 	    &inodedep) == 0)
9342 		panic("dirrem_journal: Lost inodedep");
9343 	journal_jremref(dirrem, jremref, inodedep);
9344 	if (dotremref)
9345 		journal_jremref(dirrem, dotremref, inodedep);
9346 	if (dotdotremref)
9347 		journal_jremref(dirrem, dotdotremref, NULL);
9348 }
9349 
9350 /*
9351  * Allocate a new dirrem if appropriate and return it along with
9352  * its associated pagedep. Called without a lock, returns with lock.
9353  */
9354 static struct dirrem *
newdirrem(struct buf * bp,struct inode * dp,struct inode * ip,int isrmdir,struct dirrem ** prevdirremp)9355 newdirrem(
9356 	struct buf *bp,		/* buffer containing directory block */
9357 	struct inode *dp,	/* inode for the directory being modified */
9358 	struct inode *ip,	/* inode for directory entry being removed */
9359 	int isrmdir,		/* indicates if doing RMDIR */
9360 	struct dirrem **prevdirremp) /* previously referenced inode, if any */
9361 {
9362 	int offset;
9363 	ufs_lbn_t lbn;
9364 	struct diradd *dap;
9365 	struct dirrem *dirrem;
9366 	struct pagedep *pagedep;
9367 	struct jremref *jremref;
9368 	struct jremref *dotremref;
9369 	struct jremref *dotdotremref;
9370 	struct vnode *dvp;
9371 	struct ufsmount *ump;
9372 
9373 	/*
9374 	 * Whiteouts have no deletion dependencies.
9375 	 */
9376 	if (ip == NULL)
9377 		panic("newdirrem: whiteout");
9378 	dvp = ITOV(dp);
9379 	ump = ITOUMP(dp);
9380 
9381 	/*
9382 	 * If the system is over its limit and our filesystem is
9383 	 * responsible for more than our share of that usage and
9384 	 * we are not a snapshot, request some inodedep cleanup.
9385 	 * Limiting the number of dirrem structures will also limit
9386 	 * the number of freefile and freeblks structures.
9387 	 */
9388 	ACQUIRE_LOCK(ump);
9389 	if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9390 		schedule_cleanup(UFSTOVFS(ump));
9391 	else
9392 		FREE_LOCK(ump);
9393 	dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9394 	    M_ZERO);
9395 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9396 	LIST_INIT(&dirrem->dm_jremrefhd);
9397 	LIST_INIT(&dirrem->dm_jwork);
9398 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9399 	dirrem->dm_oldinum = ip->i_number;
9400 	*prevdirremp = NULL;
9401 	/*
9402 	 * Allocate remove reference structures to track journal write
9403 	 * dependencies.  We will always have one for the link and
9404 	 * when doing directories we will always have one more for dot.
9405 	 * When renaming a directory we skip the dotdot link change so
9406 	 * this is not needed.
9407 	 */
9408 	jremref = dotremref = dotdotremref = NULL;
9409 	if (DOINGSUJ(dvp)) {
9410 		if (isrmdir) {
9411 			jremref = newjremref(dirrem, dp, ip, I_OFFSET(dp),
9412 			    ip->i_effnlink + 2);
9413 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9414 			    ip->i_effnlink + 1);
9415 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9416 			    dp->i_effnlink + 1);
9417 			dotdotremref->jr_state |= MKDIR_PARENT;
9418 		} else
9419 			jremref = newjremref(dirrem, dp, ip, I_OFFSET(dp),
9420 			    ip->i_effnlink + 1);
9421 	}
9422 	ACQUIRE_LOCK(ump);
9423 	lbn = lblkno(ump->um_fs, I_OFFSET(dp));
9424 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9425 	pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9426 	    &pagedep);
9427 	dirrem->dm_pagedep = pagedep;
9428 	dirrem->dm_offset = offset;
9429 	/*
9430 	 * If we're renaming a .. link to a new directory, cancel any
9431 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9432 	 * the jremref is preserved for any potential diradd in this
9433 	 * location.  This can not coincide with a rmdir.
9434 	 */
9435 	if (I_OFFSET(dp) == DOTDOT_OFFSET) {
9436 		if (isrmdir)
9437 			panic("newdirrem: .. directory change during remove?");
9438 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9439 	}
9440 	/*
9441 	 * If we're removing a directory search for the .. dependency now and
9442 	 * cancel it.  Any pending journal work will be added to the dirrem
9443 	 * to be completed when the workitem remove completes.
9444 	 */
9445 	if (isrmdir)
9446 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9447 	/*
9448 	 * Check for a diradd dependency for the same directory entry.
9449 	 * If present, then both dependencies become obsolete and can
9450 	 * be de-allocated.
9451 	 */
9452 	dap = diradd_lookup(pagedep, offset);
9453 	if (dap == NULL) {
9454 		/*
9455 		 * Link the jremref structures into the dirrem so they are
9456 		 * written prior to the pagedep.
9457 		 */
9458 		if (jremref)
9459 			dirrem_journal(dirrem, jremref, dotremref,
9460 			    dotdotremref);
9461 		return (dirrem);
9462 	}
9463 	/*
9464 	 * Must be ATTACHED at this point.
9465 	 */
9466 	if ((dap->da_state & ATTACHED) == 0)
9467 		panic("newdirrem: not ATTACHED");
9468 	if (dap->da_newinum != ip->i_number)
9469 		panic("newdirrem: inum %ju should be %ju",
9470 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9471 	/*
9472 	 * If we are deleting a changed name that never made it to disk,
9473 	 * then return the dirrem describing the previous inode (which
9474 	 * represents the inode currently referenced from this entry on disk).
9475 	 */
9476 	if ((dap->da_state & DIRCHG) != 0) {
9477 		*prevdirremp = dap->da_previous;
9478 		dap->da_state &= ~DIRCHG;
9479 		dap->da_pagedep = pagedep;
9480 	}
9481 	/*
9482 	 * We are deleting an entry that never made it to disk.
9483 	 * Mark it COMPLETE so we can delete its inode immediately.
9484 	 */
9485 	dirrem->dm_state |= COMPLETE;
9486 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9487 #ifdef INVARIANTS
9488 	if (isrmdir == 0) {
9489 		struct worklist *wk;
9490 
9491 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9492 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9493 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9494 	}
9495 #endif
9496 
9497 	return (dirrem);
9498 }
9499 
9500 /*
9501  * Directory entry change dependencies.
9502  *
9503  * Changing an existing directory entry requires that an add operation
9504  * be completed first followed by a deletion. The semantics for the addition
9505  * are identical to the description of adding a new entry above except
9506  * that the rollback is to the old inode number rather than zero. Once
9507  * the addition dependency is completed, the removal is done as described
9508  * in the removal routine above.
9509  */
9510 
9511 /*
9512  * This routine should be called immediately after changing
9513  * a directory entry.  The inode's link count should not be
9514  * decremented by the calling procedure -- the soft updates
9515  * code will perform this task when it is safe.
9516  */
9517 void
softdep_setup_directory_change(struct buf * bp,struct inode * dp,struct inode * ip,ino_t newinum,int isrmdir)9518 softdep_setup_directory_change(
9519 	struct buf *bp,		/* buffer containing directory block */
9520 	struct inode *dp,	/* inode for the directory being modified */
9521 	struct inode *ip,	/* inode for directory entry being removed */
9522 	ino_t newinum,		/* new inode number for changed entry */
9523 	int isrmdir)		/* indicates if doing RMDIR */
9524 {
9525 	int offset;
9526 	struct diradd *dap = NULL;
9527 	struct dirrem *dirrem, *prevdirrem;
9528 	struct pagedep *pagedep;
9529 	struct inodedep *inodedep;
9530 	struct jaddref *jaddref;
9531 	struct mount *mp;
9532 	struct ufsmount *ump;
9533 
9534 	mp = ITOVFS(dp);
9535 	ump = VFSTOUFS(mp);
9536 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9537 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9538 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9539 
9540 	/*
9541 	 * Whiteouts do not need diradd dependencies.
9542 	 */
9543 	if (newinum != UFS_WINO) {
9544 		dap = malloc(sizeof(struct diradd),
9545 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9546 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9547 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9548 		dap->da_offset = offset;
9549 		dap->da_newinum = newinum;
9550 		LIST_INIT(&dap->da_jwork);
9551 	}
9552 
9553 	/*
9554 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9555 	 */
9556 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9557 	pagedep = dirrem->dm_pagedep;
9558 	/*
9559 	 * The possible values for isrmdir:
9560 	 *	0 - non-directory file rename
9561 	 *	1 - directory rename within same directory
9562 	 *   inum - directory rename to new directory of given inode number
9563 	 * When renaming to a new directory, we are both deleting and
9564 	 * creating a new directory entry, so the link count on the new
9565 	 * directory should not change. Thus we do not need the followup
9566 	 * dirrem which is usually done in handle_workitem_remove. We set
9567 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9568 	 * followup dirrem.
9569 	 */
9570 	if (isrmdir > 1)
9571 		dirrem->dm_state |= DIRCHG;
9572 
9573 	/*
9574 	 * Whiteouts have no additional dependencies,
9575 	 * so just put the dirrem on the correct list.
9576 	 */
9577 	if (newinum == UFS_WINO) {
9578 		if ((dirrem->dm_state & COMPLETE) == 0) {
9579 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9580 			    dm_next);
9581 		} else {
9582 			dirrem->dm_dirinum = pagedep->pd_ino;
9583 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9584 				add_to_worklist(&dirrem->dm_list, 0);
9585 		}
9586 		FREE_LOCK(ump);
9587 		return;
9588 	}
9589 	/*
9590 	 * Add the dirrem to the inodedep's pending remove list for quick
9591 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9592 	 * will not fail.
9593 	 */
9594 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9595 		panic("softdep_setup_directory_change: Lost inodedep.");
9596 	dirrem->dm_state |= ONDEPLIST;
9597 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9598 
9599 	/*
9600 	 * If the COMPLETE flag is clear, then there were no active
9601 	 * entries and we want to roll back to the previous inode until
9602 	 * the new inode is committed to disk. If the COMPLETE flag is
9603 	 * set, then we have deleted an entry that never made it to disk.
9604 	 * If the entry we deleted resulted from a name change, then the old
9605 	 * inode reference still resides on disk. Any rollback that we do
9606 	 * needs to be to that old inode (returned to us in prevdirrem). If
9607 	 * the entry we deleted resulted from a create, then there is
9608 	 * no entry on the disk, so we want to roll back to zero rather
9609 	 * than the uncommitted inode. In either of the COMPLETE cases we
9610 	 * want to immediately free the unwritten and unreferenced inode.
9611 	 */
9612 	if ((dirrem->dm_state & COMPLETE) == 0) {
9613 		dap->da_previous = dirrem;
9614 	} else {
9615 		if (prevdirrem != NULL) {
9616 			dap->da_previous = prevdirrem;
9617 		} else {
9618 			dap->da_state &= ~DIRCHG;
9619 			dap->da_pagedep = pagedep;
9620 		}
9621 		dirrem->dm_dirinum = pagedep->pd_ino;
9622 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9623 			add_to_worklist(&dirrem->dm_list, 0);
9624 	}
9625 	/*
9626 	 * Lookup the jaddref for this journal entry.  We must finish
9627 	 * initializing it and make the diradd write dependent on it.
9628 	 * If we're not journaling, put it on the id_bufwait list if the
9629 	 * inode is not yet written. If it is written, do the post-inode
9630 	 * write processing to put it on the id_pendinghd list.
9631 	 */
9632 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9633 	if (MOUNTEDSUJ(mp)) {
9634 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9635 		    inoreflst);
9636 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9637 		    ("softdep_setup_directory_change: bad jaddref %p",
9638 		    jaddref));
9639 		jaddref->ja_diroff = I_OFFSET(dp);
9640 		jaddref->ja_diradd = dap;
9641 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9642 		    dap, da_pdlist);
9643 		add_to_journal(&jaddref->ja_list);
9644 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9645 		dap->da_state |= COMPLETE;
9646 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9647 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9648 	} else {
9649 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9650 		    dap, da_pdlist);
9651 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9652 	}
9653 	/*
9654 	 * If we're making a new name for a directory that has not been
9655 	 * committed when need to move the dot and dotdot references to
9656 	 * this new name.
9657 	 */
9658 	if (inodedep->id_mkdiradd && I_OFFSET(dp) != DOTDOT_OFFSET)
9659 		merge_diradd(inodedep, dap);
9660 	FREE_LOCK(ump);
9661 }
9662 
9663 /*
9664  * Called whenever the link count on an inode is changed.
9665  * It creates an inode dependency so that the new reference(s)
9666  * to the inode cannot be committed to disk until the updated
9667  * inode has been written.
9668  */
9669 void
softdep_change_linkcnt(struct inode * ip)9670 softdep_change_linkcnt(
9671 	struct inode *ip)	/* the inode with the increased link count */
9672 {
9673 	struct inodedep *inodedep;
9674 	struct ufsmount *ump;
9675 
9676 	ump = ITOUMP(ip);
9677 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9678 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9679 	ACQUIRE_LOCK(ump);
9680 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9681 	if (ip->i_nlink < ip->i_effnlink)
9682 		panic("softdep_change_linkcnt: bad delta");
9683 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9684 	FREE_LOCK(ump);
9685 }
9686 
9687 /*
9688  * Attach a sbdep dependency to the superblock buf so that we can keep
9689  * track of the head of the linked list of referenced but unlinked inodes.
9690  */
9691 void
softdep_setup_sbupdate(struct ufsmount * ump,struct fs * fs,struct buf * bp)9692 softdep_setup_sbupdate(
9693 	struct ufsmount *ump,
9694 	struct fs *fs,
9695 	struct buf *bp)
9696 {
9697 	struct sbdep *sbdep;
9698 	struct worklist *wk;
9699 
9700 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9701 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9702 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9703 		if (wk->wk_type == D_SBDEP)
9704 			break;
9705 	if (wk != NULL)
9706 		return;
9707 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9708 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9709 	sbdep->sb_fs = fs;
9710 	sbdep->sb_ump = ump;
9711 	ACQUIRE_LOCK(ump);
9712 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9713 	FREE_LOCK(ump);
9714 }
9715 
9716 /*
9717  * Return the first unlinked inodedep which is ready to be the head of the
9718  * list.  The inodedep and all those after it must have valid next pointers.
9719  */
9720 static struct inodedep *
first_unlinked_inodedep(struct ufsmount * ump)9721 first_unlinked_inodedep(struct ufsmount *ump)
9722 {
9723 	struct inodedep *inodedep;
9724 	struct inodedep *idp;
9725 
9726 	LOCK_OWNED(ump);
9727 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9728 	    inodedep; inodedep = idp) {
9729 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9730 			return (NULL);
9731 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9732 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9733 			break;
9734 		if ((inodedep->id_state & UNLINKPREV) == 0)
9735 			break;
9736 	}
9737 	return (inodedep);
9738 }
9739 
9740 /*
9741  * Set the sujfree unlinked head pointer prior to writing a superblock.
9742  */
9743 static void
initiate_write_sbdep(struct sbdep * sbdep)9744 initiate_write_sbdep(struct sbdep *sbdep)
9745 {
9746 	struct inodedep *inodedep;
9747 	struct fs *bpfs;
9748 	struct fs *fs;
9749 
9750 	bpfs = sbdep->sb_fs;
9751 	fs = sbdep->sb_ump->um_fs;
9752 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9753 	if (inodedep) {
9754 		fs->fs_sujfree = inodedep->id_ino;
9755 		inodedep->id_state |= UNLINKPREV;
9756 	} else
9757 		fs->fs_sujfree = 0;
9758 	bpfs->fs_sujfree = fs->fs_sujfree;
9759 	/*
9760 	 * Because we have made changes to the superblock, we need to
9761 	 * recompute its check-hash.
9762 	 */
9763 	bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9764 }
9765 
9766 /*
9767  * After a superblock is written determine whether it must be written again
9768  * due to a changing unlinked list head.
9769  */
9770 static int
handle_written_sbdep(struct sbdep * sbdep,struct buf * bp)9771 handle_written_sbdep(struct sbdep *sbdep, struct buf *bp)
9772 {
9773 	struct inodedep *inodedep;
9774 	struct fs *fs;
9775 
9776 	LOCK_OWNED(sbdep->sb_ump);
9777 	fs = sbdep->sb_fs;
9778 	/*
9779 	 * If the superblock doesn't match the in-memory list start over.
9780 	 */
9781 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9782 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9783 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9784 		bdirty(bp);
9785 		return (1);
9786 	}
9787 	WORKITEM_FREE(sbdep, D_SBDEP);
9788 	if (fs->fs_sujfree == 0)
9789 		return (0);
9790 	/*
9791 	 * Now that we have a record of this inode in stable store allow it
9792 	 * to be written to free up pending work.  Inodes may see a lot of
9793 	 * write activity after they are unlinked which we must not hold up.
9794 	 */
9795 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9796 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9797 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9798 			    inodedep, inodedep->id_state);
9799 		if (inodedep->id_state & UNLINKONLIST)
9800 			break;
9801 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9802 	}
9803 
9804 	return (0);
9805 }
9806 
9807 /*
9808  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9809  */
9810 static void
unlinked_inodedep(struct mount * mp,struct inodedep * inodedep)9811 unlinked_inodedep( struct mount *mp, struct inodedep *inodedep)
9812 {
9813 	struct ufsmount *ump;
9814 
9815 	ump = VFSTOUFS(mp);
9816 	LOCK_OWNED(ump);
9817 	if (MOUNTEDSUJ(mp) == 0)
9818 		return;
9819 	ump->um_fs->fs_fmod = 1;
9820 	if (inodedep->id_state & UNLINKED)
9821 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9822 	inodedep->id_state |= UNLINKED;
9823 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9824 }
9825 
9826 /*
9827  * Remove an inodedep from the unlinked inodedep list.  This may require
9828  * disk writes if the inode has made it that far.
9829  */
9830 static void
clear_unlinked_inodedep(struct inodedep * inodedep)9831 clear_unlinked_inodedep( struct inodedep *inodedep)
9832 {
9833 	struct ufs2_dinode *dip;
9834 	struct ufsmount *ump;
9835 	struct inodedep *idp;
9836 	struct inodedep *idn;
9837 	struct fs *fs, *bpfs;
9838 	struct buf *bp;
9839 	daddr_t dbn;
9840 	ino_t ino;
9841 	ino_t nino;
9842 	ino_t pino;
9843 	int error;
9844 
9845 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9846 	fs = ump->um_fs;
9847 	ino = inodedep->id_ino;
9848 	error = 0;
9849 	for (;;) {
9850 		LOCK_OWNED(ump);
9851 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9852 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9853 		    inodedep));
9854 		/*
9855 		 * If nothing has yet been written simply remove us from
9856 		 * the in memory list and return.  This is the most common
9857 		 * case where handle_workitem_remove() loses the final
9858 		 * reference.
9859 		 */
9860 		if ((inodedep->id_state & UNLINKLINKS) == 0)
9861 			break;
9862 		/*
9863 		 * If we have a NEXT pointer and no PREV pointer we can simply
9864 		 * clear NEXT's PREV and remove ourselves from the list.  Be
9865 		 * careful not to clear PREV if the superblock points at
9866 		 * next as well.
9867 		 */
9868 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9869 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9870 			if (idn && fs->fs_sujfree != idn->id_ino)
9871 				idn->id_state &= ~UNLINKPREV;
9872 			break;
9873 		}
9874 		/*
9875 		 * Here we have an inodedep which is actually linked into
9876 		 * the list.  We must remove it by forcing a write to the
9877 		 * link before us, whether it be the superblock or an inode.
9878 		 * Unfortunately the list may change while we're waiting
9879 		 * on the buf lock for either resource so we must loop until
9880 		 * we lock the right one.  If both the superblock and an
9881 		 * inode point to this inode we must clear the inode first
9882 		 * followed by the superblock.
9883 		 */
9884 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9885 		pino = 0;
9886 		if (idp && (idp->id_state & UNLINKNEXT))
9887 			pino = idp->id_ino;
9888 		FREE_LOCK(ump);
9889 		if (pino == 0) {
9890 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9891 			    (int)fs->fs_sbsize, 0, 0, 0);
9892 		} else {
9893 			dbn = fsbtodb(fs, ino_to_fsba(fs, pino));
9894 			error = ffs_breadz(ump, ump->um_devvp, dbn, dbn,
9895 			    (int)fs->fs_bsize, NULL, NULL, 0, NOCRED, 0, NULL,
9896 			    &bp);
9897 		}
9898 		ACQUIRE_LOCK(ump);
9899 		if (error)
9900 			break;
9901 		/* If the list has changed restart the loop. */
9902 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9903 		nino = 0;
9904 		if (idp && (idp->id_state & UNLINKNEXT))
9905 			nino = idp->id_ino;
9906 		if (nino != pino ||
9907 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9908 			FREE_LOCK(ump);
9909 			brelse(bp);
9910 			ACQUIRE_LOCK(ump);
9911 			continue;
9912 		}
9913 		nino = 0;
9914 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9915 		if (idn)
9916 			nino = idn->id_ino;
9917 		/*
9918 		 * Remove us from the in memory list.  After this we cannot
9919 		 * access the inodedep.
9920 		 */
9921 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9922 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9923 		    inodedep));
9924 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9925 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9926 		FREE_LOCK(ump);
9927 		/*
9928 		 * The predecessor's next pointer is manually updated here
9929 		 * so that the NEXT flag is never cleared for an element
9930 		 * that is in the list.
9931 		 */
9932 		if (pino == 0) {
9933 			bcopy((caddr_t)fs, bp->b_data, (uint64_t)fs->fs_sbsize);
9934 			bpfs = (struct fs *)bp->b_data;
9935 			ffs_oldfscompat_write(bpfs);
9936 			softdep_setup_sbupdate(ump, bpfs, bp);
9937 			/*
9938 			 * Because we may have made changes to the superblock,
9939 			 * we need to recompute its check-hash.
9940 			 */
9941 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9942 		} else if (fs->fs_magic == FS_UFS1_MAGIC) {
9943 			((struct ufs1_dinode *)bp->b_data +
9944 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9945 		} else {
9946 			dip = (struct ufs2_dinode *)bp->b_data +
9947 			    ino_to_fsbo(fs, pino);
9948 			dip->di_freelink = nino;
9949 			ffs_update_dinode_ckhash(fs, dip);
9950 		}
9951 		/*
9952 		 * If the bwrite fails we have no recourse to recover.  The
9953 		 * filesystem is corrupted already.
9954 		 */
9955 		bwrite(bp);
9956 		ACQUIRE_LOCK(ump);
9957 		/*
9958 		 * If the superblock pointer still needs to be cleared force
9959 		 * a write here.
9960 		 */
9961 		if (fs->fs_sujfree == ino) {
9962 			FREE_LOCK(ump);
9963 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9964 			    (int)fs->fs_sbsize, 0, 0, 0);
9965 			bcopy((caddr_t)fs, bp->b_data, (uint64_t)fs->fs_sbsize);
9966 			bpfs = (struct fs *)bp->b_data;
9967 			ffs_oldfscompat_write(bpfs);
9968 			softdep_setup_sbupdate(ump, bpfs, bp);
9969 			/*
9970 			 * Because we may have made changes to the superblock,
9971 			 * we need to recompute its check-hash.
9972 			 */
9973 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9974 			bwrite(bp);
9975 			ACQUIRE_LOCK(ump);
9976 		}
9977 
9978 		if (fs->fs_sujfree != ino)
9979 			return;
9980 		panic("clear_unlinked_inodedep: Failed to clear free head");
9981 	}
9982 	if (inodedep->id_ino == fs->fs_sujfree)
9983 		panic("clear_unlinked_inodedep: Freeing head of free list");
9984 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9985 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9986 	return;
9987 }
9988 
9989 /*
9990  * This workitem decrements the inode's link count.
9991  * If the link count reaches zero, the file is removed.
9992  */
9993 static int
handle_workitem_remove(struct dirrem * dirrem,int flags)9994 handle_workitem_remove(struct dirrem *dirrem, int flags)
9995 {
9996 	struct inodedep *inodedep;
9997 	struct workhead dotdotwk;
9998 	struct worklist *wk;
9999 	struct ufsmount *ump;
10000 	struct mount *mp;
10001 	struct vnode *vp;
10002 	struct inode *ip;
10003 	ino_t oldinum;
10004 
10005 	if (dirrem->dm_state & ONWORKLIST)
10006 		panic("handle_workitem_remove: dirrem %p still on worklist",
10007 		    dirrem);
10008 	oldinum = dirrem->dm_oldinum;
10009 	mp = dirrem->dm_list.wk_mp;
10010 	ump = VFSTOUFS(mp);
10011 	flags |= LK_EXCLUSIVE;
10012 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ |
10013 	    FFSV_FORCEINODEDEP) != 0)
10014 		return (EBUSY);
10015 	ip = VTOI(vp);
10016 	MPASS(ip->i_mode != 0);
10017 	ACQUIRE_LOCK(ump);
10018 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
10019 		panic("handle_workitem_remove: lost inodedep");
10020 	if (dirrem->dm_state & ONDEPLIST)
10021 		LIST_REMOVE(dirrem, dm_inonext);
10022 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
10023 	    ("handle_workitem_remove:  Journal entries not written."));
10024 
10025 	/*
10026 	 * Move all dependencies waiting on the remove to complete
10027 	 * from the dirrem to the inode inowait list to be completed
10028 	 * after the inode has been updated and written to disk.
10029 	 *
10030 	 * Any marked MKDIR_PARENT are saved to be completed when the
10031 	 * dotdot ref is removed unless DIRCHG is specified.  For
10032 	 * directory change operations there will be no further
10033 	 * directory writes and the jsegdeps need to be moved along
10034 	 * with the rest to be completed when the inode is free or
10035 	 * stable in the inode free list.
10036 	 */
10037 	LIST_INIT(&dotdotwk);
10038 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
10039 		WORKLIST_REMOVE(wk);
10040 		if ((dirrem->dm_state & DIRCHG) == 0 &&
10041 		    wk->wk_state & MKDIR_PARENT) {
10042 			wk->wk_state &= ~MKDIR_PARENT;
10043 			WORKLIST_INSERT(&dotdotwk, wk);
10044 			continue;
10045 		}
10046 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
10047 	}
10048 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
10049 	/*
10050 	 * Normal file deletion.
10051 	 */
10052 	if ((dirrem->dm_state & RMDIR) == 0) {
10053 		ip->i_nlink--;
10054 		KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: file ino "
10055 		    "%ju negative i_nlink %d", (intmax_t)ip->i_number,
10056 		    ip->i_nlink));
10057 		DIP_SET_NLINK(ip, ip->i_nlink);
10058 		UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10059 		if (ip->i_nlink < ip->i_effnlink)
10060 			panic("handle_workitem_remove: bad file delta");
10061 		if (ip->i_nlink == 0)
10062 			unlinked_inodedep(mp, inodedep);
10063 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
10064 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
10065 		    ("handle_workitem_remove: worklist not empty. %s",
10066 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
10067 		WORKITEM_FREE(dirrem, D_DIRREM);
10068 		FREE_LOCK(ump);
10069 		goto out;
10070 	}
10071 	/*
10072 	 * Directory deletion. Decrement reference count for both the
10073 	 * just deleted parent directory entry and the reference for ".".
10074 	 * Arrange to have the reference count on the parent decremented
10075 	 * to account for the loss of "..".
10076 	 */
10077 	ip->i_nlink -= 2;
10078 	KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: directory ino "
10079 	    "%ju negative i_nlink %d", (intmax_t)ip->i_number, ip->i_nlink));
10080 	DIP_SET_NLINK(ip, ip->i_nlink);
10081 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10082 	if (ip->i_nlink < ip->i_effnlink)
10083 		panic("handle_workitem_remove: bad dir delta");
10084 	if (ip->i_nlink == 0)
10085 		unlinked_inodedep(mp, inodedep);
10086 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
10087 	/*
10088 	 * Rename a directory to a new parent. Since, we are both deleting
10089 	 * and creating a new directory entry, the link count on the new
10090 	 * directory should not change. Thus we skip the followup dirrem.
10091 	 */
10092 	if (dirrem->dm_state & DIRCHG) {
10093 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
10094 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
10095 		WORKITEM_FREE(dirrem, D_DIRREM);
10096 		FREE_LOCK(ump);
10097 		goto out;
10098 	}
10099 	dirrem->dm_state = ONDEPLIST;
10100 	dirrem->dm_oldinum = dirrem->dm_dirinum;
10101 	/*
10102 	 * Place the dirrem on the parent's diremhd list.
10103 	 */
10104 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
10105 		panic("handle_workitem_remove: lost dir inodedep");
10106 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
10107 	/*
10108 	 * If the allocated inode has never been written to disk, then
10109 	 * the on-disk inode is zero'ed and we can remove the file
10110 	 * immediately.  When journaling if the inode has been marked
10111 	 * unlinked and not DEPCOMPLETE we know it can never be written.
10112 	 */
10113 	inodedep_lookup(mp, oldinum, 0, &inodedep);
10114 	if (inodedep == NULL ||
10115 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
10116 	    check_inode_unwritten(inodedep)) {
10117 		FREE_LOCK(ump);
10118 		vput(vp);
10119 		return handle_workitem_remove(dirrem, flags);
10120 	}
10121 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
10122 	FREE_LOCK(ump);
10123 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10124 out:
10125 	ffs_update(vp, 0);
10126 	vput(vp);
10127 	return (0);
10128 }
10129 
10130 /*
10131  * Inode de-allocation dependencies.
10132  *
10133  * When an inode's link count is reduced to zero, it can be de-allocated. We
10134  * found it convenient to postpone de-allocation until after the inode is
10135  * written to disk with its new link count (zero).  At this point, all of the
10136  * on-disk inode's block pointers are nullified and, with careful dependency
10137  * list ordering, all dependencies related to the inode will be satisfied and
10138  * the corresponding dependency structures de-allocated.  So, if/when the
10139  * inode is reused, there will be no mixing of old dependencies with new
10140  * ones.  This artificial dependency is set up by the block de-allocation
10141  * procedure above (softdep_setup_freeblocks) and completed by the
10142  * following procedure.
10143  */
10144 static void
handle_workitem_freefile(struct freefile * freefile)10145 handle_workitem_freefile(struct freefile *freefile)
10146 {
10147 	struct workhead wkhd;
10148 	struct fs *fs;
10149 	struct ufsmount *ump;
10150 	int error;
10151 #ifdef INVARIANTS
10152 	struct inodedep *idp;
10153 #endif
10154 
10155 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
10156 	fs = ump->um_fs;
10157 #ifdef INVARIANTS
10158 	ACQUIRE_LOCK(ump);
10159 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
10160 	FREE_LOCK(ump);
10161 	if (error)
10162 		panic("handle_workitem_freefile: inodedep %p survived", idp);
10163 #endif
10164 	UFS_LOCK(ump);
10165 	fs->fs_pendinginodes -= 1;
10166 	UFS_UNLOCK(ump);
10167 	LIST_INIT(&wkhd);
10168 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
10169 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
10170 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
10171 		softdep_error("handle_workitem_freefile", error);
10172 	ACQUIRE_LOCK(ump);
10173 	WORKITEM_FREE(freefile, D_FREEFILE);
10174 	FREE_LOCK(ump);
10175 }
10176 
10177 /*
10178  * Helper function which unlinks marker element from work list and returns
10179  * the next element on the list.
10180  */
10181 static __inline struct worklist *
markernext(struct worklist * marker)10182 markernext(struct worklist *marker)
10183 {
10184 	struct worklist *next;
10185 
10186 	next = LIST_NEXT(marker, wk_list);
10187 	LIST_REMOVE(marker, wk_list);
10188 	return next;
10189 }
10190 
10191 /*
10192  * Disk writes.
10193  *
10194  * The dependency structures constructed above are most actively used when file
10195  * system blocks are written to disk.  No constraints are placed on when a
10196  * block can be written, but unsatisfied update dependencies are made safe by
10197  * modifying (or replacing) the source memory for the duration of the disk
10198  * write.  When the disk write completes, the memory block is again brought
10199  * up-to-date.
10200  *
10201  * In-core inode structure reclamation.
10202  *
10203  * Because there are a finite number of "in-core" inode structures, they are
10204  * reused regularly.  By transferring all inode-related dependencies to the
10205  * in-memory inode block and indexing them separately (via "inodedep"s), we
10206  * can allow "in-core" inode structures to be reused at any time and avoid
10207  * any increase in contention.
10208  *
10209  * Called just before entering the device driver to initiate a new disk I/O.
10210  * The buffer must be locked, thus, no I/O completion operations can occur
10211  * while we are manipulating its associated dependencies.
10212  */
10213 static void
softdep_disk_io_initiation(struct buf * bp)10214 softdep_disk_io_initiation(
10215 	struct buf *bp)		/* structure describing disk write to occur */
10216 {
10217 	struct worklist *wk;
10218 	struct worklist marker;
10219 	struct inodedep *inodedep;
10220 	struct freeblks *freeblks;
10221 	struct jblkdep *jblkdep;
10222 	struct newblk *newblk;
10223 	struct ufsmount *ump;
10224 
10225 	/*
10226 	 * We only care about write operations. There should never
10227 	 * be dependencies for reads.
10228 	 */
10229 	if (bp->b_iocmd != BIO_WRITE)
10230 		panic("softdep_disk_io_initiation: not write");
10231 
10232 	if (bp->b_vflags & BV_BKGRDINPROG)
10233 		panic("softdep_disk_io_initiation: Writing buffer with "
10234 		    "background write in progress: %p", bp);
10235 
10236 	ump = softdep_bp_to_mp(bp);
10237 	if (ump == NULL)
10238 		return;
10239 
10240 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
10241 	PHOLD(curproc);			/* Don't swap out kernel stack */
10242 	ACQUIRE_LOCK(ump);
10243 	/*
10244 	 * Do any necessary pre-I/O processing.
10245 	 */
10246 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10247 	     wk = markernext(&marker)) {
10248 		LIST_INSERT_AFTER(wk, &marker, wk_list);
10249 		switch (wk->wk_type) {
10250 		case D_PAGEDEP:
10251 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
10252 			continue;
10253 
10254 		case D_INODEDEP:
10255 			inodedep = WK_INODEDEP(wk);
10256 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10257 				initiate_write_inodeblock_ufs1(inodedep, bp);
10258 			else
10259 				initiate_write_inodeblock_ufs2(inodedep, bp);
10260 			continue;
10261 
10262 		case D_INDIRDEP:
10263 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10264 			continue;
10265 
10266 		case D_BMSAFEMAP:
10267 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10268 			continue;
10269 
10270 		case D_JSEG:
10271 			WK_JSEG(wk)->js_buf = NULL;
10272 			continue;
10273 
10274 		case D_FREEBLKS:
10275 			freeblks = WK_FREEBLKS(wk);
10276 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10277 			/*
10278 			 * We have to wait for the freeblks to be journaled
10279 			 * before we can write an inodeblock with updated
10280 			 * pointers.  Be careful to arrange the marker so
10281 			 * we revisit the freeblks if it's not removed by
10282 			 * the first jwait().
10283 			 */
10284 			if (jblkdep != NULL) {
10285 				LIST_REMOVE(&marker, wk_list);
10286 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10287 				jwait(&jblkdep->jb_list, MNT_WAIT);
10288 			}
10289 			continue;
10290 		case D_ALLOCDIRECT:
10291 		case D_ALLOCINDIR:
10292 			/*
10293 			 * We have to wait for the jnewblk to be journaled
10294 			 * before we can write to a block if the contents
10295 			 * may be confused with an earlier file's indirect
10296 			 * at recovery time.  Handle the marker as described
10297 			 * above.
10298 			 */
10299 			newblk = WK_NEWBLK(wk);
10300 			if (newblk->nb_jnewblk != NULL &&
10301 			    indirblk_lookup(newblk->nb_list.wk_mp,
10302 			    newblk->nb_newblkno)) {
10303 				LIST_REMOVE(&marker, wk_list);
10304 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10305 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10306 			}
10307 			continue;
10308 
10309 		case D_SBDEP:
10310 			initiate_write_sbdep(WK_SBDEP(wk));
10311 			continue;
10312 
10313 		case D_MKDIR:
10314 		case D_FREEWORK:
10315 		case D_FREEDEP:
10316 		case D_JSEGDEP:
10317 			continue;
10318 
10319 		default:
10320 			panic("handle_disk_io_initiation: Unexpected type %s",
10321 			    TYPENAME(wk->wk_type));
10322 			/* NOTREACHED */
10323 		}
10324 	}
10325 	FREE_LOCK(ump);
10326 	PRELE(curproc);			/* Allow swapout of kernel stack */
10327 }
10328 
10329 /*
10330  * Called from within the procedure above to deal with unsatisfied
10331  * allocation dependencies in a directory. The buffer must be locked,
10332  * thus, no I/O completion operations can occur while we are
10333  * manipulating its associated dependencies.
10334  */
10335 static void
initiate_write_filepage(struct pagedep * pagedep,struct buf * bp)10336 initiate_write_filepage(struct pagedep *pagedep, struct buf *bp)
10337 {
10338 	struct jremref *jremref;
10339 	struct jmvref *jmvref;
10340 	struct dirrem *dirrem;
10341 	struct diradd *dap;
10342 	struct direct *ep;
10343 	int i;
10344 
10345 	if (pagedep->pd_state & IOSTARTED) {
10346 		/*
10347 		 * This can only happen if there is a driver that does not
10348 		 * understand chaining. Here biodone will reissue the call
10349 		 * to strategy for the incomplete buffers.
10350 		 */
10351 		printf("initiate_write_filepage: already started\n");
10352 		return;
10353 	}
10354 	pagedep->pd_state |= IOSTARTED;
10355 	/*
10356 	 * Wait for all journal remove dependencies to hit the disk.
10357 	 * We can not allow any potentially conflicting directory adds
10358 	 * to be visible before removes and rollback is too difficult.
10359 	 * The per-filesystem lock may be dropped and re-acquired, however
10360 	 * we hold the buf locked so the dependency can not go away.
10361 	 */
10362 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10363 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10364 			jwait(&jremref->jr_list, MNT_WAIT);
10365 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10366 		jwait(&jmvref->jm_list, MNT_WAIT);
10367 	for (i = 0; i < DAHASHSZ; i++) {
10368 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10369 			ep = (struct direct *)
10370 			    ((char *)bp->b_data + dap->da_offset);
10371 			if (ep->d_ino != dap->da_newinum)
10372 				panic("%s: dir inum %ju != new %ju",
10373 				    "initiate_write_filepage",
10374 				    (uintmax_t)ep->d_ino,
10375 				    (uintmax_t)dap->da_newinum);
10376 			if (dap->da_state & DIRCHG)
10377 				ep->d_ino = dap->da_previous->dm_oldinum;
10378 			else
10379 				ep->d_ino = 0;
10380 			dap->da_state &= ~ATTACHED;
10381 			dap->da_state |= UNDONE;
10382 		}
10383 	}
10384 }
10385 
10386 /*
10387  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10388  * Note that any bug fixes made to this routine must be done in the
10389  * version found below.
10390  *
10391  * Called from within the procedure above to deal with unsatisfied
10392  * allocation dependencies in an inodeblock. The buffer must be
10393  * locked, thus, no I/O completion operations can occur while we
10394  * are manipulating its associated dependencies.
10395  */
10396 static void
initiate_write_inodeblock_ufs1(struct inodedep * inodedep,struct buf * bp)10397 initiate_write_inodeblock_ufs1(
10398 	struct inodedep *inodedep,
10399 	struct buf *bp)			/* The inode block */
10400 {
10401 	struct allocdirect *adp, *lastadp;
10402 	struct ufs1_dinode *dp;
10403 	struct ufs1_dinode *sip;
10404 	struct inoref *inoref;
10405 	struct ufsmount *ump;
10406 	struct fs *fs;
10407 	ufs_lbn_t i;
10408 #ifdef INVARIANTS
10409 	ufs_lbn_t prevlbn = 0;
10410 #endif
10411 	int deplist __diagused;
10412 
10413 	if (inodedep->id_state & IOSTARTED)
10414 		panic("initiate_write_inodeblock_ufs1: already started");
10415 	inodedep->id_state |= IOSTARTED;
10416 	fs = inodedep->id_fs;
10417 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10418 	LOCK_OWNED(ump);
10419 	dp = (struct ufs1_dinode *)bp->b_data +
10420 	    ino_to_fsbo(fs, inodedep->id_ino);
10421 
10422 	/*
10423 	 * If we're on the unlinked list but have not yet written our
10424 	 * next pointer initialize it here.
10425 	 */
10426 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10427 		struct inodedep *inon;
10428 
10429 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10430 		dp->di_freelink = inon ? inon->id_ino : 0;
10431 	}
10432 	/*
10433 	 * If the bitmap is not yet written, then the allocated
10434 	 * inode cannot be written to disk.
10435 	 */
10436 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10437 		if (inodedep->id_savedino1 != NULL)
10438 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10439 		FREE_LOCK(ump);
10440 		sip = malloc(sizeof(struct ufs1_dinode),
10441 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10442 		ACQUIRE_LOCK(ump);
10443 		inodedep->id_savedino1 = sip;
10444 		*inodedep->id_savedino1 = *dp;
10445 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10446 		dp->di_gen = inodedep->id_savedino1->di_gen;
10447 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10448 		return;
10449 	}
10450 	/*
10451 	 * If no dependencies, then there is nothing to roll back.
10452 	 */
10453 	inodedep->id_savedsize = dp->di_size;
10454 	inodedep->id_savedextsize = 0;
10455 	inodedep->id_savednlink = dp->di_nlink;
10456 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10457 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10458 		return;
10459 	/*
10460 	 * Revert the link count to that of the first unwritten journal entry.
10461 	 */
10462 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10463 	if (inoref)
10464 		dp->di_nlink = inoref->if_nlink;
10465 	/*
10466 	 * Set the dependencies to busy.
10467 	 */
10468 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10469 	     adp = TAILQ_NEXT(adp, ad_next)) {
10470 #ifdef INVARIANTS
10471 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10472 			panic("softdep_write_inodeblock: lbn order");
10473 		prevlbn = adp->ad_offset;
10474 		if (adp->ad_offset < UFS_NDADDR &&
10475 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10476 			panic("initiate_write_inodeblock_ufs1: "
10477 			    "direct pointer #%jd mismatch %d != %jd",
10478 			    (intmax_t)adp->ad_offset,
10479 			    dp->di_db[adp->ad_offset],
10480 			    (intmax_t)adp->ad_newblkno);
10481 		if (adp->ad_offset >= UFS_NDADDR &&
10482 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10483 			panic("initiate_write_inodeblock_ufs1: "
10484 			    "indirect pointer #%jd mismatch %d != %jd",
10485 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10486 			    dp->di_ib[adp->ad_offset - UFS_NDADDR],
10487 			    (intmax_t)adp->ad_newblkno);
10488 		deplist |= 1 << adp->ad_offset;
10489 		if ((adp->ad_state & ATTACHED) == 0)
10490 			panic("initiate_write_inodeblock_ufs1: "
10491 			    "Unknown state 0x%x", adp->ad_state);
10492 #endif /* INVARIANTS */
10493 		adp->ad_state &= ~ATTACHED;
10494 		adp->ad_state |= UNDONE;
10495 	}
10496 	/*
10497 	 * The on-disk inode cannot claim to be any larger than the last
10498 	 * fragment that has been written. Otherwise, the on-disk inode
10499 	 * might have fragments that were not the last block in the file
10500 	 * which would corrupt the filesystem.
10501 	 */
10502 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10503 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10504 		if (adp->ad_offset >= UFS_NDADDR)
10505 			break;
10506 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10507 		/* keep going until hitting a rollback to a frag */
10508 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10509 			continue;
10510 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10511 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10512 #ifdef INVARIANTS
10513 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10514 				panic("initiate_write_inodeblock_ufs1: "
10515 				    "lost dep1");
10516 #endif /* INVARIANTS */
10517 			dp->di_db[i] = 0;
10518 		}
10519 		for (i = 0; i < UFS_NIADDR; i++) {
10520 #ifdef INVARIANTS
10521 			if (dp->di_ib[i] != 0 &&
10522 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10523 				panic("initiate_write_inodeblock_ufs1: "
10524 				    "lost dep2");
10525 #endif /* INVARIANTS */
10526 			dp->di_ib[i] = 0;
10527 		}
10528 		return;
10529 	}
10530 	/*
10531 	 * If we have zero'ed out the last allocated block of the file,
10532 	 * roll back the size to the last currently allocated block.
10533 	 * We know that this last allocated block is a full-sized as
10534 	 * we already checked for fragments in the loop above.
10535 	 */
10536 	if (lastadp != NULL &&
10537 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10538 		for (i = lastadp->ad_offset; i >= 0; i--)
10539 			if (dp->di_db[i] != 0)
10540 				break;
10541 		dp->di_size = (i + 1) * fs->fs_bsize;
10542 	}
10543 	/*
10544 	 * The only dependencies are for indirect blocks.
10545 	 *
10546 	 * The file size for indirect block additions is not guaranteed.
10547 	 * Such a guarantee would be non-trivial to achieve. The conventional
10548 	 * synchronous write implementation also does not make this guarantee.
10549 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10550 	 * can be over-estimated without destroying integrity when the file
10551 	 * moves into the indirect blocks (i.e., is large). If we want to
10552 	 * postpone fsck, we are stuck with this argument.
10553 	 */
10554 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10555 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10556 }
10557 
10558 /*
10559  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10560  * Note that any bug fixes made to this routine must be done in the
10561  * version found above.
10562  *
10563  * Called from within the procedure above to deal with unsatisfied
10564  * allocation dependencies in an inodeblock. The buffer must be
10565  * locked, thus, no I/O completion operations can occur while we
10566  * are manipulating its associated dependencies.
10567  */
10568 static void
initiate_write_inodeblock_ufs2(struct inodedep * inodedep,struct buf * bp)10569 initiate_write_inodeblock_ufs2(
10570 	struct inodedep *inodedep,
10571 	struct buf *bp)			/* The inode block */
10572 {
10573 	struct allocdirect *adp, *lastadp;
10574 	struct ufs2_dinode *dp;
10575 	struct ufs2_dinode *sip;
10576 	struct inoref *inoref;
10577 	struct ufsmount *ump;
10578 	struct fs *fs;
10579 	ufs_lbn_t i;
10580 #ifdef INVARIANTS
10581 	ufs_lbn_t prevlbn = 0;
10582 #endif
10583 	int deplist __diagused;
10584 
10585 	if (inodedep->id_state & IOSTARTED)
10586 		panic("initiate_write_inodeblock_ufs2: already started");
10587 	inodedep->id_state |= IOSTARTED;
10588 	fs = inodedep->id_fs;
10589 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10590 	LOCK_OWNED(ump);
10591 	dp = (struct ufs2_dinode *)bp->b_data +
10592 	    ino_to_fsbo(fs, inodedep->id_ino);
10593 
10594 	/*
10595 	 * If we're on the unlinked list but have not yet written our
10596 	 * next pointer initialize it here.
10597 	 */
10598 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10599 		struct inodedep *inon;
10600 
10601 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10602 		dp->di_freelink = inon ? inon->id_ino : 0;
10603 		ffs_update_dinode_ckhash(fs, dp);
10604 	}
10605 	/*
10606 	 * If the bitmap is not yet written, then the allocated
10607 	 * inode cannot be written to disk.
10608 	 */
10609 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10610 		if (inodedep->id_savedino2 != NULL)
10611 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10612 		FREE_LOCK(ump);
10613 		sip = malloc(sizeof(struct ufs2_dinode),
10614 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10615 		ACQUIRE_LOCK(ump);
10616 		inodedep->id_savedino2 = sip;
10617 		*inodedep->id_savedino2 = *dp;
10618 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10619 		dp->di_gen = inodedep->id_savedino2->di_gen;
10620 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10621 		return;
10622 	}
10623 	/*
10624 	 * If no dependencies, then there is nothing to roll back.
10625 	 */
10626 	inodedep->id_savedsize = dp->di_size;
10627 	inodedep->id_savedextsize = dp->di_extsize;
10628 	inodedep->id_savednlink = dp->di_nlink;
10629 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10630 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10631 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10632 		return;
10633 	/*
10634 	 * Revert the link count to that of the first unwritten journal entry.
10635 	 */
10636 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10637 	if (inoref)
10638 		dp->di_nlink = inoref->if_nlink;
10639 
10640 	/*
10641 	 * Set the ext data dependencies to busy.
10642 	 */
10643 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10644 	     adp = TAILQ_NEXT(adp, ad_next)) {
10645 #ifdef INVARIANTS
10646 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10647 			panic("initiate_write_inodeblock_ufs2: lbn order");
10648 		prevlbn = adp->ad_offset;
10649 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10650 			panic("initiate_write_inodeblock_ufs2: "
10651 			    "ext pointer #%jd mismatch %jd != %jd",
10652 			    (intmax_t)adp->ad_offset,
10653 			    (intmax_t)dp->di_extb[adp->ad_offset],
10654 			    (intmax_t)adp->ad_newblkno);
10655 		deplist |= 1 << adp->ad_offset;
10656 		if ((adp->ad_state & ATTACHED) == 0)
10657 			panic("initiate_write_inodeblock_ufs2: Unknown "
10658 			    "state 0x%x", adp->ad_state);
10659 #endif /* INVARIANTS */
10660 		adp->ad_state &= ~ATTACHED;
10661 		adp->ad_state |= UNDONE;
10662 	}
10663 	/*
10664 	 * The on-disk inode cannot claim to be any larger than the last
10665 	 * fragment that has been written. Otherwise, the on-disk inode
10666 	 * might have fragments that were not the last block in the ext
10667 	 * data which would corrupt the filesystem.
10668 	 */
10669 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10670 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10671 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10672 		/* keep going until hitting a rollback to a frag */
10673 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10674 			continue;
10675 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10676 		for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10677 #ifdef INVARIANTS
10678 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10679 				panic("initiate_write_inodeblock_ufs2: "
10680 				    "lost dep1");
10681 #endif /* INVARIANTS */
10682 			dp->di_extb[i] = 0;
10683 		}
10684 		lastadp = NULL;
10685 		break;
10686 	}
10687 	/*
10688 	 * If we have zero'ed out the last allocated block of the ext
10689 	 * data, roll back the size to the last currently allocated block.
10690 	 * We know that this last allocated block is a full-sized as
10691 	 * we already checked for fragments in the loop above.
10692 	 */
10693 	if (lastadp != NULL &&
10694 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10695 		for (i = lastadp->ad_offset; i >= 0; i--)
10696 			if (dp->di_extb[i] != 0)
10697 				break;
10698 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10699 	}
10700 	/*
10701 	 * Set the file data dependencies to busy.
10702 	 */
10703 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10704 	     adp = TAILQ_NEXT(adp, ad_next)) {
10705 #ifdef INVARIANTS
10706 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10707 			panic("softdep_write_inodeblock: lbn order");
10708 		if ((adp->ad_state & ATTACHED) == 0)
10709 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10710 		prevlbn = adp->ad_offset;
10711 		if (!ffs_fsfail_cleanup(ump, 0) &&
10712 		    adp->ad_offset < UFS_NDADDR &&
10713 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10714 			panic("initiate_write_inodeblock_ufs2: "
10715 			    "direct pointer #%jd mismatch %jd != %jd",
10716 			    (intmax_t)adp->ad_offset,
10717 			    (intmax_t)dp->di_db[adp->ad_offset],
10718 			    (intmax_t)adp->ad_newblkno);
10719 		if (!ffs_fsfail_cleanup(ump, 0) &&
10720 		    adp->ad_offset >= UFS_NDADDR &&
10721 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10722 			panic("initiate_write_inodeblock_ufs2: "
10723 			    "indirect pointer #%jd mismatch %jd != %jd",
10724 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10725 			    (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10726 			    (intmax_t)adp->ad_newblkno);
10727 		deplist |= 1 << adp->ad_offset;
10728 		if ((adp->ad_state & ATTACHED) == 0)
10729 			panic("initiate_write_inodeblock_ufs2: Unknown "
10730 			     "state 0x%x", adp->ad_state);
10731 #endif /* INVARIANTS */
10732 		adp->ad_state &= ~ATTACHED;
10733 		adp->ad_state |= UNDONE;
10734 	}
10735 	/*
10736 	 * The on-disk inode cannot claim to be any larger than the last
10737 	 * fragment that has been written. Otherwise, the on-disk inode
10738 	 * might have fragments that were not the last block in the file
10739 	 * which would corrupt the filesystem.
10740 	 */
10741 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10742 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10743 		if (adp->ad_offset >= UFS_NDADDR)
10744 			break;
10745 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10746 		/* keep going until hitting a rollback to a frag */
10747 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10748 			continue;
10749 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10750 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10751 #ifdef INVARIANTS
10752 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10753 				panic("initiate_write_inodeblock_ufs2: "
10754 				    "lost dep2");
10755 #endif /* INVARIANTS */
10756 			dp->di_db[i] = 0;
10757 		}
10758 		for (i = 0; i < UFS_NIADDR; i++) {
10759 #ifdef INVARIANTS
10760 			if (dp->di_ib[i] != 0 &&
10761 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10762 				panic("initiate_write_inodeblock_ufs2: "
10763 				    "lost dep3");
10764 #endif /* INVARIANTS */
10765 			dp->di_ib[i] = 0;
10766 		}
10767 		ffs_update_dinode_ckhash(fs, dp);
10768 		return;
10769 	}
10770 	/*
10771 	 * If we have zero'ed out the last allocated block of the file,
10772 	 * roll back the size to the last currently allocated block.
10773 	 * We know that this last allocated block is a full-sized as
10774 	 * we already checked for fragments in the loop above.
10775 	 */
10776 	if (lastadp != NULL &&
10777 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10778 		for (i = lastadp->ad_offset; i >= 0; i--)
10779 			if (dp->di_db[i] != 0)
10780 				break;
10781 		dp->di_size = (i + 1) * fs->fs_bsize;
10782 	}
10783 	/*
10784 	 * The only dependencies are for indirect blocks.
10785 	 *
10786 	 * The file size for indirect block additions is not guaranteed.
10787 	 * Such a guarantee would be non-trivial to achieve. The conventional
10788 	 * synchronous write implementation also does not make this guarantee.
10789 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10790 	 * can be over-estimated without destroying integrity when the file
10791 	 * moves into the indirect blocks (i.e., is large). If we want to
10792 	 * postpone fsck, we are stuck with this argument.
10793 	 */
10794 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10795 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10796 	ffs_update_dinode_ckhash(fs, dp);
10797 }
10798 
10799 /*
10800  * Cancel an indirdep as a result of truncation.  Release all of the
10801  * children allocindirs and place their journal work on the appropriate
10802  * list.
10803  */
10804 static void
cancel_indirdep(struct indirdep * indirdep,struct buf * bp,struct freeblks * freeblks)10805 cancel_indirdep(
10806 	struct indirdep *indirdep,
10807 	struct buf *bp,
10808 	struct freeblks *freeblks)
10809 {
10810 	struct allocindir *aip;
10811 
10812 	/*
10813 	 * None of the indirect pointers will ever be visible,
10814 	 * so they can simply be tossed. GOINGAWAY ensures
10815 	 * that allocated pointers will be saved in the buffer
10816 	 * cache until they are freed. Note that they will
10817 	 * only be able to be found by their physical address
10818 	 * since the inode mapping the logical address will
10819 	 * be gone. The save buffer used for the safe copy
10820 	 * was allocated in setup_allocindir_phase2 using
10821 	 * the physical address so it could be used for this
10822 	 * purpose. Hence we swap the safe copy with the real
10823 	 * copy, allowing the safe copy to be freed and holding
10824 	 * on to the real copy for later use in indir_trunc.
10825 	 */
10826 	if (indirdep->ir_state & GOINGAWAY)
10827 		panic("cancel_indirdep: already gone");
10828 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10829 		indirdep->ir_state |= DEPCOMPLETE;
10830 		LIST_REMOVE(indirdep, ir_next);
10831 	}
10832 	indirdep->ir_state |= GOINGAWAY;
10833 	/*
10834 	 * Pass in bp for blocks still have journal writes
10835 	 * pending so we can cancel them on their own.
10836 	 */
10837 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10838 		cancel_allocindir(aip, bp, freeblks, 0);
10839 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10840 		cancel_allocindir(aip, NULL, freeblks, 0);
10841 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10842 		cancel_allocindir(aip, NULL, freeblks, 0);
10843 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10844 		cancel_allocindir(aip, NULL, freeblks, 0);
10845 	/*
10846 	 * If there are pending partial truncations we need to keep the
10847 	 * old block copy around until they complete.  This is because
10848 	 * the current b_data is not a perfect superset of the available
10849 	 * blocks.
10850 	 */
10851 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
10852 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10853 	else
10854 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10855 	WORKLIST_REMOVE(&indirdep->ir_list);
10856 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10857 	indirdep->ir_bp = NULL;
10858 	indirdep->ir_freeblks = freeblks;
10859 }
10860 
10861 /*
10862  * Free an indirdep once it no longer has new pointers to track.
10863  */
10864 static void
free_indirdep(struct indirdep * indirdep)10865 free_indirdep(struct indirdep *indirdep)
10866 {
10867 
10868 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10869 	    ("free_indirdep: Indir trunc list not empty."));
10870 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10871 	    ("free_indirdep: Complete head not empty."));
10872 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10873 	    ("free_indirdep: write head not empty."));
10874 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10875 	    ("free_indirdep: done head not empty."));
10876 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10877 	    ("free_indirdep: deplist head not empty."));
10878 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
10879 	    ("free_indirdep: %p still on newblk list.", indirdep));
10880 	KASSERT(indirdep->ir_saveddata == NULL,
10881 	    ("free_indirdep: %p still has saved data.", indirdep));
10882 	KASSERT(indirdep->ir_savebp == NULL,
10883 	    ("free_indirdep: %p still has savebp buffer.", indirdep));
10884 	if (indirdep->ir_state & ONWORKLIST)
10885 		WORKLIST_REMOVE(&indirdep->ir_list);
10886 	WORKITEM_FREE(indirdep, D_INDIRDEP);
10887 }
10888 
10889 /*
10890  * Called before a write to an indirdep.  This routine is responsible for
10891  * rolling back pointers to a safe state which includes only those
10892  * allocindirs which have been completed.
10893  */
10894 static void
initiate_write_indirdep(struct indirdep * indirdep,struct buf * bp)10895 initiate_write_indirdep(struct indirdep *indirdep, struct buf *bp)
10896 {
10897 	struct ufsmount *ump;
10898 
10899 	indirdep->ir_state |= IOSTARTED;
10900 	if (indirdep->ir_state & GOINGAWAY)
10901 		panic("disk_io_initiation: indirdep gone");
10902 	/*
10903 	 * If there are no remaining dependencies, this will be writing
10904 	 * the real pointers.
10905 	 */
10906 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10907 	    TAILQ_EMPTY(&indirdep->ir_trunc))
10908 		return;
10909 	/*
10910 	 * Replace up-to-date version with safe version.
10911 	 */
10912 	if (indirdep->ir_saveddata == NULL) {
10913 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10914 		LOCK_OWNED(ump);
10915 		FREE_LOCK(ump);
10916 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10917 		    M_SOFTDEP_FLAGS);
10918 		ACQUIRE_LOCK(ump);
10919 	}
10920 	indirdep->ir_state &= ~ATTACHED;
10921 	indirdep->ir_state |= UNDONE;
10922 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10923 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10924 	    bp->b_bcount);
10925 }
10926 
10927 /*
10928  * Called when an inode has been cleared in a cg bitmap.  This finally
10929  * eliminates any canceled jaddrefs
10930  */
10931 void
softdep_setup_inofree(struct mount * mp,struct buf * bp,ino_t ino,struct workhead * wkhd,bool doingrecovery)10932 softdep_setup_inofree(struct mount *mp,
10933 	struct buf *bp,
10934 	ino_t ino,
10935 	struct workhead *wkhd,
10936 	bool doingrecovery)
10937 {
10938 	struct worklist *wk, *wkn;
10939 	struct ufsmount *ump;
10940 #ifdef INVARIANTS
10941 	struct inodedep *inodedep;
10942 #endif
10943 
10944 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10945 	    ("softdep_setup_inofree called on non-softdep filesystem"));
10946 	ump = VFSTOUFS(mp);
10947 	ACQUIRE_LOCK(ump);
10948 	KASSERT(doingrecovery || ffs_fsfail_cleanup(ump, 0) ||
10949 	    isclr(cg_inosused((struct cg *)bp->b_data),
10950 	    ino % ump->um_fs->fs_ipg),
10951 	    ("softdep_setup_inofree: inode %ju not freed.", (uintmax_t)ino));
10952 	KASSERT(inodedep_lookup(mp, ino, 0, &inodedep) == 0,
10953 	    ("softdep_setup_inofree: ino %ju has existing inodedep %p",
10954 	    (uintmax_t)ino, inodedep));
10955 	if (wkhd) {
10956 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10957 			if (wk->wk_type != D_JADDREF)
10958 				continue;
10959 			WORKLIST_REMOVE(wk);
10960 			/*
10961 			 * We can free immediately even if the jaddref
10962 			 * isn't attached in a background write as now
10963 			 * the bitmaps are reconciled.
10964 			 */
10965 			wk->wk_state |= COMPLETE | ATTACHED;
10966 			free_jaddref(WK_JADDREF(wk));
10967 		}
10968 		jwork_move(&bp->b_dep, wkhd);
10969 	}
10970 	FREE_LOCK(ump);
10971 }
10972 
10973 /*
10974  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10975  * map.  Any dependencies waiting for the write to clear are added to the
10976  * buf's list and any jnewblks that are being canceled are discarded
10977  * immediately.
10978  */
10979 void
softdep_setup_blkfree(struct mount * mp,struct buf * bp,ufs2_daddr_t blkno,int frags,struct workhead * wkhd,bool doingrecovery)10980 softdep_setup_blkfree(
10981 	struct mount *mp,
10982 	struct buf *bp,
10983 	ufs2_daddr_t blkno,
10984 	int frags,
10985 	struct workhead *wkhd,
10986 	bool doingrecovery)
10987 {
10988 	struct bmsafemap *bmsafemap;
10989 	struct jnewblk *jnewblk;
10990 	struct ufsmount *ump;
10991 	struct worklist *wk;
10992 	struct fs *fs;
10993 #ifdef INVARIANTS
10994 	uint8_t *blksfree;
10995 	struct cg *cgp;
10996 	ufs2_daddr_t jstart;
10997 	ufs2_daddr_t jend;
10998 	ufs2_daddr_t end;
10999 	long bno;
11000 	int i;
11001 #endif
11002 
11003 	CTR3(KTR_SUJ,
11004 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
11005 	    blkno, frags, wkhd);
11006 
11007 	ump = VFSTOUFS(mp);
11008 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
11009 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
11010 	ACQUIRE_LOCK(ump);
11011 	/* Lookup the bmsafemap so we track when it is dirty. */
11012 	fs = ump->um_fs;
11013 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
11014 	/*
11015 	 * Detach any jnewblks which have been canceled.  They must linger
11016 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
11017 	 * an unjournaled allocation from hitting the disk.
11018 	 */
11019 	if (wkhd) {
11020 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
11021 			CTR2(KTR_SUJ,
11022 			    "softdep_setup_blkfree: blkno %jd wk type %d",
11023 			    blkno, wk->wk_type);
11024 			WORKLIST_REMOVE(wk);
11025 			if (wk->wk_type != D_JNEWBLK) {
11026 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
11027 				continue;
11028 			}
11029 			jnewblk = WK_JNEWBLK(wk);
11030 			KASSERT(jnewblk->jn_state & GOINGAWAY,
11031 			    ("softdep_setup_blkfree: jnewblk not canceled."));
11032 #ifdef INVARIANTS
11033 			if (!doingrecovery && !ffs_fsfail_cleanup(ump, 0)) {
11034 				/*
11035 				 * Assert that this block is free in the
11036 				 * bitmap before we discard the jnewblk.
11037 				 */
11038 				cgp = (struct cg *)bp->b_data;
11039 				blksfree = cg_blksfree(cgp);
11040 				bno = dtogd(fs, jnewblk->jn_blkno);
11041 				for (i = jnewblk->jn_oldfrags;
11042 				    i < jnewblk->jn_frags; i++) {
11043 					if (isset(blksfree, bno + i))
11044 						continue;
11045 					panic("softdep_setup_blkfree: block "
11046 					    "%ju not freed.",
11047 					    (uintmax_t)jnewblk->jn_blkno);
11048 				}
11049 			}
11050 #endif
11051 			/*
11052 			 * Even if it's not attached we can free immediately
11053 			 * as the new bitmap is correct.
11054 			 */
11055 			wk->wk_state |= COMPLETE | ATTACHED;
11056 			free_jnewblk(jnewblk);
11057 		}
11058 	}
11059 
11060 #ifdef INVARIANTS
11061 	/*
11062 	 * Assert that we are not freeing a block which has an outstanding
11063 	 * allocation dependency.
11064 	 */
11065 	fs = VFSTOUFS(mp)->um_fs;
11066 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
11067 	end = blkno + frags;
11068 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11069 		/*
11070 		 * Don't match against blocks that will be freed when the
11071 		 * background write is done.
11072 		 */
11073 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
11074 		    (COMPLETE | DEPCOMPLETE))
11075 			continue;
11076 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
11077 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
11078 		if ((blkno >= jstart && blkno < jend) ||
11079 		    (end > jstart && end <= jend)) {
11080 			printf("state 0x%X %jd - %d %d dep %p\n",
11081 			    jnewblk->jn_state, jnewblk->jn_blkno,
11082 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
11083 			    jnewblk->jn_dep);
11084 			panic("softdep_setup_blkfree: "
11085 			    "%jd-%jd(%d) overlaps with %jd-%jd",
11086 			    blkno, end, frags, jstart, jend);
11087 		}
11088 	}
11089 #endif
11090 	FREE_LOCK(ump);
11091 }
11092 
11093 /*
11094  * Revert a block allocation when the journal record that describes it
11095  * is not yet written.
11096  */
11097 static int
jnewblk_rollback(struct jnewblk * jnewblk,struct fs * fs,struct cg * cgp,uint8_t * blksfree)11098 jnewblk_rollback(
11099 	struct jnewblk *jnewblk,
11100 	struct fs *fs,
11101 	struct cg *cgp,
11102 	uint8_t *blksfree)
11103 {
11104 	ufs1_daddr_t fragno;
11105 	long cgbno, bbase;
11106 	int frags, blk;
11107 	int i;
11108 
11109 	frags = 0;
11110 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11111 	/*
11112 	 * We have to test which frags need to be rolled back.  We may
11113 	 * be operating on a stale copy when doing background writes.
11114 	 */
11115 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
11116 		if (isclr(blksfree, cgbno + i))
11117 			frags++;
11118 	if (frags == 0)
11119 		return (0);
11120 	/*
11121 	 * This is mostly ffs_blkfree() sans some validation and
11122 	 * superblock updates.
11123 	 */
11124 	if (frags == fs->fs_frag) {
11125 		fragno = fragstoblks(fs, cgbno);
11126 		ffs_setblock(fs, blksfree, fragno);
11127 		ffs_clusteracct(fs, cgp, fragno, 1);
11128 		cgp->cg_cs.cs_nbfree++;
11129 	} else {
11130 		cgbno += jnewblk->jn_oldfrags;
11131 		bbase = cgbno - fragnum(fs, cgbno);
11132 		/* Decrement the old frags.  */
11133 		blk = blkmap(fs, blksfree, bbase);
11134 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11135 		/* Deallocate the fragment */
11136 		for (i = 0; i < frags; i++)
11137 			setbit(blksfree, cgbno + i);
11138 		cgp->cg_cs.cs_nffree += frags;
11139 		/* Add back in counts associated with the new frags */
11140 		blk = blkmap(fs, blksfree, bbase);
11141 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11142 		/* If a complete block has been reassembled, account for it. */
11143 		fragno = fragstoblks(fs, bbase);
11144 		if (ffs_isblock(fs, blksfree, fragno)) {
11145 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
11146 			ffs_clusteracct(fs, cgp, fragno, 1);
11147 			cgp->cg_cs.cs_nbfree++;
11148 		}
11149 	}
11150 	stat_jnewblk++;
11151 	jnewblk->jn_state &= ~ATTACHED;
11152 	jnewblk->jn_state |= UNDONE;
11153 
11154 	return (frags);
11155 }
11156 
11157 static void
initiate_write_bmsafemap(struct bmsafemap * bmsafemap,struct buf * bp)11158 initiate_write_bmsafemap(
11159 	struct bmsafemap *bmsafemap,
11160 	struct buf *bp)			/* The cg block. */
11161 {
11162 	struct jaddref *jaddref;
11163 	struct jnewblk *jnewblk;
11164 	uint8_t *inosused;
11165 	uint8_t *blksfree;
11166 	struct cg *cgp;
11167 	struct fs *fs;
11168 	ino_t ino;
11169 
11170 	/*
11171 	 * If this is a background write, we did this at the time that
11172 	 * the copy was made, so do not need to do it again.
11173 	 */
11174 	if (bmsafemap->sm_state & IOSTARTED)
11175 		return;
11176 	bmsafemap->sm_state |= IOSTARTED;
11177 	/*
11178 	 * Clear any inode allocations which are pending journal writes.
11179 	 */
11180 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
11181 		cgp = (struct cg *)bp->b_data;
11182 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11183 		inosused = cg_inosused(cgp);
11184 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
11185 			ino = jaddref->ja_ino % fs->fs_ipg;
11186 			if (isset(inosused, ino)) {
11187 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11188 					cgp->cg_cs.cs_ndir--;
11189 				cgp->cg_cs.cs_nifree++;
11190 				clrbit(inosused, ino);
11191 				jaddref->ja_state &= ~ATTACHED;
11192 				jaddref->ja_state |= UNDONE;
11193 				stat_jaddref++;
11194 			} else
11195 				panic("initiate_write_bmsafemap: inode %ju "
11196 				    "marked free", (uintmax_t)jaddref->ja_ino);
11197 		}
11198 	}
11199 	/*
11200 	 * Clear any block allocations which are pending journal writes.
11201 	 */
11202 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11203 		cgp = (struct cg *)bp->b_data;
11204 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11205 		blksfree = cg_blksfree(cgp);
11206 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11207 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
11208 				continue;
11209 			panic("initiate_write_bmsafemap: block %jd "
11210 			    "marked free", jnewblk->jn_blkno);
11211 		}
11212 	}
11213 	/*
11214 	 * Move allocation lists to the written lists so they can be
11215 	 * cleared once the block write is complete.
11216 	 */
11217 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
11218 	    inodedep, id_deps);
11219 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11220 	    newblk, nb_deps);
11221 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11222 	    wk_list);
11223 }
11224 
11225 void
softdep_handle_error(struct buf * bp)11226 softdep_handle_error(struct buf *bp)
11227 {
11228 	struct ufsmount *ump;
11229 
11230 	ump = softdep_bp_to_mp(bp);
11231 	if (ump == NULL)
11232 		return;
11233 
11234 	if (ffs_fsfail_cleanup(ump, bp->b_error)) {
11235 		/*
11236 		 * No future writes will succeed, so the on-disk image is safe.
11237 		 * Pretend that this write succeeded so that the softdep state
11238 		 * will be cleaned up naturally.
11239 		 */
11240 		bp->b_ioflags &= ~BIO_ERROR;
11241 		bp->b_error = 0;
11242 	}
11243 }
11244 
11245 /*
11246  * This routine is called during the completion interrupt
11247  * service routine for a disk write (from the procedure called
11248  * by the device driver to inform the filesystem caches of
11249  * a request completion).  It should be called early in this
11250  * procedure, before the block is made available to other
11251  * processes or other routines are called.
11252  *
11253  */
11254 static void
softdep_disk_write_complete(struct buf * bp)11255 softdep_disk_write_complete(
11256 	struct buf *bp)		/* describes the completed disk write */
11257 {
11258 	struct worklist *wk;
11259 	struct worklist *owk;
11260 	struct ufsmount *ump;
11261 	struct workhead reattach;
11262 	struct freeblks *freeblks;
11263 	struct buf *sbp;
11264 
11265 	ump = softdep_bp_to_mp(bp);
11266 	KASSERT(LIST_EMPTY(&bp->b_dep) || ump != NULL,
11267 	    ("softdep_disk_write_complete: softdep_bp_to_mp returned NULL "
11268 	     "with outstanding dependencies for buffer %p", bp));
11269 	if (ump == NULL)
11270 		return;
11271 	if ((bp->b_ioflags & BIO_ERROR) != 0)
11272 		softdep_handle_error(bp);
11273 	/*
11274 	 * If an error occurred while doing the write, then the data
11275 	 * has not hit the disk and the dependencies cannot be processed.
11276 	 * But we do have to go through and roll forward any dependencies
11277 	 * that were rolled back before the disk write.
11278 	 */
11279 	sbp = NULL;
11280 	ACQUIRE_LOCK(ump);
11281 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11282 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11283 			switch (wk->wk_type) {
11284 			case D_PAGEDEP:
11285 				handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11286 				continue;
11287 
11288 			case D_INODEDEP:
11289 				handle_written_inodeblock(WK_INODEDEP(wk),
11290 				    bp, 0);
11291 				continue;
11292 
11293 			case D_BMSAFEMAP:
11294 				handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11295 				    bp, 0);
11296 				continue;
11297 
11298 			case D_INDIRDEP:
11299 				handle_written_indirdep(WK_INDIRDEP(wk),
11300 				    bp, &sbp, 0);
11301 				continue;
11302 			default:
11303 				/* nothing to roll forward */
11304 				continue;
11305 			}
11306 		}
11307 		FREE_LOCK(ump);
11308 		if (sbp)
11309 			brelse(sbp);
11310 		return;
11311 	}
11312 	LIST_INIT(&reattach);
11313 
11314 	/*
11315 	 * Ump SU lock must not be released anywhere in this code segment.
11316 	 */
11317 	owk = NULL;
11318 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11319 		WORKLIST_REMOVE(wk);
11320 		atomic_add_long(&dep_write[wk->wk_type], 1);
11321 		if (wk == owk)
11322 			panic("duplicate worklist: %p\n", wk);
11323 		owk = wk;
11324 		switch (wk->wk_type) {
11325 		case D_PAGEDEP:
11326 			if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11327 			    WRITESUCCEEDED))
11328 				WORKLIST_INSERT(&reattach, wk);
11329 			continue;
11330 
11331 		case D_INODEDEP:
11332 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11333 			    WRITESUCCEEDED))
11334 				WORKLIST_INSERT(&reattach, wk);
11335 			continue;
11336 
11337 		case D_BMSAFEMAP:
11338 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11339 			    WRITESUCCEEDED))
11340 				WORKLIST_INSERT(&reattach, wk);
11341 			continue;
11342 
11343 		case D_MKDIR:
11344 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11345 			continue;
11346 
11347 		case D_ALLOCDIRECT:
11348 			wk->wk_state |= COMPLETE;
11349 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11350 			continue;
11351 
11352 		case D_ALLOCINDIR:
11353 			wk->wk_state |= COMPLETE;
11354 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11355 			continue;
11356 
11357 		case D_INDIRDEP:
11358 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11359 			    WRITESUCCEEDED))
11360 				WORKLIST_INSERT(&reattach, wk);
11361 			continue;
11362 
11363 		case D_FREEBLKS:
11364 			wk->wk_state |= COMPLETE;
11365 			freeblks = WK_FREEBLKS(wk);
11366 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11367 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11368 				add_to_worklist(wk, WK_NODELAY);
11369 			continue;
11370 
11371 		case D_FREEWORK:
11372 			handle_written_freework(WK_FREEWORK(wk));
11373 			break;
11374 
11375 		case D_JSEGDEP:
11376 			free_jsegdep(WK_JSEGDEP(wk));
11377 			continue;
11378 
11379 		case D_JSEG:
11380 			handle_written_jseg(WK_JSEG(wk), bp);
11381 			continue;
11382 
11383 		case D_SBDEP:
11384 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11385 				WORKLIST_INSERT(&reattach, wk);
11386 			continue;
11387 
11388 		case D_FREEDEP:
11389 			free_freedep(WK_FREEDEP(wk));
11390 			continue;
11391 
11392 		default:
11393 			panic("handle_disk_write_complete: Unknown type %s",
11394 			    TYPENAME(wk->wk_type));
11395 			/* NOTREACHED */
11396 		}
11397 	}
11398 	/*
11399 	 * Reattach any requests that must be redone.
11400 	 */
11401 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11402 		WORKLIST_REMOVE(wk);
11403 		WORKLIST_INSERT(&bp->b_dep, wk);
11404 	}
11405 	FREE_LOCK(ump);
11406 	if (sbp)
11407 		brelse(sbp);
11408 }
11409 
11410 /*
11411  * Called from within softdep_disk_write_complete above.
11412  */
11413 static void
handle_allocdirect_partdone(struct allocdirect * adp,struct workhead * wkhd)11414 handle_allocdirect_partdone(
11415 	struct allocdirect *adp,	/* the completed allocdirect */
11416 	struct workhead *wkhd)		/* Work to do when inode is writtne. */
11417 {
11418 	struct allocdirectlst *listhead;
11419 	struct allocdirect *listadp;
11420 	struct inodedep *inodedep;
11421 	long bsize;
11422 
11423 	LOCK_OWNED(VFSTOUFS(adp->ad_block.nb_list.wk_mp));
11424 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11425 		return;
11426 	/*
11427 	 * The on-disk inode cannot claim to be any larger than the last
11428 	 * fragment that has been written. Otherwise, the on-disk inode
11429 	 * might have fragments that were not the last block in the file
11430 	 * which would corrupt the filesystem. Thus, we cannot free any
11431 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11432 	 * these blocks must be rolled back to zero before writing the inode.
11433 	 * We check the currently active set of allocdirects in id_inoupdt
11434 	 * or id_extupdt as appropriate.
11435 	 */
11436 	inodedep = adp->ad_inodedep;
11437 	bsize = inodedep->id_fs->fs_bsize;
11438 	if (adp->ad_state & EXTDATA)
11439 		listhead = &inodedep->id_extupdt;
11440 	else
11441 		listhead = &inodedep->id_inoupdt;
11442 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11443 		/* found our block */
11444 		if (listadp == adp)
11445 			break;
11446 		/* continue if ad_oldlbn is not a fragment */
11447 		if (listadp->ad_oldsize == 0 ||
11448 		    listadp->ad_oldsize == bsize)
11449 			continue;
11450 		/* hit a fragment */
11451 		return;
11452 	}
11453 	/*
11454 	 * If we have reached the end of the current list without
11455 	 * finding the just finished dependency, then it must be
11456 	 * on the future dependency list. Future dependencies cannot
11457 	 * be freed until they are moved to the current list.
11458 	 */
11459 	if (listadp == NULL) {
11460 #ifdef INVARIANTS
11461 		if (adp->ad_state & EXTDATA)
11462 			listhead = &inodedep->id_newextupdt;
11463 		else
11464 			listhead = &inodedep->id_newinoupdt;
11465 		TAILQ_FOREACH(listadp, listhead, ad_next)
11466 			/* found our block */
11467 			if (listadp == adp)
11468 				break;
11469 		if (listadp == NULL)
11470 			panic("handle_allocdirect_partdone: lost dep");
11471 #endif /* INVARIANTS */
11472 		return;
11473 	}
11474 	/*
11475 	 * If we have found the just finished dependency, then queue
11476 	 * it along with anything that follows it that is complete.
11477 	 * Since the pointer has not yet been written in the inode
11478 	 * as the dependency prevents it, place the allocdirect on the
11479 	 * bufwait list where it will be freed once the pointer is
11480 	 * valid.
11481 	 */
11482 	if (wkhd == NULL)
11483 		wkhd = &inodedep->id_bufwait;
11484 	for (; adp; adp = listadp) {
11485 		listadp = TAILQ_NEXT(adp, ad_next);
11486 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11487 			return;
11488 		TAILQ_REMOVE(listhead, adp, ad_next);
11489 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11490 	}
11491 }
11492 
11493 /*
11494  * Called from within softdep_disk_write_complete above.  This routine
11495  * completes successfully written allocindirs.
11496  */
11497 static void
handle_allocindir_partdone(struct allocindir * aip)11498 handle_allocindir_partdone(
11499 	struct allocindir *aip)		/* the completed allocindir */
11500 {
11501 	struct indirdep *indirdep;
11502 
11503 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11504 		return;
11505 	indirdep = aip->ai_indirdep;
11506 	LIST_REMOVE(aip, ai_next);
11507 	/*
11508 	 * Don't set a pointer while the buffer is undergoing IO or while
11509 	 * we have active truncations.
11510 	 */
11511 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11512 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11513 		return;
11514 	}
11515 	if (indirdep->ir_state & UFS1FMT)
11516 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11517 		    aip->ai_newblkno;
11518 	else
11519 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11520 		    aip->ai_newblkno;
11521 	/*
11522 	 * Await the pointer write before freeing the allocindir.
11523 	 */
11524 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11525 }
11526 
11527 /*
11528  * Release segments held on a jwork list.
11529  */
11530 static void
handle_jwork(struct workhead * wkhd)11531 handle_jwork(struct workhead *wkhd)
11532 {
11533 	struct worklist *wk;
11534 
11535 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11536 		WORKLIST_REMOVE(wk);
11537 		switch (wk->wk_type) {
11538 		case D_JSEGDEP:
11539 			free_jsegdep(WK_JSEGDEP(wk));
11540 			continue;
11541 		case D_FREEDEP:
11542 			free_freedep(WK_FREEDEP(wk));
11543 			continue;
11544 		case D_FREEFRAG:
11545 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11546 			WORKITEM_FREE(wk, D_FREEFRAG);
11547 			continue;
11548 		case D_FREEWORK:
11549 			handle_written_freework(WK_FREEWORK(wk));
11550 			continue;
11551 		default:
11552 			panic("handle_jwork: Unknown type %s\n",
11553 			    TYPENAME(wk->wk_type));
11554 		}
11555 	}
11556 }
11557 
11558 /*
11559  * Handle the bufwait list on an inode when it is safe to release items
11560  * held there.  This normally happens after an inode block is written but
11561  * may be delayed and handled later if there are pending journal items that
11562  * are not yet safe to be released.
11563  */
11564 static struct freefile *
handle_bufwait(struct inodedep * inodedep,struct workhead * refhd)11565 handle_bufwait(
11566 	struct inodedep *inodedep,
11567 	struct workhead *refhd)
11568 {
11569 	struct jaddref *jaddref;
11570 	struct freefile *freefile;
11571 	struct worklist *wk;
11572 
11573 	freefile = NULL;
11574 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11575 		WORKLIST_REMOVE(wk);
11576 		switch (wk->wk_type) {
11577 		case D_FREEFILE:
11578 			/*
11579 			 * We defer adding freefile to the worklist
11580 			 * until all other additions have been made to
11581 			 * ensure that it will be done after all the
11582 			 * old blocks have been freed.
11583 			 */
11584 			if (freefile != NULL)
11585 				panic("handle_bufwait: freefile");
11586 			freefile = WK_FREEFILE(wk);
11587 			continue;
11588 
11589 		case D_MKDIR:
11590 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11591 			continue;
11592 
11593 		case D_DIRADD:
11594 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11595 			continue;
11596 
11597 		case D_FREEFRAG:
11598 			wk->wk_state |= COMPLETE;
11599 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11600 				add_to_worklist(wk, 0);
11601 			continue;
11602 
11603 		case D_DIRREM:
11604 			wk->wk_state |= COMPLETE;
11605 			add_to_worklist(wk, 0);
11606 			continue;
11607 
11608 		case D_ALLOCDIRECT:
11609 		case D_ALLOCINDIR:
11610 			free_newblk(WK_NEWBLK(wk));
11611 			continue;
11612 
11613 		case D_JNEWBLK:
11614 			wk->wk_state |= COMPLETE;
11615 			free_jnewblk(WK_JNEWBLK(wk));
11616 			continue;
11617 
11618 		/*
11619 		 * Save freed journal segments and add references on
11620 		 * the supplied list which will delay their release
11621 		 * until the cg bitmap is cleared on disk.
11622 		 */
11623 		case D_JSEGDEP:
11624 			if (refhd == NULL)
11625 				free_jsegdep(WK_JSEGDEP(wk));
11626 			else
11627 				WORKLIST_INSERT(refhd, wk);
11628 			continue;
11629 
11630 		case D_JADDREF:
11631 			jaddref = WK_JADDREF(wk);
11632 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11633 			    if_deps);
11634 			/*
11635 			 * Transfer any jaddrefs to the list to be freed with
11636 			 * the bitmap if we're handling a removed file.
11637 			 */
11638 			if (refhd == NULL) {
11639 				wk->wk_state |= COMPLETE;
11640 				free_jaddref(jaddref);
11641 			} else
11642 				WORKLIST_INSERT(refhd, wk);
11643 			continue;
11644 
11645 		default:
11646 			panic("handle_bufwait: Unknown type %p(%s)",
11647 			    wk, TYPENAME(wk->wk_type));
11648 			/* NOTREACHED */
11649 		}
11650 	}
11651 	return (freefile);
11652 }
11653 /*
11654  * Called from within softdep_disk_write_complete above to restore
11655  * in-memory inode block contents to their most up-to-date state. Note
11656  * that this routine is always called from interrupt level with further
11657  * interrupts from this device blocked.
11658  *
11659  * If the write did not succeed, we will do all the roll-forward
11660  * operations, but we will not take the actions that will allow its
11661  * dependencies to be processed.
11662  */
11663 static int
handle_written_inodeblock(struct inodedep * inodedep,struct buf * bp,int flags)11664 handle_written_inodeblock(
11665 	struct inodedep *inodedep,
11666 	struct buf *bp,		/* buffer containing the inode block */
11667 	int flags)
11668 {
11669 	struct freefile *freefile;
11670 	struct allocdirect *adp, *nextadp;
11671 	struct ufs1_dinode *dp1 = NULL;
11672 	struct ufs2_dinode *dp2 = NULL;
11673 	struct workhead wkhd;
11674 	int hadchanges, fstype;
11675 	ino_t freelink;
11676 
11677 	LIST_INIT(&wkhd);
11678 	hadchanges = 0;
11679 	freefile = NULL;
11680 	if ((inodedep->id_state & IOSTARTED) == 0)
11681 		panic("handle_written_inodeblock: not started");
11682 	inodedep->id_state &= ~IOSTARTED;
11683 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11684 		fstype = UFS1;
11685 		dp1 = (struct ufs1_dinode *)bp->b_data +
11686 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11687 		freelink = dp1->di_freelink;
11688 	} else {
11689 		fstype = UFS2;
11690 		dp2 = (struct ufs2_dinode *)bp->b_data +
11691 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11692 		freelink = dp2->di_freelink;
11693 	}
11694 	/*
11695 	 * Leave this inodeblock dirty until it's in the list.
11696 	 */
11697 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11698 	    (flags & WRITESUCCEEDED)) {
11699 		struct inodedep *inon;
11700 
11701 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11702 		if ((inon == NULL && freelink == 0) ||
11703 		    (inon && inon->id_ino == freelink)) {
11704 			if (inon)
11705 				inon->id_state |= UNLINKPREV;
11706 			inodedep->id_state |= UNLINKNEXT;
11707 		}
11708 		hadchanges = 1;
11709 	}
11710 	/*
11711 	 * If we had to rollback the inode allocation because of
11712 	 * bitmaps being incomplete, then simply restore it.
11713 	 * Keep the block dirty so that it will not be reclaimed until
11714 	 * all associated dependencies have been cleared and the
11715 	 * corresponding updates written to disk.
11716 	 */
11717 	if (inodedep->id_savedino1 != NULL) {
11718 		hadchanges = 1;
11719 		if (fstype == UFS1)
11720 			*dp1 = *inodedep->id_savedino1;
11721 		else
11722 			*dp2 = *inodedep->id_savedino2;
11723 		free(inodedep->id_savedino1, M_SAVEDINO);
11724 		inodedep->id_savedino1 = NULL;
11725 		if ((bp->b_flags & B_DELWRI) == 0)
11726 			stat_inode_bitmap++;
11727 		bdirty(bp);
11728 		/*
11729 		 * If the inode is clear here and GOINGAWAY it will never
11730 		 * be written.  Process the bufwait and clear any pending
11731 		 * work which may include the freefile.
11732 		 */
11733 		if (inodedep->id_state & GOINGAWAY)
11734 			goto bufwait;
11735 		return (1);
11736 	}
11737 	if (flags & WRITESUCCEEDED)
11738 		inodedep->id_state |= COMPLETE;
11739 	/*
11740 	 * Roll forward anything that had to be rolled back before
11741 	 * the inode could be updated.
11742 	 */
11743 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11744 		nextadp = TAILQ_NEXT(adp, ad_next);
11745 		if (adp->ad_state & ATTACHED)
11746 			panic("handle_written_inodeblock: new entry");
11747 		if (fstype == UFS1) {
11748 			if (adp->ad_offset < UFS_NDADDR) {
11749 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11750 					panic("%s %s #%jd mismatch %d != %jd",
11751 					    "handle_written_inodeblock:",
11752 					    "direct pointer",
11753 					    (intmax_t)adp->ad_offset,
11754 					    dp1->di_db[adp->ad_offset],
11755 					    (intmax_t)adp->ad_oldblkno);
11756 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11757 			} else {
11758 				if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11759 				    0)
11760 					panic("%s: %s #%jd allocated as %d",
11761 					    "handle_written_inodeblock",
11762 					    "indirect pointer",
11763 					    (intmax_t)adp->ad_offset -
11764 					    UFS_NDADDR,
11765 					    dp1->di_ib[adp->ad_offset -
11766 					    UFS_NDADDR]);
11767 				dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11768 				    adp->ad_newblkno;
11769 			}
11770 		} else {
11771 			if (adp->ad_offset < UFS_NDADDR) {
11772 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11773 					panic("%s: %s #%jd %s %jd != %jd",
11774 					    "handle_written_inodeblock",
11775 					    "direct pointer",
11776 					    (intmax_t)adp->ad_offset, "mismatch",
11777 					    (intmax_t)dp2->di_db[adp->ad_offset],
11778 					    (intmax_t)adp->ad_oldblkno);
11779 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11780 			} else {
11781 				if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11782 				    0)
11783 					panic("%s: %s #%jd allocated as %jd",
11784 					    "handle_written_inodeblock",
11785 					    "indirect pointer",
11786 					    (intmax_t)adp->ad_offset -
11787 					    UFS_NDADDR,
11788 					    (intmax_t)
11789 					    dp2->di_ib[adp->ad_offset -
11790 					    UFS_NDADDR]);
11791 				dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11792 				    adp->ad_newblkno;
11793 			}
11794 		}
11795 		adp->ad_state &= ~UNDONE;
11796 		adp->ad_state |= ATTACHED;
11797 		hadchanges = 1;
11798 	}
11799 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11800 		nextadp = TAILQ_NEXT(adp, ad_next);
11801 		if (adp->ad_state & ATTACHED)
11802 			panic("handle_written_inodeblock: new entry");
11803 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11804 			panic("%s: direct pointers #%jd %s %jd != %jd",
11805 			    "handle_written_inodeblock",
11806 			    (intmax_t)adp->ad_offset, "mismatch",
11807 			    (intmax_t)dp2->di_extb[adp->ad_offset],
11808 			    (intmax_t)adp->ad_oldblkno);
11809 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11810 		adp->ad_state &= ~UNDONE;
11811 		adp->ad_state |= ATTACHED;
11812 		hadchanges = 1;
11813 	}
11814 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11815 		stat_direct_blk_ptrs++;
11816 	/*
11817 	 * Reset the file size to its most up-to-date value.
11818 	 */
11819 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11820 		panic("handle_written_inodeblock: bad size");
11821 	if (inodedep->id_savednlink > UFS_LINK_MAX)
11822 		panic("handle_written_inodeblock: Invalid link count "
11823 		    "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11824 		    inodedep);
11825 	if (fstype == UFS1) {
11826 		if (dp1->di_nlink != inodedep->id_savednlink) {
11827 			dp1->di_nlink = inodedep->id_savednlink;
11828 			hadchanges = 1;
11829 		}
11830 		if (dp1->di_size != inodedep->id_savedsize) {
11831 			dp1->di_size = inodedep->id_savedsize;
11832 			hadchanges = 1;
11833 		}
11834 	} else {
11835 		if (dp2->di_nlink != inodedep->id_savednlink) {
11836 			dp2->di_nlink = inodedep->id_savednlink;
11837 			hadchanges = 1;
11838 		}
11839 		if (dp2->di_size != inodedep->id_savedsize) {
11840 			dp2->di_size = inodedep->id_savedsize;
11841 			hadchanges = 1;
11842 		}
11843 		if (dp2->di_extsize != inodedep->id_savedextsize) {
11844 			dp2->di_extsize = inodedep->id_savedextsize;
11845 			hadchanges = 1;
11846 		}
11847 	}
11848 	inodedep->id_savedsize = -1;
11849 	inodedep->id_savedextsize = -1;
11850 	inodedep->id_savednlink = -1;
11851 	/*
11852 	 * If there were any rollbacks in the inode block, then it must be
11853 	 * marked dirty so that its will eventually get written back in
11854 	 * its correct form.
11855 	 */
11856 	if (hadchanges) {
11857 		if (fstype == UFS2)
11858 			ffs_update_dinode_ckhash(inodedep->id_fs, dp2);
11859 		bdirty(bp);
11860 	}
11861 bufwait:
11862 	/*
11863 	 * If the write did not succeed, we have done all the roll-forward
11864 	 * operations, but we cannot take the actions that will allow its
11865 	 * dependencies to be processed.
11866 	 */
11867 	if ((flags & WRITESUCCEEDED) == 0)
11868 		return (hadchanges);
11869 	/*
11870 	 * Process any allocdirects that completed during the update.
11871 	 */
11872 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11873 		handle_allocdirect_partdone(adp, &wkhd);
11874 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11875 		handle_allocdirect_partdone(adp, &wkhd);
11876 	/*
11877 	 * Process deallocations that were held pending until the
11878 	 * inode had been written to disk. Freeing of the inode
11879 	 * is delayed until after all blocks have been freed to
11880 	 * avoid creation of new <vfsid, inum, lbn> triples
11881 	 * before the old ones have been deleted.  Completely
11882 	 * unlinked inodes are not processed until the unlinked
11883 	 * inode list is written or the last reference is removed.
11884 	 */
11885 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11886 		freefile = handle_bufwait(inodedep, NULL);
11887 		if (freefile && !LIST_EMPTY(&wkhd)) {
11888 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11889 			freefile = NULL;
11890 		}
11891 	}
11892 	/*
11893 	 * Move rolled forward dependency completions to the bufwait list
11894 	 * now that those that were already written have been processed.
11895 	 */
11896 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11897 		panic("handle_written_inodeblock: bufwait but no changes");
11898 	jwork_move(&inodedep->id_bufwait, &wkhd);
11899 
11900 	if (freefile != NULL) {
11901 		/*
11902 		 * If the inode is goingaway it was never written.  Fake up
11903 		 * the state here so free_inodedep() can succeed.
11904 		 */
11905 		if (inodedep->id_state & GOINGAWAY)
11906 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11907 		if (free_inodedep(inodedep) == 0)
11908 			panic("handle_written_inodeblock: live inodedep %p",
11909 			    inodedep);
11910 		add_to_worklist(&freefile->fx_list, 0);
11911 		return (0);
11912 	}
11913 
11914 	/*
11915 	 * If no outstanding dependencies, free it.
11916 	 */
11917 	if (free_inodedep(inodedep) ||
11918 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11919 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11920 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11921 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
11922 		return (0);
11923 	return (hadchanges);
11924 }
11925 
11926 /*
11927  * Perform needed roll-forwards and kick off any dependencies that
11928  * can now be processed.
11929  *
11930  * If the write did not succeed, we will do all the roll-forward
11931  * operations, but we will not take the actions that will allow its
11932  * dependencies to be processed.
11933  */
11934 static int
handle_written_indirdep(struct indirdep * indirdep,struct buf * bp,struct buf ** bpp,int flags)11935 handle_written_indirdep(
11936 	struct indirdep *indirdep,
11937 	struct buf *bp,
11938 	struct buf **bpp,
11939 	int flags)
11940 {
11941 	struct allocindir *aip;
11942 	struct buf *sbp;
11943 	int chgs;
11944 
11945 	if (indirdep->ir_state & GOINGAWAY)
11946 		panic("handle_written_indirdep: indirdep gone");
11947 	if ((indirdep->ir_state & IOSTARTED) == 0)
11948 		panic("handle_written_indirdep: IO not started");
11949 	chgs = 0;
11950 	/*
11951 	 * If there were rollbacks revert them here.
11952 	 */
11953 	if (indirdep->ir_saveddata) {
11954 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11955 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11956 			free(indirdep->ir_saveddata, M_INDIRDEP);
11957 			indirdep->ir_saveddata = NULL;
11958 		}
11959 		chgs = 1;
11960 	}
11961 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11962 	indirdep->ir_state |= ATTACHED;
11963 	/*
11964 	 * If the write did not succeed, we have done all the roll-forward
11965 	 * operations, but we cannot take the actions that will allow its
11966 	 * dependencies to be processed.
11967 	 */
11968 	if ((flags & WRITESUCCEEDED) == 0) {
11969 		stat_indir_blk_ptrs++;
11970 		bdirty(bp);
11971 		return (1);
11972 	}
11973 	/*
11974 	 * Move allocindirs with written pointers to the completehd if
11975 	 * the indirdep's pointer is not yet written.  Otherwise
11976 	 * free them here.
11977 	 */
11978 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11979 		LIST_REMOVE(aip, ai_next);
11980 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11981 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11982 			    ai_next);
11983 			newblk_freefrag(&aip->ai_block);
11984 			continue;
11985 		}
11986 		free_newblk(&aip->ai_block);
11987 	}
11988 	/*
11989 	 * Move allocindirs that have finished dependency processing from
11990 	 * the done list to the write list after updating the pointers.
11991 	 */
11992 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11993 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11994 			handle_allocindir_partdone(aip);
11995 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
11996 				panic("disk_write_complete: not gone");
11997 			chgs = 1;
11998 		}
11999 	}
12000 	/*
12001 	 * Preserve the indirdep if there were any changes or if it is not
12002 	 * yet valid on disk.
12003 	 */
12004 	if (chgs) {
12005 		stat_indir_blk_ptrs++;
12006 		bdirty(bp);
12007 		return (1);
12008 	}
12009 	/*
12010 	 * If there were no changes we can discard the savedbp and detach
12011 	 * ourselves from the buf.  We are only carrying completed pointers
12012 	 * in this case.
12013 	 */
12014 	sbp = indirdep->ir_savebp;
12015 	sbp->b_flags |= B_INVAL | B_NOCACHE;
12016 	indirdep->ir_savebp = NULL;
12017 	indirdep->ir_bp = NULL;
12018 	if (*bpp != NULL)
12019 		panic("handle_written_indirdep: bp already exists.");
12020 	*bpp = sbp;
12021 	/*
12022 	 * The indirdep may not be freed until its parent points at it.
12023 	 */
12024 	if (indirdep->ir_state & DEPCOMPLETE)
12025 		free_indirdep(indirdep);
12026 
12027 	return (0);
12028 }
12029 
12030 /*
12031  * Process a diradd entry after its dependent inode has been written.
12032  */
12033 static void
diradd_inode_written(struct diradd * dap,struct inodedep * inodedep)12034 diradd_inode_written(
12035 	struct diradd *dap,
12036 	struct inodedep *inodedep)
12037 {
12038 
12039 	LOCK_OWNED(VFSTOUFS(dap->da_list.wk_mp));
12040 	dap->da_state |= COMPLETE;
12041 	complete_diradd(dap);
12042 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
12043 }
12044 
12045 /*
12046  * Returns true if the bmsafemap will have rollbacks when written.  Must only
12047  * be called with the per-filesystem lock and the buf lock on the cg held.
12048  */
12049 static int
bmsafemap_backgroundwrite(struct bmsafemap * bmsafemap,struct buf * bp)12050 bmsafemap_backgroundwrite(
12051 	struct bmsafemap *bmsafemap,
12052 	struct buf *bp)
12053 {
12054 	int dirty;
12055 
12056 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
12057 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
12058 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
12059 	/*
12060 	 * If we're initiating a background write we need to process the
12061 	 * rollbacks as they exist now, not as they exist when IO starts.
12062 	 * No other consumers will look at the contents of the shadowed
12063 	 * buf so this is safe to do here.
12064 	 */
12065 	if (bp->b_xflags & BX_BKGRDMARKER)
12066 		initiate_write_bmsafemap(bmsafemap, bp);
12067 
12068 	return (dirty);
12069 }
12070 
12071 /*
12072  * Re-apply an allocation when a cg write is complete.
12073  */
12074 static int
jnewblk_rollforward(struct jnewblk * jnewblk,struct fs * fs,struct cg * cgp,uint8_t * blksfree)12075 jnewblk_rollforward(
12076 	struct jnewblk *jnewblk,
12077 	struct fs *fs,
12078 	struct cg *cgp,
12079 	uint8_t *blksfree)
12080 {
12081 	ufs1_daddr_t fragno;
12082 	ufs2_daddr_t blkno;
12083 	long cgbno, bbase;
12084 	int frags, blk;
12085 	int i;
12086 
12087 	frags = 0;
12088 	cgbno = dtogd(fs, jnewblk->jn_blkno);
12089 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
12090 		if (isclr(blksfree, cgbno + i))
12091 			panic("jnewblk_rollforward: re-allocated fragment");
12092 		frags++;
12093 	}
12094 	if (frags == fs->fs_frag) {
12095 		blkno = fragstoblks(fs, cgbno);
12096 		ffs_clrblock(fs, blksfree, (long)blkno);
12097 		ffs_clusteracct(fs, cgp, blkno, -1);
12098 		cgp->cg_cs.cs_nbfree--;
12099 	} else {
12100 		bbase = cgbno - fragnum(fs, cgbno);
12101 		cgbno += jnewblk->jn_oldfrags;
12102                 /* If a complete block had been reassembled, account for it. */
12103 		fragno = fragstoblks(fs, bbase);
12104 		if (ffs_isblock(fs, blksfree, fragno)) {
12105 			cgp->cg_cs.cs_nffree += fs->fs_frag;
12106 			ffs_clusteracct(fs, cgp, fragno, -1);
12107 			cgp->cg_cs.cs_nbfree--;
12108 		}
12109 		/* Decrement the old frags.  */
12110 		blk = blkmap(fs, blksfree, bbase);
12111 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
12112 		/* Allocate the fragment */
12113 		for (i = 0; i < frags; i++)
12114 			clrbit(blksfree, cgbno + i);
12115 		cgp->cg_cs.cs_nffree -= frags;
12116 		/* Add back in counts associated with the new frags */
12117 		blk = blkmap(fs, blksfree, bbase);
12118 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
12119 	}
12120 	return (frags);
12121 }
12122 
12123 /*
12124  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
12125  * changes if it's not a background write.  Set all written dependencies
12126  * to DEPCOMPLETE and free the structure if possible.
12127  *
12128  * If the write did not succeed, we will do all the roll-forward
12129  * operations, but we will not take the actions that will allow its
12130  * dependencies to be processed.
12131  */
12132 static int
handle_written_bmsafemap(struct bmsafemap * bmsafemap,struct buf * bp,int flags)12133 handle_written_bmsafemap(
12134 	struct bmsafemap *bmsafemap,
12135 	struct buf *bp,
12136 	int flags)
12137 {
12138 	struct newblk *newblk;
12139 	struct inodedep *inodedep;
12140 	struct jaddref *jaddref, *jatmp;
12141 	struct jnewblk *jnewblk, *jntmp;
12142 	struct ufsmount *ump;
12143 	uint8_t *inosused;
12144 	uint8_t *blksfree;
12145 	struct cg *cgp;
12146 	struct fs *fs;
12147 	ino_t ino;
12148 	int foreground;
12149 	int chgs;
12150 
12151 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
12152 		panic("handle_written_bmsafemap: Not started\n");
12153 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
12154 	chgs = 0;
12155 	bmsafemap->sm_state &= ~IOSTARTED;
12156 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
12157 	/*
12158 	 * If write was successful, release journal work that was waiting
12159 	 * on the write. Otherwise move the work back.
12160 	 */
12161 	if (flags & WRITESUCCEEDED)
12162 		handle_jwork(&bmsafemap->sm_freewr);
12163 	else
12164 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12165 		    worklist, wk_list);
12166 
12167 	/*
12168 	 * Restore unwritten inode allocation pending jaddref writes.
12169 	 */
12170 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
12171 		cgp = (struct cg *)bp->b_data;
12172 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12173 		inosused = cg_inosused(cgp);
12174 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
12175 		    ja_bmdeps, jatmp) {
12176 			if ((jaddref->ja_state & UNDONE) == 0)
12177 				continue;
12178 			ino = jaddref->ja_ino % fs->fs_ipg;
12179 			if (isset(inosused, ino))
12180 				panic("handle_written_bmsafemap: "
12181 				    "re-allocated inode");
12182 			/* Do the roll-forward only if it's a real copy. */
12183 			if (foreground) {
12184 				if ((jaddref->ja_mode & IFMT) == IFDIR)
12185 					cgp->cg_cs.cs_ndir++;
12186 				cgp->cg_cs.cs_nifree--;
12187 				setbit(inosused, ino);
12188 				chgs = 1;
12189 			}
12190 			jaddref->ja_state &= ~UNDONE;
12191 			jaddref->ja_state |= ATTACHED;
12192 			free_jaddref(jaddref);
12193 		}
12194 	}
12195 	/*
12196 	 * Restore any block allocations which are pending journal writes.
12197 	 */
12198 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
12199 		cgp = (struct cg *)bp->b_data;
12200 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12201 		blksfree = cg_blksfree(cgp);
12202 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
12203 		    jntmp) {
12204 			if ((jnewblk->jn_state & UNDONE) == 0)
12205 				continue;
12206 			/* Do the roll-forward only if it's a real copy. */
12207 			if (foreground &&
12208 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
12209 				chgs = 1;
12210 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
12211 			jnewblk->jn_state |= ATTACHED;
12212 			free_jnewblk(jnewblk);
12213 		}
12214 	}
12215 	/*
12216 	 * If the write did not succeed, we have done all the roll-forward
12217 	 * operations, but we cannot take the actions that will allow its
12218 	 * dependencies to be processed.
12219 	 */
12220 	if ((flags & WRITESUCCEEDED) == 0) {
12221 		LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
12222 		    newblk, nb_deps);
12223 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12224 		    worklist, wk_list);
12225 		if (foreground)
12226 			bdirty(bp);
12227 		return (1);
12228 	}
12229 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
12230 		newblk->nb_state |= DEPCOMPLETE;
12231 		newblk->nb_state &= ~ONDEPLIST;
12232 		newblk->nb_bmsafemap = NULL;
12233 		LIST_REMOVE(newblk, nb_deps);
12234 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
12235 			handle_allocdirect_partdone(
12236 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
12237 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
12238 			handle_allocindir_partdone(
12239 			    WK_ALLOCINDIR(&newblk->nb_list));
12240 		else if (newblk->nb_list.wk_type != D_NEWBLK)
12241 			panic("handle_written_bmsafemap: Unexpected type: %s",
12242 			    TYPENAME(newblk->nb_list.wk_type));
12243 	}
12244 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
12245 		inodedep->id_state |= DEPCOMPLETE;
12246 		inodedep->id_state &= ~ONDEPLIST;
12247 		LIST_REMOVE(inodedep, id_deps);
12248 		inodedep->id_bmsafemap = NULL;
12249 	}
12250 	LIST_REMOVE(bmsafemap, sm_next);
12251 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12252 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12253 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12254 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12255 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
12256 		LIST_REMOVE(bmsafemap, sm_hash);
12257 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12258 		return (0);
12259 	}
12260 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12261 	if (foreground)
12262 		bdirty(bp);
12263 	return (1);
12264 }
12265 
12266 /*
12267  * Try to free a mkdir dependency.
12268  */
12269 static void
complete_mkdir(struct mkdir * mkdir)12270 complete_mkdir(struct mkdir *mkdir)
12271 {
12272 	struct diradd *dap;
12273 
12274 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12275 		return;
12276 	LIST_REMOVE(mkdir, md_mkdirs);
12277 	dap = mkdir->md_diradd;
12278 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12279 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12280 		dap->da_state |= DEPCOMPLETE;
12281 		complete_diradd(dap);
12282 	}
12283 	WORKITEM_FREE(mkdir, D_MKDIR);
12284 }
12285 
12286 /*
12287  * Handle the completion of a mkdir dependency.
12288  */
12289 static void
handle_written_mkdir(struct mkdir * mkdir,int type)12290 handle_written_mkdir(struct mkdir *mkdir, int type)
12291 {
12292 
12293 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12294 		panic("handle_written_mkdir: bad type");
12295 	mkdir->md_state |= COMPLETE;
12296 	complete_mkdir(mkdir);
12297 }
12298 
12299 static int
free_pagedep(struct pagedep * pagedep)12300 free_pagedep(struct pagedep *pagedep)
12301 {
12302 	int i;
12303 
12304 	if (pagedep->pd_state & NEWBLOCK)
12305 		return (0);
12306 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12307 		return (0);
12308 	for (i = 0; i < DAHASHSZ; i++)
12309 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12310 			return (0);
12311 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12312 		return (0);
12313 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12314 		return (0);
12315 	if (pagedep->pd_state & ONWORKLIST)
12316 		WORKLIST_REMOVE(&pagedep->pd_list);
12317 	LIST_REMOVE(pagedep, pd_hash);
12318 	WORKITEM_FREE(pagedep, D_PAGEDEP);
12319 
12320 	return (1);
12321 }
12322 
12323 /*
12324  * Called from within softdep_disk_write_complete above.
12325  * A write operation was just completed. Removed inodes can
12326  * now be freed and associated block pointers may be committed.
12327  * Note that this routine is always called from interrupt level
12328  * with further interrupts from this device blocked.
12329  *
12330  * If the write did not succeed, we will do all the roll-forward
12331  * operations, but we will not take the actions that will allow its
12332  * dependencies to be processed.
12333  */
12334 static int
handle_written_filepage(struct pagedep * pagedep,struct buf * bp,int flags)12335 handle_written_filepage(
12336 	struct pagedep *pagedep,
12337 	struct buf *bp,		/* buffer containing the written page */
12338 	int flags)
12339 {
12340 	struct dirrem *dirrem;
12341 	struct diradd *dap, *nextdap;
12342 	struct direct *ep;
12343 	int i, chgs;
12344 
12345 	if ((pagedep->pd_state & IOSTARTED) == 0)
12346 		panic("handle_written_filepage: not started");
12347 	pagedep->pd_state &= ~IOSTARTED;
12348 	if ((flags & WRITESUCCEEDED) == 0)
12349 		goto rollforward;
12350 	/*
12351 	 * Process any directory removals that have been committed.
12352 	 */
12353 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12354 		LIST_REMOVE(dirrem, dm_next);
12355 		dirrem->dm_state |= COMPLETE;
12356 		dirrem->dm_dirinum = pagedep->pd_ino;
12357 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12358 		    ("handle_written_filepage: Journal entries not written."));
12359 		add_to_worklist(&dirrem->dm_list, 0);
12360 	}
12361 	/*
12362 	 * Free any directory additions that have been committed.
12363 	 * If it is a newly allocated block, we have to wait until
12364 	 * the on-disk directory inode claims the new block.
12365 	 */
12366 	if ((pagedep->pd_state & NEWBLOCK) == 0)
12367 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12368 			free_diradd(dap, NULL);
12369 rollforward:
12370 	/*
12371 	 * Uncommitted directory entries must be restored.
12372 	 */
12373 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12374 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12375 		     dap = nextdap) {
12376 			nextdap = LIST_NEXT(dap, da_pdlist);
12377 			if (dap->da_state & ATTACHED)
12378 				panic("handle_written_filepage: attached");
12379 			ep = (struct direct *)
12380 			    ((char *)bp->b_data + dap->da_offset);
12381 			ep->d_ino = dap->da_newinum;
12382 			dap->da_state &= ~UNDONE;
12383 			dap->da_state |= ATTACHED;
12384 			chgs = 1;
12385 			/*
12386 			 * If the inode referenced by the directory has
12387 			 * been written out, then the dependency can be
12388 			 * moved to the pending list.
12389 			 */
12390 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12391 				LIST_REMOVE(dap, da_pdlist);
12392 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12393 				    da_pdlist);
12394 			}
12395 		}
12396 	}
12397 	/*
12398 	 * If there were any rollbacks in the directory, then it must be
12399 	 * marked dirty so that its will eventually get written back in
12400 	 * its correct form.
12401 	 */
12402 	if (chgs || (flags & WRITESUCCEEDED) == 0) {
12403 		if ((bp->b_flags & B_DELWRI) == 0)
12404 			stat_dir_entry++;
12405 		bdirty(bp);
12406 		return (1);
12407 	}
12408 	/*
12409 	 * If we are not waiting for a new directory block to be
12410 	 * claimed by its inode, then the pagedep will be freed.
12411 	 * Otherwise it will remain to track any new entries on
12412 	 * the page in case they are fsync'ed.
12413 	 */
12414 	free_pagedep(pagedep);
12415 	return (0);
12416 }
12417 
12418 /*
12419  * Writing back in-core inode structures.
12420  *
12421  * The filesystem only accesses an inode's contents when it occupies an
12422  * "in-core" inode structure.  These "in-core" structures are separate from
12423  * the page frames used to cache inode blocks.  Only the latter are
12424  * transferred to/from the disk.  So, when the updated contents of the
12425  * "in-core" inode structure are copied to the corresponding in-memory inode
12426  * block, the dependencies are also transferred.  The following procedure is
12427  * called when copying a dirty "in-core" inode to a cached inode block.
12428  */
12429 
12430 /*
12431  * Called when an inode is loaded from disk. If the effective link count
12432  * differed from the actual link count when it was last flushed, then we
12433  * need to ensure that the correct effective link count is put back.
12434  */
12435 void
softdep_load_inodeblock(struct inode * ip)12436 softdep_load_inodeblock(
12437 	struct inode *ip)	/* the "in_core" copy of the inode */
12438 {
12439 	struct inodedep *inodedep;
12440 	struct ufsmount *ump;
12441 
12442 	ump = ITOUMP(ip);
12443 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12444 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12445 	/*
12446 	 * Check for alternate nlink count.
12447 	 */
12448 	ip->i_effnlink = ip->i_nlink;
12449 	ACQUIRE_LOCK(ump);
12450 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12451 		FREE_LOCK(ump);
12452 		return;
12453 	}
12454 	if (ip->i_nlink != inodedep->id_nlinkwrote &&
12455 	    inodedep->id_nlinkwrote != -1) {
12456 		KASSERT(ip->i_nlink == 0 &&
12457 		    (ump->um_flags & UM_FSFAIL_CLEANUP) != 0,
12458 		    ("read bad i_nlink value"));
12459 		ip->i_effnlink = ip->i_nlink = inodedep->id_nlinkwrote;
12460 	}
12461 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12462 	KASSERT(ip->i_effnlink >= 0,
12463 	    ("softdep_load_inodeblock: negative i_effnlink"));
12464 	FREE_LOCK(ump);
12465 }
12466 
12467 /*
12468  * This routine is called just before the "in-core" inode
12469  * information is to be copied to the in-memory inode block.
12470  * Recall that an inode block contains several inodes. If
12471  * the force flag is set, then the dependencies will be
12472  * cleared so that the update can always be made. Note that
12473  * the buffer is locked when this routine is called, so we
12474  * will never be in the middle of writing the inode block
12475  * to disk.
12476  */
12477 void
softdep_update_inodeblock(struct inode * ip,struct buf * bp,int waitfor)12478 softdep_update_inodeblock(
12479 	struct inode *ip,	/* the "in_core" copy of the inode */
12480 	struct buf *bp,		/* the buffer containing the inode block */
12481 	int waitfor)		/* nonzero => update must be allowed */
12482 {
12483 	struct inodedep *inodedep;
12484 	struct inoref *inoref;
12485 	struct ufsmount *ump;
12486 	struct worklist *wk;
12487 	struct mount *mp;
12488 	struct buf *ibp;
12489 	struct fs *fs;
12490 	int error;
12491 
12492 	ump = ITOUMP(ip);
12493 	mp = UFSTOVFS(ump);
12494 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12495 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12496 	fs = ump->um_fs;
12497 	/*
12498 	 * If the effective link count is not equal to the actual link
12499 	 * count, then we must track the difference in an inodedep while
12500 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12501 	 * if there is no existing inodedep, then there are no dependencies
12502 	 * to track.
12503 	 */
12504 	ACQUIRE_LOCK(ump);
12505 again:
12506 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12507 		FREE_LOCK(ump);
12508 		if (ip->i_effnlink != ip->i_nlink)
12509 			panic("softdep_update_inodeblock: bad link count");
12510 		return;
12511 	}
12512 	/*
12513 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12514 	 * does not have access to the in-core ip so must write directly into
12515 	 * the inode block buffer when setting freelink.
12516 	 */
12517 	if ((inodedep->id_state & UNLINKED) != 0) {
12518 		if (fs->fs_magic == FS_UFS1_MAGIC)
12519 			DIP_SET(ip, i_freelink,
12520 			    ((struct ufs1_dinode *)bp->b_data +
12521 			    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12522 		else
12523 			DIP_SET(ip, i_freelink,
12524 			    ((struct ufs2_dinode *)bp->b_data +
12525 			    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12526 	}
12527 	KASSERT(ip->i_nlink >= inodedep->id_nlinkdelta,
12528 	    ("softdep_update_inodeblock inconsistent ip %p i_nlink %d "
12529 	    "inodedep %p id_nlinkdelta %jd",
12530 	    ip, ip->i_nlink, inodedep, (intmax_t)inodedep->id_nlinkdelta));
12531 	inodedep->id_nlinkwrote = ip->i_nlink;
12532 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12533 		panic("softdep_update_inodeblock: bad delta");
12534 	/*
12535 	 * If we're flushing all dependencies we must also move any waiting
12536 	 * for journal writes onto the bufwait list prior to I/O.
12537 	 */
12538 	if (waitfor) {
12539 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12540 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12541 			    == DEPCOMPLETE) {
12542 				jwait(&inoref->if_list, MNT_WAIT);
12543 				goto again;
12544 			}
12545 		}
12546 	}
12547 	/*
12548 	 * Changes have been initiated. Anything depending on these
12549 	 * changes cannot occur until this inode has been written.
12550 	 */
12551 	inodedep->id_state &= ~COMPLETE;
12552 	if ((inodedep->id_state & ONWORKLIST) == 0)
12553 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12554 	/*
12555 	 * Any new dependencies associated with the incore inode must
12556 	 * now be moved to the list associated with the buffer holding
12557 	 * the in-memory copy of the inode. Once merged process any
12558 	 * allocdirects that are completed by the merger.
12559 	 */
12560 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12561 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12562 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12563 		    NULL);
12564 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12565 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12566 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12567 		    NULL);
12568 	/*
12569 	 * Now that the inode has been pushed into the buffer, the
12570 	 * operations dependent on the inode being written to disk
12571 	 * can be moved to the id_bufwait so that they will be
12572 	 * processed when the buffer I/O completes.
12573 	 */
12574 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12575 		WORKLIST_REMOVE(wk);
12576 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12577 	}
12578 	/*
12579 	 * Newly allocated inodes cannot be written until the bitmap
12580 	 * that allocates them have been written (indicated by
12581 	 * DEPCOMPLETE being set in id_state). If we are doing a
12582 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12583 	 * to be written so that the update can be done.
12584 	 */
12585 	if (waitfor == 0) {
12586 		FREE_LOCK(ump);
12587 		return;
12588 	}
12589 retry:
12590 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12591 		FREE_LOCK(ump);
12592 		return;
12593 	}
12594 	ibp = inodedep->id_bmsafemap->sm_buf;
12595 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12596 	if (ibp == NULL) {
12597 		/*
12598 		 * If ibp came back as NULL, the dependency could have been
12599 		 * freed while we slept.  Look it up again, and check to see
12600 		 * that it has completed.
12601 		 */
12602 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12603 			goto retry;
12604 		FREE_LOCK(ump);
12605 		return;
12606 	}
12607 	FREE_LOCK(ump);
12608 	if ((error = bwrite(ibp)) != 0)
12609 		softdep_error("softdep_update_inodeblock: bwrite", error);
12610 }
12611 
12612 /*
12613  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12614  * old inode dependency list (such as id_inoupdt).
12615  */
12616 static void
merge_inode_lists(struct allocdirectlst * newlisthead,struct allocdirectlst * oldlisthead)12617 merge_inode_lists(
12618 	struct allocdirectlst *newlisthead,
12619 	struct allocdirectlst *oldlisthead)
12620 {
12621 	struct allocdirect *listadp, *newadp;
12622 
12623 	newadp = TAILQ_FIRST(newlisthead);
12624 	if (newadp != NULL)
12625 		LOCK_OWNED(VFSTOUFS(newadp->ad_block.nb_list.wk_mp));
12626 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12627 		if (listadp->ad_offset < newadp->ad_offset) {
12628 			listadp = TAILQ_NEXT(listadp, ad_next);
12629 			continue;
12630 		}
12631 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12632 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12633 		if (listadp->ad_offset == newadp->ad_offset) {
12634 			allocdirect_merge(oldlisthead, newadp,
12635 			    listadp);
12636 			listadp = newadp;
12637 		}
12638 		newadp = TAILQ_FIRST(newlisthead);
12639 	}
12640 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12641 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12642 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12643 	}
12644 }
12645 
12646 /*
12647  * If we are doing an fsync, then we must ensure that any directory
12648  * entries for the inode have been written after the inode gets to disk.
12649  */
12650 int
softdep_fsync(struct vnode * vp)12651 softdep_fsync(
12652 	struct vnode *vp)	/* the "in_core" copy of the inode */
12653 {
12654 	struct inodedep *inodedep;
12655 	struct pagedep *pagedep;
12656 	struct inoref *inoref;
12657 	struct ufsmount *ump;
12658 	struct worklist *wk;
12659 	struct diradd *dap;
12660 	struct mount *mp;
12661 	struct vnode *pvp;
12662 	struct inode *ip;
12663 	struct buf *bp;
12664 	struct fs *fs;
12665 	struct thread *td = curthread;
12666 	int error, flushparent, pagedep_new_block;
12667 	ino_t parentino;
12668 	ufs_lbn_t lbn;
12669 
12670 	ip = VTOI(vp);
12671 	mp = vp->v_mount;
12672 	ump = VFSTOUFS(mp);
12673 	fs = ump->um_fs;
12674 	if (MOUNTEDSOFTDEP(mp) == 0)
12675 		return (0);
12676 	ACQUIRE_LOCK(ump);
12677 restart:
12678 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12679 		FREE_LOCK(ump);
12680 		return (0);
12681 	}
12682 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12683 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12684 		    == DEPCOMPLETE) {
12685 			jwait(&inoref->if_list, MNT_WAIT);
12686 			goto restart;
12687 		}
12688 	}
12689 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12690 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12691 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12692 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12693 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12694 		panic("softdep_fsync: pending ops %p", inodedep);
12695 	for (error = 0, flushparent = 0; ; ) {
12696 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12697 			break;
12698 		if (wk->wk_type != D_DIRADD)
12699 			panic("softdep_fsync: Unexpected type %s",
12700 			    TYPENAME(wk->wk_type));
12701 		dap = WK_DIRADD(wk);
12702 		/*
12703 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12704 		 * dependency or is contained in a newly allocated block.
12705 		 */
12706 		if (dap->da_state & DIRCHG)
12707 			pagedep = dap->da_previous->dm_pagedep;
12708 		else
12709 			pagedep = dap->da_pagedep;
12710 		parentino = pagedep->pd_ino;
12711 		lbn = pagedep->pd_lbn;
12712 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12713 			panic("softdep_fsync: dirty");
12714 		if ((dap->da_state & MKDIR_PARENT) ||
12715 		    (pagedep->pd_state & NEWBLOCK))
12716 			flushparent = 1;
12717 		else
12718 			flushparent = 0;
12719 		/*
12720 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12721 		 * then we will not be able to release and recover the
12722 		 * vnode below, so we just have to give up on writing its
12723 		 * directory entry out. It will eventually be written, just
12724 		 * not now, but then the user was not asking to have it
12725 		 * written, so we are not breaking any promises.
12726 		 */
12727 		if (VN_IS_DOOMED(vp))
12728 			break;
12729 		/*
12730 		 * We prevent deadlock by always fetching inodes from the
12731 		 * root, moving down the directory tree. Thus, when fetching
12732 		 * our parent directory, we first try to get the lock. If
12733 		 * that fails, we must unlock ourselves before requesting
12734 		 * the lock on our parent. See the comment in ufs_lookup
12735 		 * for details on possible races.
12736 		 */
12737 		FREE_LOCK(ump);
12738 		error = get_parent_vp(vp, mp, parentino, NULL, NULL, NULL,
12739 		    &pvp);
12740 		if (error == ERELOOKUP)
12741 			error = 0;
12742 		if (error != 0)
12743 			return (error);
12744 		/*
12745 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12746 		 * that are contained in direct blocks will be resolved by
12747 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12748 		 * may require a complete sync'ing of the directory. So, we
12749 		 * try the cheap and fast ffs_update first, and if that fails,
12750 		 * then we do the slower ffs_syncvnode of the directory.
12751 		 */
12752 		if (flushparent) {
12753 			int locked;
12754 
12755 			if ((error = ffs_update(pvp, 1)) != 0) {
12756 				vput(pvp);
12757 				return (error);
12758 			}
12759 			ACQUIRE_LOCK(ump);
12760 			locked = 1;
12761 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12762 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12763 					if (wk->wk_type != D_DIRADD)
12764 						panic("softdep_fsync: Unexpected type %s",
12765 						      TYPENAME(wk->wk_type));
12766 					dap = WK_DIRADD(wk);
12767 					if (dap->da_state & DIRCHG)
12768 						pagedep = dap->da_previous->dm_pagedep;
12769 					else
12770 						pagedep = dap->da_pagedep;
12771 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12772 					FREE_LOCK(ump);
12773 					locked = 0;
12774 					if (pagedep_new_block) {
12775 						VOP_UNLOCK(vp);
12776 						error = ffs_syncvnode(pvp,
12777 						    MNT_WAIT, 0);
12778 						if (error == 0)
12779 							error = ERELOOKUP;
12780 						vput(pvp);
12781 						vn_lock(vp, LK_EXCLUSIVE |
12782 						    LK_RETRY);
12783 						return (error);
12784 					}
12785 				}
12786 			}
12787 			if (locked)
12788 				FREE_LOCK(ump);
12789 		}
12790 		/*
12791 		 * Flush directory page containing the inode's name.
12792 		 */
12793 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12794 		    &bp);
12795 		if (error == 0)
12796 			error = bwrite(bp);
12797 		else
12798 			brelse(bp);
12799 		vput(pvp);
12800 		if (!ffs_fsfail_cleanup(ump, error))
12801 			return (error);
12802 		ACQUIRE_LOCK(ump);
12803 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12804 			break;
12805 	}
12806 	FREE_LOCK(ump);
12807 	return (0);
12808 }
12809 
12810 /*
12811  * Flush all the dirty bitmaps associated with the block device
12812  * before flushing the rest of the dirty blocks so as to reduce
12813  * the number of dependencies that will have to be rolled back.
12814  *
12815  * XXX Unused?
12816  */
12817 void
softdep_fsync_mountdev(struct vnode * vp)12818 softdep_fsync_mountdev(struct vnode *vp)
12819 {
12820 	struct buf *bp, *nbp;
12821 	struct worklist *wk;
12822 	struct bufobj *bo;
12823 
12824 	if (!vn_isdisk(vp))
12825 		panic("softdep_fsync_mountdev: vnode not a disk");
12826 	bo = &vp->v_bufobj;
12827 restart:
12828 	BO_LOCK(bo);
12829 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12830 		/*
12831 		 * If it is already scheduled, skip to the next buffer.
12832 		 */
12833 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12834 			continue;
12835 
12836 		if ((bp->b_flags & B_DELWRI) == 0)
12837 			panic("softdep_fsync_mountdev: not dirty");
12838 		/*
12839 		 * We are only interested in bitmaps with outstanding
12840 		 * dependencies.
12841 		 */
12842 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12843 		    wk->wk_type != D_BMSAFEMAP ||
12844 		    (bp->b_vflags & BV_BKGRDINPROG)) {
12845 			BUF_UNLOCK(bp);
12846 			continue;
12847 		}
12848 		BO_UNLOCK(bo);
12849 		bremfree(bp);
12850 		(void) bawrite(bp);
12851 		goto restart;
12852 	}
12853 	drain_output(vp);
12854 	BO_UNLOCK(bo);
12855 }
12856 
12857 /*
12858  * Sync all cylinder groups that were dirty at the time this function is
12859  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12860  * is used to flush freedep activity that may be holding up writes to a
12861  * indirect block.
12862  */
12863 static int
sync_cgs(struct mount * mp,int waitfor)12864 sync_cgs(struct mount *mp, int waitfor)
12865 {
12866 	struct bmsafemap *bmsafemap;
12867 	struct bmsafemap *sentinel;
12868 	struct ufsmount *ump;
12869 	struct buf *bp;
12870 	int error;
12871 
12872 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12873 	sentinel->sm_cg = -1;
12874 	ump = VFSTOUFS(mp);
12875 	error = 0;
12876 	ACQUIRE_LOCK(ump);
12877 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12878 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12879 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12880 		/* Skip sentinels and cgs with no work to release. */
12881 		if (bmsafemap->sm_cg == -1 ||
12882 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12883 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
12884 			LIST_REMOVE(sentinel, sm_next);
12885 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12886 			continue;
12887 		}
12888 		/*
12889 		 * If we don't get the lock and we're waiting try again, if
12890 		 * not move on to the next buf and try to sync it.
12891 		 */
12892 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12893 		if (bp == NULL && waitfor == MNT_WAIT)
12894 			continue;
12895 		LIST_REMOVE(sentinel, sm_next);
12896 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12897 		if (bp == NULL)
12898 			continue;
12899 		FREE_LOCK(ump);
12900 		if (waitfor == MNT_NOWAIT)
12901 			bawrite(bp);
12902 		else
12903 			error = bwrite(bp);
12904 		ACQUIRE_LOCK(ump);
12905 		if (error)
12906 			break;
12907 	}
12908 	LIST_REMOVE(sentinel, sm_next);
12909 	FREE_LOCK(ump);
12910 	free(sentinel, M_BMSAFEMAP);
12911 	return (error);
12912 }
12913 
12914 /*
12915  * This routine is called when we are trying to synchronously flush a
12916  * file. This routine must eliminate any filesystem metadata dependencies
12917  * so that the syncing routine can succeed.
12918  */
12919 int
softdep_sync_metadata(struct vnode * vp)12920 softdep_sync_metadata(struct vnode *vp)
12921 {
12922 	struct inode *ip;
12923 	int error;
12924 
12925 	ip = VTOI(vp);
12926 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12927 	    ("softdep_sync_metadata called on non-softdep filesystem"));
12928 	/*
12929 	 * Ensure that any direct block dependencies have been cleared,
12930 	 * truncations are started, and inode references are journaled.
12931 	 */
12932 	ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12933 	/*
12934 	 * Write all journal records to prevent rollbacks on devvp.
12935 	 */
12936 	if (vp->v_type == VCHR)
12937 		softdep_flushjournal(vp->v_mount);
12938 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12939 	/*
12940 	 * Ensure that all truncates are written so we won't find deps on
12941 	 * indirect blocks.
12942 	 */
12943 	process_truncates(vp);
12944 	FREE_LOCK(VFSTOUFS(vp->v_mount));
12945 
12946 	return (error);
12947 }
12948 
12949 /*
12950  * This routine is called when we are attempting to sync a buf with
12951  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12952  * other IO it can but returns EBUSY if the buffer is not yet able to
12953  * be written.  Dependencies which will not cause rollbacks will always
12954  * return 0.
12955  */
12956 int
softdep_sync_buf(struct vnode * vp,struct buf * bp,int waitfor)12957 softdep_sync_buf(struct vnode *vp,
12958 	struct buf *bp,
12959 	int waitfor)
12960 {
12961 	struct indirdep *indirdep;
12962 	struct pagedep *pagedep;
12963 	struct allocindir *aip;
12964 	struct newblk *newblk;
12965 	struct ufsmount *ump;
12966 	struct buf *nbp;
12967 	struct worklist *wk;
12968 	int i, error;
12969 
12970 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12971 	    ("softdep_sync_buf called on non-softdep filesystem"));
12972 	/*
12973 	 * For VCHR we just don't want to force flush any dependencies that
12974 	 * will cause rollbacks.
12975 	 */
12976 	if (vp->v_type == VCHR) {
12977 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12978 			return (EBUSY);
12979 		return (0);
12980 	}
12981 	ump = VFSTOUFS(vp->v_mount);
12982 	ACQUIRE_LOCK(ump);
12983 	/*
12984 	 * As we hold the buffer locked, none of its dependencies
12985 	 * will disappear.
12986 	 */
12987 	error = 0;
12988 top:
12989 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12990 		switch (wk->wk_type) {
12991 		case D_ALLOCDIRECT:
12992 		case D_ALLOCINDIR:
12993 			newblk = WK_NEWBLK(wk);
12994 			if (newblk->nb_jnewblk != NULL) {
12995 				if (waitfor == MNT_NOWAIT) {
12996 					error = EBUSY;
12997 					goto out_unlock;
12998 				}
12999 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
13000 				goto top;
13001 			}
13002 			if (newblk->nb_state & DEPCOMPLETE ||
13003 			    waitfor == MNT_NOWAIT)
13004 				continue;
13005 			nbp = newblk->nb_bmsafemap->sm_buf;
13006 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
13007 			if (nbp == NULL)
13008 				goto top;
13009 			FREE_LOCK(ump);
13010 			if ((error = bwrite(nbp)) != 0)
13011 				goto out;
13012 			ACQUIRE_LOCK(ump);
13013 			continue;
13014 
13015 		case D_INDIRDEP:
13016 			indirdep = WK_INDIRDEP(wk);
13017 			if (waitfor == MNT_NOWAIT) {
13018 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
13019 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
13020 					error = EBUSY;
13021 					goto out_unlock;
13022 				}
13023 			}
13024 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
13025 				panic("softdep_sync_buf: truncation pending.");
13026 		restart:
13027 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
13028 				newblk = (struct newblk *)aip;
13029 				if (newblk->nb_jnewblk != NULL) {
13030 					jwait(&newblk->nb_jnewblk->jn_list,
13031 					    waitfor);
13032 					goto restart;
13033 				}
13034 				if (newblk->nb_state & DEPCOMPLETE)
13035 					continue;
13036 				nbp = newblk->nb_bmsafemap->sm_buf;
13037 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
13038 				if (nbp == NULL)
13039 					goto restart;
13040 				FREE_LOCK(ump);
13041 				if ((error = bwrite(nbp)) != 0)
13042 					goto out;
13043 				ACQUIRE_LOCK(ump);
13044 				goto restart;
13045 			}
13046 			continue;
13047 
13048 		case D_PAGEDEP:
13049 			/*
13050 			 * Only flush directory entries in synchronous passes.
13051 			 */
13052 			if (waitfor != MNT_WAIT) {
13053 				error = EBUSY;
13054 				goto out_unlock;
13055 			}
13056 			/*
13057 			 * While syncing snapshots, we must allow recursive
13058 			 * lookups.
13059 			 */
13060 			BUF_AREC(bp);
13061 			/*
13062 			 * We are trying to sync a directory that may
13063 			 * have dependencies on both its own metadata
13064 			 * and/or dependencies on the inodes of any
13065 			 * recently allocated files. We walk its diradd
13066 			 * lists pushing out the associated inode.
13067 			 */
13068 			pagedep = WK_PAGEDEP(wk);
13069 			for (i = 0; i < DAHASHSZ; i++) {
13070 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
13071 					continue;
13072 				error = flush_pagedep_deps(vp, wk->wk_mp,
13073 				    &pagedep->pd_diraddhd[i], bp);
13074 				if (error != 0) {
13075 					if (error != ERELOOKUP)
13076 						BUF_NOREC(bp);
13077 					goto out_unlock;
13078 				}
13079 			}
13080 			BUF_NOREC(bp);
13081 			continue;
13082 
13083 		case D_FREEWORK:
13084 		case D_FREEDEP:
13085 		case D_JSEGDEP:
13086 		case D_JNEWBLK:
13087 			continue;
13088 
13089 		default:
13090 			panic("softdep_sync_buf: Unknown type %s",
13091 			    TYPENAME(wk->wk_type));
13092 			/* NOTREACHED */
13093 		}
13094 	}
13095 out_unlock:
13096 	FREE_LOCK(ump);
13097 out:
13098 	return (error);
13099 }
13100 
13101 /*
13102  * Flush the dependencies associated with an inodedep.
13103  */
13104 static int
flush_inodedep_deps(struct vnode * vp,struct mount * mp,ino_t ino)13105 flush_inodedep_deps(
13106 	struct vnode *vp,
13107 	struct mount *mp,
13108 	ino_t ino)
13109 {
13110 	struct inodedep *inodedep;
13111 	struct inoref *inoref;
13112 	struct ufsmount *ump;
13113 	int error, waitfor;
13114 
13115 	/*
13116 	 * This work is done in two passes. The first pass grabs most
13117 	 * of the buffers and begins asynchronously writing them. The
13118 	 * only way to wait for these asynchronous writes is to sleep
13119 	 * on the filesystem vnode which may stay busy for a long time
13120 	 * if the filesystem is active. So, instead, we make a second
13121 	 * pass over the dependencies blocking on each write. In the
13122 	 * usual case we will be blocking against a write that we
13123 	 * initiated, so when it is done the dependency will have been
13124 	 * resolved. Thus the second pass is expected to end quickly.
13125 	 * We give a brief window at the top of the loop to allow
13126 	 * any pending I/O to complete.
13127 	 */
13128 	ump = VFSTOUFS(mp);
13129 	LOCK_OWNED(ump);
13130 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
13131 		if (error)
13132 			return (error);
13133 		FREE_LOCK(ump);
13134 		ACQUIRE_LOCK(ump);
13135 restart:
13136 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13137 			return (0);
13138 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13139 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13140 			    == DEPCOMPLETE) {
13141 				jwait(&inoref->if_list, MNT_WAIT);
13142 				goto restart;
13143 			}
13144 		}
13145 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
13146 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
13147 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
13148 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
13149 			continue;
13150 		/*
13151 		 * If pass2, we are done, otherwise do pass 2.
13152 		 */
13153 		if (waitfor == MNT_WAIT)
13154 			break;
13155 		waitfor = MNT_WAIT;
13156 	}
13157 	/*
13158 	 * Try freeing inodedep in case all dependencies have been removed.
13159 	 */
13160 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
13161 		(void) free_inodedep(inodedep);
13162 	return (0);
13163 }
13164 
13165 /*
13166  * Flush an inode dependency list.
13167  */
13168 static int
flush_deplist(struct allocdirectlst * listhead,int waitfor,int * errorp)13169 flush_deplist(
13170 	struct allocdirectlst *listhead,
13171 	int waitfor,
13172 	int *errorp)
13173 {
13174 	struct allocdirect *adp;
13175 	struct newblk *newblk;
13176 	struct ufsmount *ump;
13177 	struct buf *bp;
13178 
13179 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
13180 		return (0);
13181 	ump = VFSTOUFS(adp->ad_list.wk_mp);
13182 	LOCK_OWNED(ump);
13183 	TAILQ_FOREACH(adp, listhead, ad_next) {
13184 		newblk = (struct newblk *)adp;
13185 		if (newblk->nb_jnewblk != NULL) {
13186 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13187 			return (1);
13188 		}
13189 		if (newblk->nb_state & DEPCOMPLETE)
13190 			continue;
13191 		bp = newblk->nb_bmsafemap->sm_buf;
13192 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
13193 		if (bp == NULL) {
13194 			if (waitfor == MNT_NOWAIT)
13195 				continue;
13196 			return (1);
13197 		}
13198 		FREE_LOCK(ump);
13199 		if (waitfor == MNT_NOWAIT)
13200 			bawrite(bp);
13201 		else
13202 			*errorp = bwrite(bp);
13203 		ACQUIRE_LOCK(ump);
13204 		return (1);
13205 	}
13206 	return (0);
13207 }
13208 
13209 /*
13210  * Flush dependencies associated with an allocdirect block.
13211  */
13212 static int
flush_newblk_dep(struct vnode * vp,struct mount * mp,ufs_lbn_t lbn)13213 flush_newblk_dep(
13214 	struct vnode *vp,
13215 	struct mount *mp,
13216 	ufs_lbn_t lbn)
13217 {
13218 	struct newblk *newblk;
13219 	struct ufsmount *ump;
13220 	struct bufobj *bo;
13221 	struct inode *ip;
13222 	struct buf *bp;
13223 	ufs2_daddr_t blkno;
13224 	int error;
13225 
13226 	error = 0;
13227 	bo = &vp->v_bufobj;
13228 	ip = VTOI(vp);
13229 	blkno = DIP(ip, i_db[lbn]);
13230 	if (blkno == 0)
13231 		panic("flush_newblk_dep: Missing block");
13232 	ump = VFSTOUFS(mp);
13233 	ACQUIRE_LOCK(ump);
13234 	/*
13235 	 * Loop until all dependencies related to this block are satisfied.
13236 	 * We must be careful to restart after each sleep in case a write
13237 	 * completes some part of this process for us.
13238 	 */
13239 	for (;;) {
13240 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
13241 			FREE_LOCK(ump);
13242 			break;
13243 		}
13244 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13245 			panic("flush_newblk_dep: Bad newblk %p", newblk);
13246 		/*
13247 		 * Flush the journal.
13248 		 */
13249 		if (newblk->nb_jnewblk != NULL) {
13250 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13251 			continue;
13252 		}
13253 		/*
13254 		 * Write the bitmap dependency.
13255 		 */
13256 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13257 			bp = newblk->nb_bmsafemap->sm_buf;
13258 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13259 			if (bp == NULL)
13260 				continue;
13261 			FREE_LOCK(ump);
13262 			error = bwrite(bp);
13263 			if (error)
13264 				break;
13265 			ACQUIRE_LOCK(ump);
13266 			continue;
13267 		}
13268 		/*
13269 		 * Write the buffer.
13270 		 */
13271 		FREE_LOCK(ump);
13272 		BO_LOCK(bo);
13273 		bp = gbincore(bo, lbn);
13274 		if (bp != NULL) {
13275 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13276 			    LK_INTERLOCK, BO_LOCKPTR(bo));
13277 			if (error == ENOLCK) {
13278 				ACQUIRE_LOCK(ump);
13279 				error = 0;
13280 				continue; /* Slept, retry */
13281 			}
13282 			if (error != 0)
13283 				break;	/* Failed */
13284 			if (bp->b_flags & B_DELWRI) {
13285 				bremfree(bp);
13286 				error = bwrite(bp);
13287 				if (error)
13288 					break;
13289 			} else
13290 				BUF_UNLOCK(bp);
13291 		} else
13292 			BO_UNLOCK(bo);
13293 		/*
13294 		 * We have to wait for the direct pointers to
13295 		 * point at the newdirblk before the dependency
13296 		 * will go away.
13297 		 */
13298 		error = ffs_update(vp, 1);
13299 		if (error)
13300 			break;
13301 		ACQUIRE_LOCK(ump);
13302 	}
13303 	return (error);
13304 }
13305 
13306 /*
13307  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13308  */
13309 static int
flush_pagedep_deps(struct vnode * pvp,struct mount * mp,struct diraddhd * diraddhdp,struct buf * locked_bp)13310 flush_pagedep_deps(
13311 	struct vnode *pvp,
13312 	struct mount *mp,
13313 	struct diraddhd *diraddhdp,
13314 	struct buf *locked_bp)
13315 {
13316 	struct inodedep *inodedep;
13317 	struct inoref *inoref;
13318 	struct ufsmount *ump;
13319 	struct diradd *dap;
13320 	struct vnode *vp;
13321 	int error = 0;
13322 	struct buf *bp;
13323 	ino_t inum;
13324 	struct diraddhd unfinished;
13325 
13326 	LIST_INIT(&unfinished);
13327 	ump = VFSTOUFS(mp);
13328 	LOCK_OWNED(ump);
13329 restart:
13330 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13331 		/*
13332 		 * Flush ourselves if this directory entry
13333 		 * has a MKDIR_PARENT dependency.
13334 		 */
13335 		if (dap->da_state & MKDIR_PARENT) {
13336 			FREE_LOCK(ump);
13337 			if ((error = ffs_update(pvp, 1)) != 0)
13338 				break;
13339 			ACQUIRE_LOCK(ump);
13340 			/*
13341 			 * If that cleared dependencies, go on to next.
13342 			 */
13343 			if (dap != LIST_FIRST(diraddhdp))
13344 				continue;
13345 			/*
13346 			 * All MKDIR_PARENT dependencies and all the
13347 			 * NEWBLOCK pagedeps that are contained in direct
13348 			 * blocks were resolved by doing above ffs_update.
13349 			 * Pagedeps contained in indirect blocks may
13350 			 * require a complete sync'ing of the directory.
13351 			 * We are in the midst of doing a complete sync,
13352 			 * so if they are not resolved in this pass we
13353 			 * defer them for now as they will be sync'ed by
13354 			 * our caller shortly.
13355 			 */
13356 			LIST_REMOVE(dap, da_pdlist);
13357 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13358 			continue;
13359 		}
13360 		/*
13361 		 * A newly allocated directory must have its "." and
13362 		 * ".." entries written out before its name can be
13363 		 * committed in its parent.
13364 		 */
13365 		inum = dap->da_newinum;
13366 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13367 			panic("flush_pagedep_deps: lost inode1");
13368 		/*
13369 		 * Wait for any pending journal adds to complete so we don't
13370 		 * cause rollbacks while syncing.
13371 		 */
13372 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13373 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13374 			    == DEPCOMPLETE) {
13375 				jwait(&inoref->if_list, MNT_WAIT);
13376 				goto restart;
13377 			}
13378 		}
13379 		if (dap->da_state & MKDIR_BODY) {
13380 			FREE_LOCK(ump);
13381 			error = get_parent_vp(pvp, mp, inum, locked_bp,
13382 			    diraddhdp, &unfinished, &vp);
13383 			if (error != 0)
13384 				break;
13385 			error = flush_newblk_dep(vp, mp, 0);
13386 			/*
13387 			 * If we still have the dependency we might need to
13388 			 * update the vnode to sync the new link count to
13389 			 * disk.
13390 			 */
13391 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
13392 				error = ffs_update(vp, 1);
13393 			vput(vp);
13394 			if (error != 0)
13395 				break;
13396 			ACQUIRE_LOCK(ump);
13397 			/*
13398 			 * If that cleared dependencies, go on to next.
13399 			 */
13400 			if (dap != LIST_FIRST(diraddhdp))
13401 				continue;
13402 			if (dap->da_state & MKDIR_BODY) {
13403 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
13404 				    &inodedep);
13405 				panic("flush_pagedep_deps: MKDIR_BODY "
13406 				    "inodedep %p dap %p vp %p",
13407 				    inodedep, dap, vp);
13408 			}
13409 		}
13410 		/*
13411 		 * Flush the inode on which the directory entry depends.
13412 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13413 		 * the only remaining dependency is that the updated inode
13414 		 * count must get pushed to disk. The inode has already
13415 		 * been pushed into its inode buffer (via VOP_UPDATE) at
13416 		 * the time of the reference count change. So we need only
13417 		 * locate that buffer, ensure that there will be no rollback
13418 		 * caused by a bitmap dependency, then write the inode buffer.
13419 		 */
13420 retry:
13421 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13422 			panic("flush_pagedep_deps: lost inode");
13423 		/*
13424 		 * If the inode still has bitmap dependencies,
13425 		 * push them to disk.
13426 		 */
13427 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13428 			bp = inodedep->id_bmsafemap->sm_buf;
13429 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13430 			if (bp == NULL)
13431 				goto retry;
13432 			FREE_LOCK(ump);
13433 			if ((error = bwrite(bp)) != 0)
13434 				break;
13435 			ACQUIRE_LOCK(ump);
13436 			if (dap != LIST_FIRST(diraddhdp))
13437 				continue;
13438 		}
13439 		/*
13440 		 * If the inode is still sitting in a buffer waiting
13441 		 * to be written or waiting for the link count to be
13442 		 * adjusted update it here to flush it to disk.
13443 		 */
13444 		if (dap == LIST_FIRST(diraddhdp)) {
13445 			FREE_LOCK(ump);
13446 			error = get_parent_vp(pvp, mp, inum, locked_bp,
13447 			    diraddhdp, &unfinished, &vp);
13448 			if (error != 0)
13449 				break;
13450 			error = ffs_update(vp, 1);
13451 			vput(vp);
13452 			if (error)
13453 				break;
13454 			ACQUIRE_LOCK(ump);
13455 		}
13456 		/*
13457 		 * If we have failed to get rid of all the dependencies
13458 		 * then something is seriously wrong.
13459 		 */
13460 		if (dap == LIST_FIRST(diraddhdp)) {
13461 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13462 			panic("flush_pagedep_deps: failed to flush "
13463 			    "inodedep %p ino %ju dap %p",
13464 			    inodedep, (uintmax_t)inum, dap);
13465 		}
13466 	}
13467 	if (error)
13468 		ACQUIRE_LOCK(ump);
13469 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13470 		LIST_REMOVE(dap, da_pdlist);
13471 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13472 	}
13473 	return (error);
13474 }
13475 
13476 /*
13477  * A large burst of file addition or deletion activity can drive the
13478  * memory load excessively high. First attempt to slow things down
13479  * using the techniques below. If that fails, this routine requests
13480  * the offending operations to fall back to running synchronously
13481  * until the memory load returns to a reasonable level.
13482  */
13483 int
softdep_slowdown(struct vnode * vp)13484 softdep_slowdown(struct vnode *vp)
13485 {
13486 	struct ufsmount *ump;
13487 	int jlow;
13488 	int max_softdeps_hard;
13489 
13490 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13491 	    ("softdep_slowdown called on non-softdep filesystem"));
13492 	ump = VFSTOUFS(vp->v_mount);
13493 	ACQUIRE_LOCK(ump);
13494 	jlow = 0;
13495 	/*
13496 	 * Check for journal space if needed.
13497 	 */
13498 	if (DOINGSUJ(vp)) {
13499 		if (journal_space(ump, 0) == 0)
13500 			jlow = 1;
13501 	}
13502 	/*
13503 	 * If the system is under its limits and our filesystem is
13504 	 * not responsible for more than our share of the usage and
13505 	 * we are not low on journal space, then no need to slow down.
13506 	 */
13507 	max_softdeps_hard = max_softdeps * 11 / 10;
13508 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13509 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13510 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13511 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13512 	    ump->softdep_curdeps[D_DIRREM] <
13513 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13514 	    ump->softdep_curdeps[D_INODEDEP] <
13515 	    max_softdeps_hard / stat_flush_threads &&
13516 	    ump->softdep_curdeps[D_INDIRDEP] <
13517 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13518 	    ump->softdep_curdeps[D_FREEBLKS] <
13519 	    max_softdeps_hard / stat_flush_threads) {
13520 		FREE_LOCK(ump);
13521   		return (0);
13522 	}
13523 	/*
13524 	 * If the journal is low or our filesystem is over its limit
13525 	 * then speedup the cleanup.
13526 	 */
13527 	if (ump->softdep_curdeps[D_INDIRDEP] <
13528 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13529 		softdep_speedup(ump);
13530 	stat_sync_limit_hit += 1;
13531 	FREE_LOCK(ump);
13532 	/*
13533 	 * We only slow down the rate at which new dependencies are
13534 	 * generated if we are not using journaling. With journaling,
13535 	 * the cleanup should always be sufficient to keep things
13536 	 * under control.
13537 	 */
13538 	if (DOINGSUJ(vp))
13539 		return (0);
13540 	return (1);
13541 }
13542 
13543 static int
softdep_request_cleanup_filter(struct vnode * vp,void * arg __unused)13544 softdep_request_cleanup_filter(struct vnode *vp, void *arg __unused)
13545 {
13546 	return ((vp->v_iflag & VI_OWEINACT) != 0 && vp->v_usecount == 0 &&
13547 	    ((vp->v_vflag & VV_NOSYNC) != 0 || VTOI(vp)->i_effnlink == 0));
13548 }
13549 
13550 static void
softdep_request_cleanup_inactivate(struct mount * mp)13551 softdep_request_cleanup_inactivate(struct mount *mp)
13552 {
13553 	struct vnode *vp, *mvp;
13554 	int error;
13555 
13556 	MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, softdep_request_cleanup_filter,
13557 	    NULL) {
13558 		vholdl(vp);
13559 		vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK | LK_RETRY);
13560 		VI_LOCK(vp);
13561 		if (IS_UFS(vp) && vp->v_usecount == 0) {
13562 			while ((vp->v_iflag & VI_OWEINACT) != 0) {
13563 				error = vinactive(vp);
13564 				if (error != 0 && error != ERELOOKUP)
13565 					break;
13566 			}
13567 			atomic_add_int(&stat_delayed_inact, 1);
13568 		}
13569 		VOP_UNLOCK(vp);
13570 		vdropl(vp);
13571 	}
13572 }
13573 
13574 /*
13575  * Called by the allocation routines when they are about to fail
13576  * in the hope that we can free up the requested resource (inodes
13577  * or disk space).
13578  *
13579  * First check to see if the work list has anything on it. If it has,
13580  * clean up entries until we successfully free the requested resource.
13581  * Because this process holds inodes locked, we cannot handle any remove
13582  * requests that might block on a locked inode as that could lead to
13583  * deadlock. If the worklist yields none of the requested resource,
13584  * start syncing out vnodes to free up the needed space.
13585  */
13586 int
softdep_request_cleanup(struct fs * fs,struct vnode * vp,struct ucred * cred,int resource)13587 softdep_request_cleanup(
13588 	struct fs *fs,
13589 	struct vnode *vp,
13590 	struct ucred *cred,
13591 	int resource)
13592 {
13593 	struct ufsmount *ump;
13594 	struct mount *mp;
13595 	long starttime;
13596 	ufs2_daddr_t needed;
13597 	int error, failed_vnode;
13598 
13599 	/*
13600 	 * If we are being called because of a process doing a
13601 	 * copy-on-write, then it is not safe to process any
13602 	 * worklist items as we will recurse into the copyonwrite
13603 	 * routine.  This will result in an incoherent snapshot.
13604 	 * If the vnode that we hold is a snapshot, we must avoid
13605 	 * handling other resources that could cause deadlock.
13606 	 */
13607 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13608 		return (0);
13609 
13610 	if (resource == FLUSH_BLOCKS_WAIT)
13611 		stat_cleanup_blkrequests += 1;
13612 	else
13613 		stat_cleanup_inorequests += 1;
13614 
13615 	mp = vp->v_mount;
13616 	ump = VFSTOUFS(mp);
13617 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13618 	UFS_UNLOCK(ump);
13619 	error = ffs_update(vp, 1);
13620 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13621 		UFS_LOCK(ump);
13622 		return (0);
13623 	}
13624 	/*
13625 	 * If we are in need of resources, start by cleaning up
13626 	 * any block removals associated with our inode.
13627 	 */
13628 	ACQUIRE_LOCK(ump);
13629 	process_removes(vp);
13630 	process_truncates(vp);
13631 	FREE_LOCK(ump);
13632 	/*
13633 	 * Now clean up at least as many resources as we will need.
13634 	 *
13635 	 * When requested to clean up inodes, the number that are needed
13636 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13637 	 * plus a bit of slop (2) in case some more writers show up while
13638 	 * we are cleaning.
13639 	 *
13640 	 * When requested to free up space, the amount of space that
13641 	 * we need is enough blocks to allocate a full-sized segment
13642 	 * (fs_contigsumsize). The number of such segments that will
13643 	 * be needed is set by the number of simultaneous writers
13644 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13645 	 * writers show up while we are cleaning.
13646 	 *
13647 	 * Additionally, if we are unpriviledged and allocating space,
13648 	 * we need to ensure that we clean up enough blocks to get the
13649 	 * needed number of blocks over the threshold of the minimum
13650 	 * number of blocks required to be kept free by the filesystem
13651 	 * (fs_minfree).
13652 	 */
13653 	if (resource == FLUSH_INODES_WAIT) {
13654 		needed = vfs_mount_fetch_counter(vp->v_mount,
13655 		    MNT_COUNT_WRITEOPCOUNT) + 2;
13656 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13657 		needed = (vfs_mount_fetch_counter(vp->v_mount,
13658 		    MNT_COUNT_WRITEOPCOUNT) + 2) * fs->fs_contigsumsize;
13659 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE))
13660 			needed += fragstoblks(fs,
13661 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13662 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13663 	} else {
13664 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13665 		    resource);
13666 		UFS_LOCK(ump);
13667 		return (0);
13668 	}
13669 	starttime = time_second;
13670 retry:
13671 	if (resource == FLUSH_BLOCKS_WAIT &&
13672 	    fs->fs_cstotal.cs_nbfree <= needed)
13673 		softdep_send_speedup(ump, needed * fs->fs_bsize,
13674 		    BIO_SPEEDUP_TRIM);
13675 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13676 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13677 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13678 	    fs->fs_cstotal.cs_nifree <= needed)) {
13679 		ACQUIRE_LOCK(ump);
13680 		if (ump->softdep_on_worklist > 0 &&
13681 		    process_worklist_item(UFSTOVFS(ump),
13682 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13683 			stat_worklist_push += 1;
13684 		FREE_LOCK(ump);
13685 	}
13686 
13687 	/*
13688 	 * Check that there are vnodes pending inactivation.  As they
13689 	 * have been unlinked, inactivating them will free up their
13690 	 * inodes.
13691 	 */
13692 	ACQUIRE_LOCK(ump);
13693 	if (resource == FLUSH_INODES_WAIT &&
13694 	    fs->fs_cstotal.cs_nifree <= needed &&
13695 	    fs->fs_pendinginodes <= needed) {
13696 		if ((ump->um_softdep->sd_flags & FLUSH_DI_ACTIVE) == 0) {
13697 			ump->um_softdep->sd_flags |= FLUSH_DI_ACTIVE;
13698 			FREE_LOCK(ump);
13699 			softdep_request_cleanup_inactivate(mp);
13700 			ACQUIRE_LOCK(ump);
13701 			ump->um_softdep->sd_flags &= ~FLUSH_DI_ACTIVE;
13702 			wakeup(&ump->um_softdep->sd_flags);
13703 		} else {
13704 			while ((ump->um_softdep->sd_flags &
13705 			    FLUSH_DI_ACTIVE) != 0) {
13706 				msleep(&ump->um_softdep->sd_flags,
13707 				    LOCK_PTR(ump), PVM, "ffsvina", hz);
13708 			}
13709 		}
13710 	}
13711 	FREE_LOCK(ump);
13712 
13713 	/*
13714 	 * If we still need resources and there are no more worklist
13715 	 * entries to process to obtain them, we have to start flushing
13716 	 * the dirty vnodes to force the release of additional requests
13717 	 * to the worklist that we can then process to reap addition
13718 	 * resources. We walk the vnodes associated with the mount point
13719 	 * until we get the needed worklist requests that we can reap.
13720 	 *
13721 	 * If there are several threads all needing to clean the same
13722 	 * mount point, only one is allowed to walk the mount list.
13723 	 * When several threads all try to walk the same mount list,
13724 	 * they end up competing with each other and often end up in
13725 	 * livelock. This approach ensures that forward progress is
13726 	 * made at the cost of occational ENOSPC errors being returned
13727 	 * that might otherwise have been avoided.
13728 	 */
13729 	error = 1;
13730 	if ((resource == FLUSH_BLOCKS_WAIT &&
13731 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13732 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13733 	     fs->fs_cstotal.cs_nifree <= needed)) {
13734 		ACQUIRE_LOCK(ump);
13735 		if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13736 			ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13737 			FREE_LOCK(ump);
13738 			failed_vnode = softdep_request_cleanup_flush(mp, ump);
13739 			ACQUIRE_LOCK(ump);
13740 			ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13741 			wakeup(&ump->um_softdep->sd_flags);
13742 			FREE_LOCK(ump);
13743 			if (ump->softdep_on_worklist > 0) {
13744 				stat_cleanup_retries += 1;
13745 				if (!failed_vnode)
13746 					goto retry;
13747 			}
13748 		} else {
13749 			while ((ump->um_softdep->sd_flags &
13750 			    FLUSH_RC_ACTIVE) != 0) {
13751 				msleep(&ump->um_softdep->sd_flags,
13752 				    LOCK_PTR(ump), PVM, "ffsrca", hz);
13753 			}
13754 			FREE_LOCK(ump);
13755 			error = 0;
13756 		}
13757 		stat_cleanup_failures += 1;
13758 	}
13759 	if (time_second - starttime > stat_cleanup_high_delay)
13760 		stat_cleanup_high_delay = time_second - starttime;
13761 	UFS_LOCK(ump);
13762 	return (error);
13763 }
13764 
13765 /*
13766  * Scan the vnodes for the specified mount point flushing out any
13767  * vnodes that can be locked without waiting. Finally, try to flush
13768  * the device associated with the mount point if it can be locked
13769  * without waiting.
13770  *
13771  * We return 0 if we were able to lock every vnode in our scan.
13772  * If we had to skip one or more vnodes, we return 1.
13773  */
13774 static int
softdep_request_cleanup_flush(struct mount * mp,struct ufsmount * ump)13775 softdep_request_cleanup_flush(struct mount *mp, struct ufsmount *ump)
13776 {
13777 	struct thread *td;
13778 	struct vnode *lvp, *mvp;
13779 	int failed_vnode;
13780 
13781 	failed_vnode = 0;
13782 	td = curthread;
13783 	MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13784 		if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13785 			VI_UNLOCK(lvp);
13786 			continue;
13787 		}
13788 		if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT) != 0) {
13789 			failed_vnode = 1;
13790 			continue;
13791 		}
13792 		if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
13793 			vput(lvp);
13794 			continue;
13795 		}
13796 		(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13797 		vput(lvp);
13798 	}
13799 	lvp = ump->um_devvp;
13800 	if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13801 		VOP_FSYNC(lvp, MNT_NOWAIT, td);
13802 		VOP_UNLOCK(lvp);
13803 	}
13804 	return (failed_vnode);
13805 }
13806 
13807 static bool
softdep_excess_items(struct ufsmount * ump,int item)13808 softdep_excess_items(struct ufsmount *ump, int item)
13809 {
13810 
13811 	KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13812 	return (dep_current[item] > max_softdeps &&
13813 	    ump->softdep_curdeps[item] > max_softdeps /
13814 	    stat_flush_threads);
13815 }
13816 
13817 static void
schedule_cleanup(struct mount * mp)13818 schedule_cleanup(struct mount *mp)
13819 {
13820 	struct ufsmount *ump;
13821 	struct thread *td;
13822 
13823 	ump = VFSTOUFS(mp);
13824 	LOCK_OWNED(ump);
13825 	FREE_LOCK(ump);
13826 	td = curthread;
13827 	if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13828 	    (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13829 		/*
13830 		 * No ast is delivered to kernel threads, so nobody
13831 		 * would deref the mp.  Some kernel threads
13832 		 * explicitly check for AST, e.g. NFS daemon does
13833 		 * this in the serving loop.
13834 		 */
13835 		return;
13836 	}
13837 	if (td->td_su != NULL)
13838 		vfs_rel(td->td_su);
13839 	vfs_ref(mp);
13840 	td->td_su = mp;
13841 	thread_lock(td);
13842 	td->td_flags |= TDF_ASTPENDING;
13843 	thread_unlock(td);
13844 }
13845 
13846 static void
softdep_ast_cleanup_proc(struct thread * td)13847 softdep_ast_cleanup_proc(struct thread *td)
13848 {
13849 	struct mount *mp;
13850 	struct ufsmount *ump;
13851 	int error;
13852 	bool req;
13853 
13854 	while ((mp = td->td_su) != NULL) {
13855 		td->td_su = NULL;
13856 		error = vfs_busy(mp, MBF_NOWAIT);
13857 		vfs_rel(mp);
13858 		if (error != 0)
13859 			return;
13860 		if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13861 			ump = VFSTOUFS(mp);
13862 			for (;;) {
13863 				req = false;
13864 				ACQUIRE_LOCK(ump);
13865 				if (softdep_excess_items(ump, D_INODEDEP)) {
13866 					req = true;
13867 					request_cleanup(mp, FLUSH_INODES);
13868 				}
13869 				if (softdep_excess_items(ump, D_DIRREM)) {
13870 					req = true;
13871 					request_cleanup(mp, FLUSH_BLOCKS);
13872 				}
13873 				FREE_LOCK(ump);
13874 				if (softdep_excess_items(ump, D_NEWBLK) ||
13875 				    softdep_excess_items(ump, D_ALLOCDIRECT) ||
13876 				    softdep_excess_items(ump, D_ALLOCINDIR)) {
13877 					error = vn_start_write(NULL, &mp,
13878 					    V_WAIT);
13879 					if (error == 0) {
13880 						req = true;
13881 						VFS_SYNC(mp, MNT_WAIT);
13882 						vn_finished_write(mp);
13883 					}
13884 				}
13885 				if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13886 					break;
13887 			}
13888 		}
13889 		vfs_unbusy(mp);
13890 	}
13891 	if ((mp = td->td_su) != NULL) {
13892 		td->td_su = NULL;
13893 		vfs_rel(mp);
13894 	}
13895 }
13896 
13897 /*
13898  * If memory utilization has gotten too high, deliberately slow things
13899  * down and speed up the I/O processing.
13900  */
13901 static int
request_cleanup(struct mount * mp,int resource)13902 request_cleanup(struct mount *mp, int resource)
13903 {
13904 	struct thread *td = curthread;
13905 	struct ufsmount *ump;
13906 
13907 	ump = VFSTOUFS(mp);
13908 	LOCK_OWNED(ump);
13909 	/*
13910 	 * We never hold up the filesystem syncer or buf daemon.
13911 	 */
13912 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13913 		return (0);
13914 	/*
13915 	 * First check to see if the work list has gotten backlogged.
13916 	 * If it has, co-opt this process to help clean up two entries.
13917 	 * Because this process may hold inodes locked, we cannot
13918 	 * handle any remove requests that might block on a locked
13919 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13920 	 * to avoid recursively processing the worklist.
13921 	 */
13922 	if (ump->softdep_on_worklist > max_softdeps / 10) {
13923 		td->td_pflags |= TDP_SOFTDEP;
13924 		process_worklist_item(mp, 2, LK_NOWAIT);
13925 		td->td_pflags &= ~TDP_SOFTDEP;
13926 		stat_worklist_push += 2;
13927 		return(1);
13928 	}
13929 	/*
13930 	 * Next, we attempt to speed up the syncer process. If that
13931 	 * is successful, then we allow the process to continue.
13932 	 */
13933 	if (softdep_speedup(ump) &&
13934 	    resource != FLUSH_BLOCKS_WAIT &&
13935 	    resource != FLUSH_INODES_WAIT)
13936 		return(0);
13937 	/*
13938 	 * If we are resource constrained on inode dependencies, try
13939 	 * flushing some dirty inodes. Otherwise, we are constrained
13940 	 * by file deletions, so try accelerating flushes of directories
13941 	 * with removal dependencies. We would like to do the cleanup
13942 	 * here, but we probably hold an inode locked at this point and
13943 	 * that might deadlock against one that we try to clean. So,
13944 	 * the best that we can do is request the syncer daemon to do
13945 	 * the cleanup for us.
13946 	 */
13947 	switch (resource) {
13948 	case FLUSH_INODES:
13949 	case FLUSH_INODES_WAIT:
13950 		ACQUIRE_GBLLOCK(&lk);
13951 		stat_ino_limit_push += 1;
13952 		req_clear_inodedeps += 1;
13953 		FREE_GBLLOCK(&lk);
13954 		stat_countp = &stat_ino_limit_hit;
13955 		break;
13956 
13957 	case FLUSH_BLOCKS:
13958 	case FLUSH_BLOCKS_WAIT:
13959 		ACQUIRE_GBLLOCK(&lk);
13960 		stat_blk_limit_push += 1;
13961 		req_clear_remove += 1;
13962 		FREE_GBLLOCK(&lk);
13963 		stat_countp = &stat_blk_limit_hit;
13964 		break;
13965 
13966 	default:
13967 		panic("request_cleanup: unknown type");
13968 	}
13969 	/*
13970 	 * Hopefully the syncer daemon will catch up and awaken us.
13971 	 * We wait at most tickdelay before proceeding in any case.
13972 	 */
13973 	ACQUIRE_GBLLOCK(&lk);
13974 	FREE_LOCK(ump);
13975 	proc_waiting += 1;
13976 	if (callout_pending(&softdep_callout) == FALSE)
13977 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13978 		    pause_timer, 0);
13979 
13980 	if ((td->td_pflags & TDP_KTHREAD) == 0)
13981 		msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13982 	proc_waiting -= 1;
13983 	FREE_GBLLOCK(&lk);
13984 	ACQUIRE_LOCK(ump);
13985 	return (1);
13986 }
13987 
13988 /*
13989  * Awaken processes pausing in request_cleanup and clear proc_waiting
13990  * to indicate that there is no longer a timer running. Pause_timer
13991  * will be called with the global softdep mutex (&lk) locked.
13992  */
13993 static void
pause_timer(void * arg)13994 pause_timer(void *arg)
13995 {
13996 
13997 	GBLLOCK_OWNED(&lk);
13998 	/*
13999 	 * The callout_ API has acquired mtx and will hold it around this
14000 	 * function call.
14001 	 */
14002 	*stat_countp += proc_waiting;
14003 	wakeup(&proc_waiting);
14004 }
14005 
14006 /*
14007  * If requested, try removing inode or removal dependencies.
14008  */
14009 static void
check_clear_deps(struct mount * mp)14010 check_clear_deps(struct mount *mp)
14011 {
14012 	struct ufsmount *ump;
14013 	bool suj_susp;
14014 
14015 	/*
14016 	 * Tell the lower layers that any TRIM or WRITE transactions that have
14017 	 * been delayed for performance reasons should proceed to help alleviate
14018 	 * the shortage faster. The race between checking req_* and the softdep
14019 	 * mutex (lk) is fine since this is an advisory operation that at most
14020 	 * causes deferred work to be done sooner.
14021 	 */
14022 	ump = VFSTOUFS(mp);
14023 	suj_susp = ump->um_softdep->sd_jblocks != NULL &&
14024 	    ump->softdep_jblocks->jb_suspended;
14025 	if (req_clear_remove || req_clear_inodedeps || suj_susp) {
14026 		FREE_LOCK(ump);
14027 		softdep_send_speedup(ump, 0, BIO_SPEEDUP_TRIM | BIO_SPEEDUP_WRITE);
14028 		ACQUIRE_LOCK(ump);
14029 	}
14030 
14031 	/*
14032 	 * If we are suspended, it may be because of our using
14033 	 * too many inodedeps, so help clear them out.
14034 	 */
14035 	if (suj_susp)
14036 		clear_inodedeps(mp);
14037 
14038 	/*
14039 	 * General requests for cleanup of backed up dependencies
14040 	 */
14041 	ACQUIRE_GBLLOCK(&lk);
14042 	if (req_clear_inodedeps) {
14043 		req_clear_inodedeps -= 1;
14044 		FREE_GBLLOCK(&lk);
14045 		clear_inodedeps(mp);
14046 		ACQUIRE_GBLLOCK(&lk);
14047 		wakeup(&proc_waiting);
14048 	}
14049 	if (req_clear_remove) {
14050 		req_clear_remove -= 1;
14051 		FREE_GBLLOCK(&lk);
14052 		clear_remove(mp);
14053 		ACQUIRE_GBLLOCK(&lk);
14054 		wakeup(&proc_waiting);
14055 	}
14056 	FREE_GBLLOCK(&lk);
14057 }
14058 
14059 /*
14060  * Flush out a directory with at least one removal dependency in an effort to
14061  * reduce the number of dirrem, freefile, and freeblks dependency structures.
14062  */
14063 static void
clear_remove(struct mount * mp)14064 clear_remove(struct mount *mp)
14065 {
14066 	struct pagedep_hashhead *pagedephd;
14067 	struct pagedep *pagedep;
14068 	struct ufsmount *ump;
14069 	struct vnode *vp;
14070 	struct bufobj *bo;
14071 	int error, cnt;
14072 	ino_t ino;
14073 
14074 	ump = VFSTOUFS(mp);
14075 	LOCK_OWNED(ump);
14076 
14077 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
14078 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
14079 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
14080 			ump->pagedep_nextclean = 0;
14081 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
14082 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
14083 				continue;
14084 			ino = pagedep->pd_ino;
14085 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
14086 				continue;
14087 			FREE_LOCK(ump);
14088 
14089 			/*
14090 			 * Let unmount clear deps
14091 			 */
14092 			error = vfs_busy(mp, MBF_NOWAIT);
14093 			if (error != 0)
14094 				goto finish_write;
14095 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
14096 			     FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP);
14097 			vfs_unbusy(mp);
14098 			if (error != 0) {
14099 				softdep_error("clear_remove: vget", error);
14100 				goto finish_write;
14101 			}
14102 			MPASS(VTOI(vp)->i_mode != 0);
14103 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
14104 				softdep_error("clear_remove: fsync", error);
14105 			bo = &vp->v_bufobj;
14106 			BO_LOCK(bo);
14107 			drain_output(vp);
14108 			BO_UNLOCK(bo);
14109 			vput(vp);
14110 		finish_write:
14111 			vn_finished_write(mp);
14112 			ACQUIRE_LOCK(ump);
14113 			return;
14114 		}
14115 	}
14116 }
14117 
14118 /*
14119  * Clear out a block of dirty inodes in an effort to reduce
14120  * the number of inodedep dependency structures.
14121  */
14122 static void
clear_inodedeps(struct mount * mp)14123 clear_inodedeps(struct mount *mp)
14124 {
14125 	struct inodedep_hashhead *inodedephd;
14126 	struct inodedep *inodedep;
14127 	struct ufsmount *ump;
14128 	struct vnode *vp;
14129 	struct fs *fs;
14130 	int error, cnt;
14131 	ino_t firstino, lastino, ino;
14132 
14133 	ump = VFSTOUFS(mp);
14134 	fs = ump->um_fs;
14135 	LOCK_OWNED(ump);
14136 	/*
14137 	 * Pick a random inode dependency to be cleared.
14138 	 * We will then gather up all the inodes in its block
14139 	 * that have dependencies and flush them out.
14140 	 */
14141 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
14142 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
14143 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
14144 			ump->inodedep_nextclean = 0;
14145 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
14146 			break;
14147 	}
14148 	if (inodedep == NULL)
14149 		return;
14150 	/*
14151 	 * Find the last inode in the block with dependencies.
14152 	 */
14153 	firstino = rounddown2(inodedep->id_ino, INOPB(fs));
14154 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
14155 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
14156 			break;
14157 	/*
14158 	 * Asynchronously push all but the last inode with dependencies.
14159 	 * Synchronously push the last inode with dependencies to ensure
14160 	 * that the inode block gets written to free up the inodedeps.
14161 	 */
14162 	for (ino = firstino; ino <= lastino; ino++) {
14163 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
14164 			continue;
14165 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
14166 			continue;
14167 		FREE_LOCK(ump);
14168 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
14169 		if (error != 0) {
14170 			vn_finished_write(mp);
14171 			ACQUIRE_LOCK(ump);
14172 			return;
14173 		}
14174 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
14175 		    FFSV_FORCEINSMQ | FFSV_FORCEINODEDEP)) != 0) {
14176 			softdep_error("clear_inodedeps: vget", error);
14177 			vfs_unbusy(mp);
14178 			vn_finished_write(mp);
14179 			ACQUIRE_LOCK(ump);
14180 			return;
14181 		}
14182 		vfs_unbusy(mp);
14183 		if (VTOI(vp)->i_mode == 0) {
14184 			vgone(vp);
14185 		} else if (ino == lastino) {
14186 			do {
14187 				error = ffs_syncvnode(vp, MNT_WAIT, 0);
14188 			} while (error == ERELOOKUP);
14189 			if (error != 0)
14190 				softdep_error("clear_inodedeps: fsync1", error);
14191 		} else {
14192 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
14193 				softdep_error("clear_inodedeps: fsync2", error);
14194 			BO_LOCK(&vp->v_bufobj);
14195 			drain_output(vp);
14196 			BO_UNLOCK(&vp->v_bufobj);
14197 		}
14198 		vput(vp);
14199 		vn_finished_write(mp);
14200 		ACQUIRE_LOCK(ump);
14201 	}
14202 }
14203 
14204 void
softdep_buf_append(struct buf * bp,struct workhead * wkhd)14205 softdep_buf_append(struct buf *bp, struct workhead *wkhd)
14206 {
14207 	struct worklist *wk;
14208 	struct ufsmount *ump;
14209 
14210 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14211 		return;
14212 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14213 	    ("softdep_buf_append called on non-softdep filesystem"));
14214 	ump = VFSTOUFS(wk->wk_mp);
14215 	ACQUIRE_LOCK(ump);
14216 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
14217 		WORKLIST_REMOVE(wk);
14218 		WORKLIST_INSERT(&bp->b_dep, wk);
14219 	}
14220 	FREE_LOCK(ump);
14221 
14222 }
14223 
14224 void
softdep_inode_append(struct inode * ip,struct ucred * cred,struct workhead * wkhd)14225 softdep_inode_append(
14226 	struct inode *ip,
14227 	struct ucred *cred,
14228 	struct workhead *wkhd)
14229 {
14230 	struct buf *bp;
14231 	struct fs *fs;
14232 	struct ufsmount *ump;
14233 	int error;
14234 
14235 	ump = ITOUMP(ip);
14236 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
14237 	    ("softdep_inode_append called on non-softdep filesystem"));
14238 	fs = ump->um_fs;
14239 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
14240 	    (int)fs->fs_bsize, cred, &bp);
14241 	if (error) {
14242 		bqrelse(bp);
14243 		softdep_freework(wkhd);
14244 		return;
14245 	}
14246 	softdep_buf_append(bp, wkhd);
14247 	bqrelse(bp);
14248 }
14249 
14250 void
softdep_freework(struct workhead * wkhd)14251 softdep_freework(struct workhead *wkhd)
14252 {
14253 	struct worklist *wk;
14254 	struct ufsmount *ump;
14255 
14256 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14257 		return;
14258 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14259 	    ("softdep_freework called on non-softdep filesystem"));
14260 	ump = VFSTOUFS(wk->wk_mp);
14261 	ACQUIRE_LOCK(ump);
14262 	handle_jwork(wkhd);
14263 	FREE_LOCK(ump);
14264 }
14265 
14266 static struct ufsmount *
softdep_bp_to_mp(struct buf * bp)14267 softdep_bp_to_mp(struct buf *bp)
14268 {
14269 	struct mount *mp;
14270 	struct vnode *vp;
14271 
14272 	if (LIST_EMPTY(&bp->b_dep))
14273 		return (NULL);
14274 	vp = bp->b_vp;
14275 	KASSERT(vp != NULL,
14276 	    ("%s, buffer with dependencies lacks vnode", __func__));
14277 
14278 	/*
14279 	 * The ump mount point is stable after we get a correct
14280 	 * pointer, since bp is locked and this prevents unmount from
14281 	 * proceeding.  But to get to it, we cannot dereference bp->b_dep
14282 	 * head wk_mp, because we do not yet own SU ump lock and
14283 	 * workitem might be freed while dereferenced.
14284 	 */
14285 retry:
14286 	switch (vp->v_type) {
14287 	case VCHR:
14288 		VI_LOCK(vp);
14289 		mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
14290 		VI_UNLOCK(vp);
14291 		if (mp == NULL)
14292 			goto retry;
14293 		break;
14294 	case VREG:
14295 	case VDIR:
14296 	case VLNK:
14297 	case VFIFO:
14298 	case VSOCK:
14299 		mp = vp->v_mount;
14300 		break;
14301 	case VBLK:
14302 		vn_printf(vp, "softdep_bp_to_mp: unexpected block device\n");
14303 		/* FALLTHROUGH */
14304 	case VNON:
14305 	case VBAD:
14306 	case VMARKER:
14307 		mp = NULL;
14308 		break;
14309 	default:
14310 		vn_printf(vp, "unknown vnode type");
14311 		mp = NULL;
14312 		break;
14313 	}
14314 	return (VFSTOUFS(mp));
14315 }
14316 
14317 /*
14318  * Function to determine if the buffer has outstanding dependencies
14319  * that will cause a roll-back if the buffer is written. If wantcount
14320  * is set, return number of dependencies, otherwise just yes or no.
14321  */
14322 static int
softdep_count_dependencies(struct buf * bp,int wantcount)14323 softdep_count_dependencies(struct buf *bp, int wantcount)
14324 {
14325 	struct worklist *wk;
14326 	struct ufsmount *ump;
14327 	struct bmsafemap *bmsafemap;
14328 	struct freework *freework;
14329 	struct inodedep *inodedep;
14330 	struct indirdep *indirdep;
14331 	struct freeblks *freeblks;
14332 	struct allocindir *aip;
14333 	struct pagedep *pagedep;
14334 	struct dirrem *dirrem;
14335 	struct newblk *newblk;
14336 	struct mkdir *mkdir;
14337 	struct diradd *dap;
14338 	int i, retval;
14339 
14340 	ump = softdep_bp_to_mp(bp);
14341 	if (ump == NULL)
14342 		return (0);
14343 	retval = 0;
14344 	ACQUIRE_LOCK(ump);
14345 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14346 		switch (wk->wk_type) {
14347 		case D_INODEDEP:
14348 			inodedep = WK_INODEDEP(wk);
14349 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14350 				/* bitmap allocation dependency */
14351 				retval += 1;
14352 				if (!wantcount)
14353 					goto out;
14354 			}
14355 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14356 				/* direct block pointer dependency */
14357 				retval += 1;
14358 				if (!wantcount)
14359 					goto out;
14360 			}
14361 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14362 				/* direct block pointer dependency */
14363 				retval += 1;
14364 				if (!wantcount)
14365 					goto out;
14366 			}
14367 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14368 				/* Add reference dependency. */
14369 				retval += 1;
14370 				if (!wantcount)
14371 					goto out;
14372 			}
14373 			continue;
14374 
14375 		case D_INDIRDEP:
14376 			indirdep = WK_INDIRDEP(wk);
14377 
14378 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14379 				/* indirect truncation dependency */
14380 				retval += 1;
14381 				if (!wantcount)
14382 					goto out;
14383 			}
14384 
14385 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14386 				/* indirect block pointer dependency */
14387 				retval += 1;
14388 				if (!wantcount)
14389 					goto out;
14390 			}
14391 			continue;
14392 
14393 		case D_PAGEDEP:
14394 			pagedep = WK_PAGEDEP(wk);
14395 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14396 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14397 					/* Journal remove ref dependency. */
14398 					retval += 1;
14399 					if (!wantcount)
14400 						goto out;
14401 				}
14402 			}
14403 			for (i = 0; i < DAHASHSZ; i++) {
14404 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14405 					/* directory entry dependency */
14406 					retval += 1;
14407 					if (!wantcount)
14408 						goto out;
14409 				}
14410 			}
14411 			continue;
14412 
14413 		case D_BMSAFEMAP:
14414 			bmsafemap = WK_BMSAFEMAP(wk);
14415 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14416 				/* Add reference dependency. */
14417 				retval += 1;
14418 				if (!wantcount)
14419 					goto out;
14420 			}
14421 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14422 				/* Allocate block dependency. */
14423 				retval += 1;
14424 				if (!wantcount)
14425 					goto out;
14426 			}
14427 			continue;
14428 
14429 		case D_FREEBLKS:
14430 			freeblks = WK_FREEBLKS(wk);
14431 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14432 				/* Freeblk journal dependency. */
14433 				retval += 1;
14434 				if (!wantcount)
14435 					goto out;
14436 			}
14437 			continue;
14438 
14439 		case D_ALLOCDIRECT:
14440 		case D_ALLOCINDIR:
14441 			newblk = WK_NEWBLK(wk);
14442 			if (newblk->nb_jnewblk) {
14443 				/* Journal allocate dependency. */
14444 				retval += 1;
14445 				if (!wantcount)
14446 					goto out;
14447 			}
14448 			continue;
14449 
14450 		case D_MKDIR:
14451 			mkdir = WK_MKDIR(wk);
14452 			if (mkdir->md_jaddref) {
14453 				/* Journal reference dependency. */
14454 				retval += 1;
14455 				if (!wantcount)
14456 					goto out;
14457 			}
14458 			continue;
14459 
14460 		case D_FREEWORK:
14461 		case D_FREEDEP:
14462 		case D_JSEGDEP:
14463 		case D_JSEG:
14464 		case D_SBDEP:
14465 			/* never a dependency on these blocks */
14466 			continue;
14467 
14468 		default:
14469 			panic("softdep_count_dependencies: Unexpected type %s",
14470 			    TYPENAME(wk->wk_type));
14471 			/* NOTREACHED */
14472 		}
14473 	}
14474 out:
14475 	FREE_LOCK(ump);
14476 	return (retval);
14477 }
14478 
14479 /*
14480  * Acquire exclusive access to a buffer.
14481  * Must be called with a locked mtx parameter.
14482  * Return acquired buffer or NULL on failure.
14483  */
14484 static struct buf *
getdirtybuf(struct buf * bp,struct rwlock * lock,int waitfor)14485 getdirtybuf(struct buf *bp,
14486 	struct rwlock *lock,
14487 	int waitfor)
14488 {
14489 	int error;
14490 
14491 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14492 		if (waitfor != MNT_WAIT)
14493 			return (NULL);
14494 		error = BUF_LOCK(bp,
14495 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14496 		/*
14497 		 * Even if we successfully acquire bp here, we have dropped
14498 		 * lock, which may violates our guarantee.
14499 		 */
14500 		if (error == 0)
14501 			BUF_UNLOCK(bp);
14502 		else if (error != ENOLCK)
14503 			panic("getdirtybuf: inconsistent lock: %d", error);
14504 		rw_wlock(lock);
14505 		return (NULL);
14506 	}
14507 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14508 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14509 			rw_wunlock(lock);
14510 			BO_LOCK(bp->b_bufobj);
14511 			BUF_UNLOCK(bp);
14512 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14513 				bp->b_vflags |= BV_BKGRDWAIT;
14514 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14515 				       PRIBIO | PDROP, "getbuf", 0);
14516 			} else
14517 				BO_UNLOCK(bp->b_bufobj);
14518 			rw_wlock(lock);
14519 			return (NULL);
14520 		}
14521 		BUF_UNLOCK(bp);
14522 		if (waitfor != MNT_WAIT)
14523 			return (NULL);
14524 #ifdef DEBUG_VFS_LOCKS
14525 		if (bp->b_vp->v_type != VCHR)
14526 			ASSERT_BO_WLOCKED(bp->b_bufobj);
14527 #endif
14528 		bp->b_vflags |= BV_BKGRDWAIT;
14529 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14530 		return (NULL);
14531 	}
14532 	if ((bp->b_flags & B_DELWRI) == 0) {
14533 		BUF_UNLOCK(bp);
14534 		return (NULL);
14535 	}
14536 	bremfree(bp);
14537 	return (bp);
14538 }
14539 
14540 /*
14541  * Check if it is safe to suspend the file system now.  On entry,
14542  * the vnode interlock for devvp should be held.  Return 0 with
14543  * the mount interlock held if the file system can be suspended now,
14544  * otherwise return EAGAIN with the mount interlock held.
14545  */
14546 int
softdep_check_suspend(struct mount * mp,struct vnode * devvp,int softdep_depcnt,int softdep_accdepcnt,int secondary_writes,int secondary_accwrites)14547 softdep_check_suspend(struct mount *mp,
14548 		      struct vnode *devvp,
14549 		      int softdep_depcnt,
14550 		      int softdep_accdepcnt,
14551 		      int secondary_writes,
14552 		      int secondary_accwrites)
14553 {
14554 	struct buf *bp;
14555 	struct bufobj *bo;
14556 	struct ufsmount *ump;
14557 	struct inodedep *inodedep;
14558 	struct indirdep *indirdep;
14559 	struct worklist *wk, *nextwk;
14560 	int error, unlinked;
14561 
14562 	bo = &devvp->v_bufobj;
14563 	ASSERT_BO_WLOCKED(bo);
14564 
14565 	/*
14566 	 * If we are not running with soft updates, then we need only
14567 	 * deal with secondary writes as we try to suspend.
14568 	 */
14569 	if (MOUNTEDSOFTDEP(mp) == 0) {
14570 		MNT_ILOCK(mp);
14571 		while (mp->mnt_secondary_writes != 0) {
14572 			BO_UNLOCK(bo);
14573 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14574 			    (PUSER - 1) | PDROP, "secwr", 0);
14575 			BO_LOCK(bo);
14576 			MNT_ILOCK(mp);
14577 		}
14578 
14579 		/*
14580 		 * Reasons for needing more work before suspend:
14581 		 * - Dirty buffers on devvp.
14582 		 * - Secondary writes occurred after start of vnode sync loop
14583 		 */
14584 		error = 0;
14585 		if (bo->bo_numoutput > 0 ||
14586 		    bo->bo_dirty.bv_cnt > 0 ||
14587 		    secondary_writes != 0 ||
14588 		    mp->mnt_secondary_writes != 0 ||
14589 		    secondary_accwrites != mp->mnt_secondary_accwrites)
14590 			error = EAGAIN;
14591 		BO_UNLOCK(bo);
14592 		return (error);
14593 	}
14594 
14595 	/*
14596 	 * If we are running with soft updates, then we need to coordinate
14597 	 * with them as we try to suspend.
14598 	 */
14599 	ump = VFSTOUFS(mp);
14600 	for (;;) {
14601 		if (!TRY_ACQUIRE_LOCK(ump)) {
14602 			BO_UNLOCK(bo);
14603 			ACQUIRE_LOCK(ump);
14604 			FREE_LOCK(ump);
14605 			BO_LOCK(bo);
14606 			continue;
14607 		}
14608 		MNT_ILOCK(mp);
14609 		if (mp->mnt_secondary_writes != 0) {
14610 			FREE_LOCK(ump);
14611 			BO_UNLOCK(bo);
14612 			msleep(&mp->mnt_secondary_writes,
14613 			       MNT_MTX(mp),
14614 			       (PUSER - 1) | PDROP, "secwr", 0);
14615 			BO_LOCK(bo);
14616 			continue;
14617 		}
14618 		break;
14619 	}
14620 
14621 	unlinked = 0;
14622 	if (MOUNTEDSUJ(mp)) {
14623 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14624 		    inodedep != NULL;
14625 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14626 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14627 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14628 			    UNLINKONLIST) ||
14629 			    !check_inodedep_free(inodedep))
14630 				continue;
14631 			unlinked++;
14632 		}
14633 	}
14634 
14635 	/*
14636 	 * XXX Check for orphaned indirdep dependency structures.
14637 	 *
14638 	 * During forcible unmount after a disk failure there is a
14639 	 * bug that causes one or more indirdep dependency structures
14640 	 * to fail to be deallocated. We check for them here and clean
14641 	 * them up so that the unmount can succeed.
14642 	 */
14643 	if ((ump->um_flags & UM_FSFAIL_CLEANUP) != 0 && ump->softdep_deps > 0 &&
14644 	    ump->softdep_deps == ump->softdep_curdeps[D_INDIRDEP]) {
14645 		LIST_FOREACH_SAFE(wk, &ump->softdep_alldeps[D_INDIRDEP],
14646 		    wk_all, nextwk) {
14647 			indirdep = WK_INDIRDEP(wk);
14648 			if ((indirdep->ir_state & (GOINGAWAY | DEPCOMPLETE)) !=
14649 			    (GOINGAWAY | DEPCOMPLETE) ||
14650 			    !TAILQ_EMPTY(&indirdep->ir_trunc) ||
14651 			    !LIST_EMPTY(&indirdep->ir_completehd) ||
14652 			    !LIST_EMPTY(&indirdep->ir_writehd) ||
14653 			    !LIST_EMPTY(&indirdep->ir_donehd) ||
14654 			    !LIST_EMPTY(&indirdep->ir_deplisthd) ||
14655 			    indirdep->ir_saveddata != NULL ||
14656 			    indirdep->ir_savebp == NULL) {
14657 				printf("%s: skipping orphaned indirdep %p\n",
14658 				    __FUNCTION__, indirdep);
14659 				continue;
14660 			}
14661 			printf("%s: freeing orphaned indirdep %p\n",
14662 			    __FUNCTION__, indirdep);
14663 			bp = indirdep->ir_savebp;
14664 			indirdep->ir_savebp = NULL;
14665 			free_indirdep(indirdep);
14666 			FREE_LOCK(ump);
14667 			brelse(bp);
14668 			while (!TRY_ACQUIRE_LOCK(ump)) {
14669 				BO_UNLOCK(bo);
14670 				ACQUIRE_LOCK(ump);
14671 				FREE_LOCK(ump);
14672 				BO_LOCK(bo);
14673 			}
14674 		}
14675 	}
14676 
14677 	/*
14678 	 * Reasons for needing more work before suspend:
14679 	 * - Dirty buffers on devvp.
14680 	 * - Dependency structures still exist
14681 	 * - Softdep activity occurred after start of vnode sync loop
14682 	 * - Secondary writes occurred after start of vnode sync loop
14683 	 */
14684 	error = 0;
14685 	if (bo->bo_numoutput > 0 ||
14686 	    bo->bo_dirty.bv_cnt > 0 ||
14687 	    softdep_depcnt != unlinked ||
14688 	    ump->softdep_deps != unlinked ||
14689 	    softdep_accdepcnt != ump->softdep_accdeps ||
14690 	    secondary_writes != 0 ||
14691 	    mp->mnt_secondary_writes != 0 ||
14692 	    secondary_accwrites != mp->mnt_secondary_accwrites)
14693 		error = EAGAIN;
14694 	FREE_LOCK(ump);
14695 	BO_UNLOCK(bo);
14696 	return (error);
14697 }
14698 
14699 /*
14700  * Get the number of dependency structures for the file system, both
14701  * the current number and the total number allocated.  These will
14702  * later be used to detect that softdep processing has occurred.
14703  */
14704 void
softdep_get_depcounts(struct mount * mp,int * softdep_depsp,int * softdep_accdepsp)14705 softdep_get_depcounts(struct mount *mp,
14706 		      int *softdep_depsp,
14707 		      int *softdep_accdepsp)
14708 {
14709 	struct ufsmount *ump;
14710 
14711 	if (MOUNTEDSOFTDEP(mp) == 0) {
14712 		*softdep_depsp = 0;
14713 		*softdep_accdepsp = 0;
14714 		return;
14715 	}
14716 	ump = VFSTOUFS(mp);
14717 	ACQUIRE_LOCK(ump);
14718 	*softdep_depsp = ump->softdep_deps;
14719 	*softdep_accdepsp = ump->softdep_accdeps;
14720 	FREE_LOCK(ump);
14721 }
14722 
14723 /*
14724  * Wait for pending output on a vnode to complete.
14725  */
14726 static void
drain_output(struct vnode * vp)14727 drain_output(struct vnode *vp)
14728 {
14729 
14730 	ASSERT_VOP_LOCKED(vp, "drain_output");
14731 	(void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14732 }
14733 
14734 /*
14735  * Called whenever a buffer that is being invalidated or reallocated
14736  * contains dependencies. This should only happen if an I/O error has
14737  * occurred. The routine is called with the buffer locked.
14738  */
14739 static void
softdep_deallocate_dependencies(struct buf * bp)14740 softdep_deallocate_dependencies(struct buf *bp)
14741 {
14742 
14743 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14744 		panic("softdep_deallocate_dependencies: dangling deps");
14745 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14746 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14747 	else
14748 		printf("softdep_deallocate_dependencies: "
14749 		    "got error %d while accessing filesystem\n", bp->b_error);
14750 	if (bp->b_error != ENXIO)
14751 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14752 }
14753 
14754 /*
14755  * Function to handle asynchronous write errors in the filesystem.
14756  */
14757 static void
softdep_error(char * func,int error)14758 softdep_error(char *func, int error)
14759 {
14760 
14761 	/* XXX should do something better! */
14762 	printf("%s: got error %d while accessing filesystem\n", func, error);
14763 }
14764 
14765 #ifdef DDB
14766 
14767 /* exported to ffs_vfsops.c */
14768 extern void db_print_ffs(struct ufsmount *ump);
14769 void
db_print_ffs(struct ufsmount * ump)14770 db_print_ffs(struct ufsmount *ump)
14771 {
14772 	db_printf("mp %p (%s) devvp %p\n", ump->um_mountp,
14773 	    ump->um_mountp->mnt_stat.f_mntonname, ump->um_devvp);
14774 	db_printf("    fs %p ", ump->um_fs);
14775 
14776 	if (ump->um_softdep != NULL) {
14777 		db_printf("su_wl %d su_deps %d su_req %d\n",
14778 		    ump->softdep_on_worklist, ump->softdep_deps,
14779 		    ump->softdep_req);
14780 	} else {
14781 		db_printf("su disabled\n");
14782 	}
14783 }
14784 
14785 static void
worklist_print(struct worklist * wk,int verbose)14786 worklist_print(struct worklist *wk, int verbose)
14787 {
14788 
14789 	if (!verbose) {
14790 		db_printf("%s: %p state 0x%b\n", TYPENAME(wk->wk_type), wk,
14791 		    wk->wk_state, PRINT_SOFTDEP_FLAGS);
14792 		return;
14793 	}
14794 	db_printf("worklist: %p type %s state 0x%b next %p\n    ", wk,
14795 	    TYPENAME(wk->wk_type), wk->wk_state, PRINT_SOFTDEP_FLAGS,
14796 	    LIST_NEXT(wk, wk_list));
14797 	db_print_ffs(VFSTOUFS(wk->wk_mp));
14798 }
14799 
14800 static void
inodedep_print(struct inodedep * inodedep,int verbose)14801 inodedep_print(struct inodedep *inodedep, int verbose)
14802 {
14803 
14804 	worklist_print(&inodedep->id_list, 0);
14805 	db_printf("    fs %p ino %jd inoblk %jd delta %jd nlink %jd\n",
14806 	    inodedep->id_fs,
14807 	    (intmax_t)inodedep->id_ino,
14808 	    (intmax_t)fsbtodb(inodedep->id_fs,
14809 	        ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14810 	    (intmax_t)inodedep->id_nlinkdelta,
14811 	    (intmax_t)inodedep->id_savednlink);
14812 
14813 	if (verbose == 0)
14814 		return;
14815 
14816 	db_printf("    bmsafemap %p, mkdiradd %p, inoreflst %p\n",
14817 	    inodedep->id_bmsafemap,
14818 	    inodedep->id_mkdiradd,
14819 	    TAILQ_FIRST(&inodedep->id_inoreflst));
14820 	db_printf("    dirremhd %p, pendinghd %p, bufwait %p\n",
14821 	    LIST_FIRST(&inodedep->id_dirremhd),
14822 	    LIST_FIRST(&inodedep->id_pendinghd),
14823 	    LIST_FIRST(&inodedep->id_bufwait));
14824 	db_printf("    inowait %p, inoupdt %p, newinoupdt %p\n",
14825 	    LIST_FIRST(&inodedep->id_inowait),
14826 	    TAILQ_FIRST(&inodedep->id_inoupdt),
14827 	    TAILQ_FIRST(&inodedep->id_newinoupdt));
14828 	db_printf("    extupdt %p, newextupdt %p, freeblklst %p\n",
14829 	    TAILQ_FIRST(&inodedep->id_extupdt),
14830 	    TAILQ_FIRST(&inodedep->id_newextupdt),
14831 	    TAILQ_FIRST(&inodedep->id_freeblklst));
14832 	db_printf("    saveino %p, savedsize %jd, savedextsize %jd\n",
14833 	    inodedep->id_savedino1,
14834 	    (intmax_t)inodedep->id_savedsize,
14835 	    (intmax_t)inodedep->id_savedextsize);
14836 }
14837 
14838 static void
newblk_print(struct newblk * nbp)14839 newblk_print(struct newblk *nbp)
14840 {
14841 
14842 	worklist_print(&nbp->nb_list, 0);
14843 	db_printf("    newblkno %jd\n", (intmax_t)nbp->nb_newblkno);
14844 	db_printf("    jnewblk %p, bmsafemap %p, freefrag %p\n",
14845 	    &nbp->nb_jnewblk,
14846 	    &nbp->nb_bmsafemap,
14847 	    &nbp->nb_freefrag);
14848 	db_printf("    indirdeps %p, newdirblk %p, jwork %p\n",
14849 	    LIST_FIRST(&nbp->nb_indirdeps),
14850 	    LIST_FIRST(&nbp->nb_newdirblk),
14851 	    LIST_FIRST(&nbp->nb_jwork));
14852 }
14853 
14854 static void
allocdirect_print(struct allocdirect * adp)14855 allocdirect_print(struct allocdirect *adp)
14856 {
14857 
14858 	newblk_print(&adp->ad_block);
14859 	db_printf("    oldblkno %jd, oldsize %ld, newsize %ld\n",
14860 	    adp->ad_oldblkno, adp->ad_oldsize, adp->ad_newsize);
14861 	db_printf("    offset %d, inodedep %p\n",
14862 	    adp->ad_offset, adp->ad_inodedep);
14863 }
14864 
14865 static void
allocindir_print(struct allocindir * aip)14866 allocindir_print(struct allocindir *aip)
14867 {
14868 
14869 	newblk_print(&aip->ai_block);
14870 	db_printf("    oldblkno %jd, lbn %jd\n",
14871 	    (intmax_t)aip->ai_oldblkno, (intmax_t)aip->ai_lbn);
14872 	db_printf("    offset %d, indirdep %p\n",
14873 	    aip->ai_offset, aip->ai_indirdep);
14874 }
14875 
14876 static void
mkdir_print(struct mkdir * mkdir)14877 mkdir_print(struct mkdir *mkdir)
14878 {
14879 
14880 	worklist_print(&mkdir->md_list, 0);
14881 	db_printf("    diradd %p, jaddref %p, buf %p\n",
14882 		mkdir->md_diradd, mkdir->md_jaddref, mkdir->md_buf);
14883 }
14884 
DB_SHOW_COMMAND(sd_inodedep,db_show_sd_inodedep)14885 DB_SHOW_COMMAND(sd_inodedep, db_show_sd_inodedep)
14886 {
14887 
14888 	if (have_addr == 0) {
14889 		db_printf("inodedep address required\n");
14890 		return;
14891 	}
14892 	inodedep_print((struct inodedep*)addr, 1);
14893 }
14894 
DB_SHOW_COMMAND(sd_allinodedeps,db_show_sd_allinodedeps)14895 DB_SHOW_COMMAND(sd_allinodedeps, db_show_sd_allinodedeps)
14896 {
14897 	struct inodedep_hashhead *inodedephd;
14898 	struct inodedep *inodedep;
14899 	struct ufsmount *ump;
14900 	int cnt;
14901 
14902 	if (have_addr == 0) {
14903 		db_printf("ufsmount address required\n");
14904 		return;
14905 	}
14906 	ump = (struct ufsmount *)addr;
14907 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14908 		inodedephd = &ump->inodedep_hashtbl[cnt];
14909 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
14910 			inodedep_print(inodedep, 0);
14911 		}
14912 	}
14913 }
14914 
DB_SHOW_COMMAND(sd_worklist,db_show_sd_worklist)14915 DB_SHOW_COMMAND(sd_worklist, db_show_sd_worklist)
14916 {
14917 
14918 	if (have_addr == 0) {
14919 		db_printf("worklist address required\n");
14920 		return;
14921 	}
14922 	worklist_print((struct worklist *)addr, 1);
14923 }
14924 
DB_SHOW_COMMAND(sd_workhead,db_show_sd_workhead)14925 DB_SHOW_COMMAND(sd_workhead, db_show_sd_workhead)
14926 {
14927 	struct worklist *wk;
14928 	struct workhead *wkhd;
14929 
14930 	if (have_addr == 0) {
14931 		db_printf("worklist address required "
14932 		    "(for example value in bp->b_dep)\n");
14933 		return;
14934 	}
14935 	/*
14936 	 * We often do not have the address of the worklist head but
14937 	 * instead a pointer to its first entry (e.g., we have the
14938 	 * contents of bp->b_dep rather than &bp->b_dep). But the back
14939 	 * pointer of bp->b_dep will point at the head of the list, so
14940 	 * we cheat and use that instead. If we are in the middle of
14941 	 * a list we will still get the same result, so nothing
14942 	 * unexpected will result.
14943 	 */
14944 	wk = (struct worklist *)addr;
14945 	if (wk == NULL)
14946 		return;
14947 	wkhd = (struct workhead *)wk->wk_list.le_prev;
14948 	LIST_FOREACH(wk, wkhd, wk_list) {
14949 		switch(wk->wk_type) {
14950 		case D_INODEDEP:
14951 			inodedep_print(WK_INODEDEP(wk), 0);
14952 			continue;
14953 		case D_ALLOCDIRECT:
14954 			allocdirect_print(WK_ALLOCDIRECT(wk));
14955 			continue;
14956 		case D_ALLOCINDIR:
14957 			allocindir_print(WK_ALLOCINDIR(wk));
14958 			continue;
14959 		case D_MKDIR:
14960 			mkdir_print(WK_MKDIR(wk));
14961 			continue;
14962 		default:
14963 			worklist_print(wk, 0);
14964 			continue;
14965 		}
14966 	}
14967 }
14968 
DB_SHOW_COMMAND(sd_mkdir,db_show_sd_mkdir)14969 DB_SHOW_COMMAND(sd_mkdir, db_show_sd_mkdir)
14970 {
14971 	if (have_addr == 0) {
14972 		db_printf("mkdir address required\n");
14973 		return;
14974 	}
14975 	mkdir_print((struct mkdir *)addr);
14976 }
14977 
DB_SHOW_COMMAND(sd_mkdir_list,db_show_sd_mkdir_list)14978 DB_SHOW_COMMAND(sd_mkdir_list, db_show_sd_mkdir_list)
14979 {
14980 	struct mkdirlist *mkdirlisthd;
14981 	struct mkdir *mkdir;
14982 
14983 	if (have_addr == 0) {
14984 		db_printf("mkdir listhead address required\n");
14985 		return;
14986 	}
14987 	mkdirlisthd = (struct mkdirlist *)addr;
14988 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14989 		mkdir_print(mkdir);
14990 		if (mkdir->md_diradd != NULL) {
14991 			db_printf("    ");
14992 			worklist_print(&mkdir->md_diradd->da_list, 0);
14993 		}
14994 		if (mkdir->md_jaddref != NULL) {
14995 			db_printf("    ");
14996 			worklist_print(&mkdir->md_jaddref->ja_list, 0);
14997 		}
14998 	}
14999 }
15000 
DB_SHOW_COMMAND(sd_allocdirect,db_show_sd_allocdirect)15001 DB_SHOW_COMMAND(sd_allocdirect, db_show_sd_allocdirect)
15002 {
15003 	if (have_addr == 0) {
15004 		db_printf("allocdirect address required\n");
15005 		return;
15006 	}
15007 	allocdirect_print((struct allocdirect *)addr);
15008 }
15009 
DB_SHOW_COMMAND(sd_allocindir,db_show_sd_allocindir)15010 DB_SHOW_COMMAND(sd_allocindir, db_show_sd_allocindir)
15011 {
15012 	if (have_addr == 0) {
15013 		db_printf("allocindir address required\n");
15014 		return;
15015 	}
15016 	allocindir_print((struct allocindir *)addr);
15017 }
15018 
15019 #endif /* DDB */
15020 
15021 #endif /* SOFTUPDATES */
15022