]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/ufs/ffs/ffs_inode.c
dts: Import DTS for arm64
[FreeBSD/FreeBSD.git] / sys / ufs / ffs / ffs_inode.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *      @(#)ffs_inode.c 8.13 (Berkeley) 4/21/95
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include "opt_quota.h"
38
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/bio.h>
42 #include <sys/buf.h>
43 #include <sys/malloc.h>
44 #include <sys/mount.h>
45 #include <sys/proc.h>
46 #include <sys/racct.h>
47 #include <sys/random.h>
48 #include <sys/resourcevar.h>
49 #include <sys/rwlock.h>
50 #include <sys/stat.h>
51 #include <sys/vmmeter.h>
52 #include <sys/vnode.h>
53
54 #include <vm/vm.h>
55 #include <vm/vm_extern.h>
56 #include <vm/vm_object.h>
57
58 #include <ufs/ufs/extattr.h>
59 #include <ufs/ufs/quota.h>
60 #include <ufs/ufs/ufsmount.h>
61 #include <ufs/ufs/inode.h>
62 #include <ufs/ufs/ufs_extern.h>
63
64 #include <ufs/ffs/fs.h>
65 #include <ufs/ffs/ffs_extern.h>
66
67 static int ffs_indirtrunc(struct inode *, ufs2_daddr_t, ufs2_daddr_t,
68             ufs2_daddr_t, int, ufs2_daddr_t *);
69
70 /*
71  * Update the access, modified, and inode change times as specified by the
72  * IN_ACCESS, IN_UPDATE, and IN_CHANGE flags respectively.  Write the inode
73  * to disk if the IN_MODIFIED flag is set (it may be set initially, or by
74  * the timestamp update).  The IN_LAZYMOD flag is set to force a write
75  * later if not now.  The IN_LAZYACCESS is set instead of IN_MODIFIED if the fs
76  * is currently being suspended (or is suspended) and vnode has been accessed.
77  * If we write now, then clear IN_MODIFIED, IN_LAZYACCESS and IN_LAZYMOD to
78  * reflect the presumably successful write, and if waitfor is set, then wait
79  * for the write to complete.
80  */
81 int
82 ffs_update(vp, waitfor)
83         struct vnode *vp;
84         int waitfor;
85 {
86         struct fs *fs;
87         struct buf *bp;
88         struct inode *ip;
89         int flags, error;
90
91         ASSERT_VOP_ELOCKED(vp, "ffs_update");
92         ufs_itimes(vp);
93         ip = VTOI(vp);
94         if ((ip->i_flag & IN_MODIFIED) == 0 && waitfor == 0)
95                 return (0);
96         ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
97         fs = ITOFS(ip);
98         if (fs->fs_ronly && ITOUMP(ip)->um_fsckpid == 0)
99                 return (0);
100         /*
101          * If we are updating a snapshot and another process is currently
102          * writing the buffer containing the inode for this snapshot then
103          * a deadlock can occur when it tries to check the snapshot to see
104          * if that block needs to be copied. Thus when updating a snapshot
105          * we check to see if the buffer is already locked, and if it is
106          * we drop the snapshot lock until the buffer has been written
107          * and is available to us. We have to grab a reference to the
108          * snapshot vnode to prevent it from being removed while we are
109          * waiting for the buffer.
110          */
111         flags = 0;
112         if (IS_SNAPSHOT(ip))
113                 flags = GB_LOCK_NOWAIT;
114 loop:
115         error = bread_gb(ITODEVVP(ip),
116              fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
117              (int) fs->fs_bsize, NOCRED, flags, &bp);
118         if (error != 0) {
119                 if (error != EBUSY)
120                         return (error);
121                 KASSERT((IS_SNAPSHOT(ip)), ("EBUSY from non-snapshot"));
122                 /*
123                  * Wait for our inode block to become available.
124                  *
125                  * Hold a reference to the vnode to protect against
126                  * ffs_snapgone(). Since we hold a reference, it can only
127                  * get reclaimed (VI_DOOMED flag) in a forcible downgrade
128                  * or unmount. For an unmount, the entire filesystem will be
129                  * gone, so we cannot attempt to touch anything associated
130                  * with it while the vnode is unlocked; all we can do is 
131                  * pause briefly and try again. If when we relock the vnode
132                  * we discover that it has been reclaimed, updating it is no
133                  * longer necessary and we can just return an error.
134                  */
135                 vref(vp);
136                 VOP_UNLOCK(vp, 0);
137                 pause("ffsupd", 1);
138                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
139                 vrele(vp);
140                 if ((vp->v_iflag & VI_DOOMED) != 0)
141                         return (ENOENT);
142                 goto loop;
143         }
144         if (DOINGSOFTDEP(vp))
145                 softdep_update_inodeblock(ip, bp, waitfor);
146         else if (ip->i_effnlink != ip->i_nlink)
147                 panic("ffs_update: bad link cnt");
148         if (I_IS_UFS1(ip)) {
149                 *((struct ufs1_dinode *)bp->b_data +
150                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
151                 /* XXX: FIX? The entropy here is desirable, but the harvesting may be expensive */
152                 random_harvest_queue(&(ip->i_din1), sizeof(ip->i_din1), 1, RANDOM_FS_ATIME);
153         } else {
154                 *((struct ufs2_dinode *)bp->b_data +
155                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
156                 /* XXX: FIX? The entropy here is desirable, but the harvesting may be expensive */
157                 random_harvest_queue(&(ip->i_din2), sizeof(ip->i_din2), 1, RANDOM_FS_ATIME);
158         }
159         if (waitfor)
160                 error = bwrite(bp);
161         else if (vm_page_count_severe() || buf_dirty_count_severe()) {
162                 bawrite(bp);
163                 error = 0;
164         } else {
165                 if (bp->b_bufsize == fs->fs_bsize)
166                         bp->b_flags |= B_CLUSTEROK;
167                 bdwrite(bp);
168                 error = 0;
169         }
170         return (error);
171 }
172
173 #define SINGLE  0       /* index of single indirect block */
174 #define DOUBLE  1       /* index of double indirect block */
175 #define TRIPLE  2       /* index of triple indirect block */
176 /*
177  * Truncate the inode ip to at most length size, freeing the
178  * disk blocks.
179  */
180 int
181 ffs_truncate(vp, length, flags, cred)
182         struct vnode *vp;
183         off_t length;
184         int flags;
185         struct ucred *cred;
186 {
187         struct inode *ip;
188         ufs2_daddr_t bn, lbn, lastblock, lastiblock[UFS_NIADDR];
189         ufs2_daddr_t indir_lbn[UFS_NIADDR], oldblks[UFS_NDADDR + UFS_NIADDR];
190         ufs2_daddr_t newblks[UFS_NDADDR + UFS_NIADDR];
191         ufs2_daddr_t count, blocksreleased = 0, datablocks, blkno;
192         struct bufobj *bo;
193         struct fs *fs;
194         struct buf *bp;
195         struct ufsmount *ump;
196         int softdeptrunc, journaltrunc;
197         int needextclean, extblocks;
198         int offset, size, level, nblocks;
199         int i, error, allerror, indiroff, waitforupdate;
200         u_long key;
201         off_t osize;
202
203         ip = VTOI(vp);
204         ump = VFSTOUFS(vp->v_mount);
205         fs = ump->um_fs;
206         bo = &vp->v_bufobj;
207
208         ASSERT_VOP_LOCKED(vp, "ffs_truncate");
209
210         if (length < 0)
211                 return (EINVAL);
212         if (length > fs->fs_maxfilesize)
213                 return (EFBIG);
214 #ifdef QUOTA
215         error = getinoquota(ip);
216         if (error)
217                 return (error);
218 #endif
219         /*
220          * Historically clients did not have to specify which data
221          * they were truncating. So, if not specified, we assume
222          * traditional behavior, e.g., just the normal data.
223          */
224         if ((flags & (IO_EXT | IO_NORMAL)) == 0)
225                 flags |= IO_NORMAL;
226         if (!DOINGSOFTDEP(vp) && !DOINGASYNC(vp))
227                 flags |= IO_SYNC;
228         waitforupdate = (flags & IO_SYNC) != 0 || !DOINGASYNC(vp);
229         /*
230          * If we are truncating the extended-attributes, and cannot
231          * do it with soft updates, then do it slowly here. If we are
232          * truncating both the extended attributes and the file contents
233          * (e.g., the file is being unlinked), then pick it off with
234          * soft updates below.
235          */
236         allerror = 0;
237         needextclean = 0;
238         softdeptrunc = 0;
239         journaltrunc = DOINGSUJ(vp);
240         if (journaltrunc == 0 && DOINGSOFTDEP(vp) && length == 0)
241                 softdeptrunc = !softdep_slowdown(vp);
242         extblocks = 0;
243         datablocks = DIP(ip, i_blocks);
244         if (fs->fs_magic == FS_UFS2_MAGIC && ip->i_din2->di_extsize > 0) {
245                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
246                 datablocks -= extblocks;
247         }
248         if ((flags & IO_EXT) && extblocks > 0) {
249                 if (length != 0)
250                         panic("ffs_truncate: partial trunc of extdata");
251                 if (softdeptrunc || journaltrunc) {
252                         if ((flags & IO_NORMAL) == 0)
253                                 goto extclean;
254                         needextclean = 1;
255                 } else {
256                         if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
257                                 return (error);
258 #ifdef QUOTA
259                         (void) chkdq(ip, -extblocks, NOCRED, 0);
260 #endif
261                         vinvalbuf(vp, V_ALT, 0, 0);
262                         vn_pages_remove(vp,
263                             OFF_TO_IDX(lblktosize(fs, -extblocks)), 0);
264                         osize = ip->i_din2->di_extsize;
265                         ip->i_din2->di_blocks -= extblocks;
266                         ip->i_din2->di_extsize = 0;
267                         for (i = 0; i < UFS_NXADDR; i++) {
268                                 oldblks[i] = ip->i_din2->di_extb[i];
269                                 ip->i_din2->di_extb[i] = 0;
270                         }
271                         ip->i_flag |= IN_CHANGE;
272                         if ((error = ffs_update(vp, waitforupdate)))
273                                 return (error);
274                         for (i = 0; i < UFS_NXADDR; i++) {
275                                 if (oldblks[i] == 0)
276                                         continue;
277                                 ffs_blkfree(ump, fs, ITODEVVP(ip), oldblks[i],
278                                     sblksize(fs, osize, i), ip->i_number,
279                                     vp->v_type, NULL, SINGLETON_KEY);
280                         }
281                 }
282         }
283         if ((flags & IO_NORMAL) == 0)
284                 return (0);
285         if (vp->v_type == VLNK &&
286             (ip->i_size < vp->v_mount->mnt_maxsymlinklen ||
287              datablocks == 0)) {
288 #ifdef INVARIANTS
289                 if (length != 0)
290                         panic("ffs_truncate: partial truncate of symlink");
291 #endif
292                 bzero(SHORTLINK(ip), (u_int)ip->i_size);
293                 ip->i_size = 0;
294                 DIP_SET(ip, i_size, 0);
295                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
296                 if (needextclean)
297                         goto extclean;
298                 return (ffs_update(vp, waitforupdate));
299         }
300         if (ip->i_size == length) {
301                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
302                 if (needextclean)
303                         goto extclean;
304                 return (ffs_update(vp, 0));
305         }
306         if (fs->fs_ronly)
307                 panic("ffs_truncate: read-only filesystem");
308         if (IS_SNAPSHOT(ip))
309                 ffs_snapremove(vp);
310         vp->v_lasta = vp->v_clen = vp->v_cstart = vp->v_lastw = 0;
311         osize = ip->i_size;
312         /*
313          * Lengthen the size of the file. We must ensure that the
314          * last byte of the file is allocated. Since the smallest
315          * value of osize is 0, length will be at least 1.
316          */
317         if (osize < length) {
318                 vnode_pager_setsize(vp, length);
319                 flags |= BA_CLRBUF;
320                 error = UFS_BALLOC(vp, length - 1, 1, cred, flags, &bp);
321                 if (error) {
322                         vnode_pager_setsize(vp, osize);
323                         return (error);
324                 }
325                 ip->i_size = length;
326                 DIP_SET(ip, i_size, length);
327                 if (bp->b_bufsize == fs->fs_bsize)
328                         bp->b_flags |= B_CLUSTEROK;
329                 if (flags & IO_SYNC)
330                         bwrite(bp);
331                 else if (DOINGASYNC(vp))
332                         bdwrite(bp);
333                 else
334                         bawrite(bp);
335                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
336                 return (ffs_update(vp, waitforupdate));
337         }
338         /*
339          * Lookup block number for a given offset. Zero length files
340          * have no blocks, so return a blkno of -1.
341          */
342         lbn = lblkno(fs, length - 1);
343         if (length == 0) {
344                 blkno = -1;
345         } else if (lbn < UFS_NDADDR) {
346                 blkno = DIP(ip, i_db[lbn]);
347         } else {
348                 error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn), fs->fs_bsize,
349                     cred, BA_METAONLY, &bp);
350                 if (error)
351                         return (error);
352                 indiroff = (lbn - UFS_NDADDR) % NINDIR(fs);
353                 if (I_IS_UFS1(ip))
354                         blkno = ((ufs1_daddr_t *)(bp->b_data))[indiroff];
355                 else
356                         blkno = ((ufs2_daddr_t *)(bp->b_data))[indiroff];
357                 /*
358                  * If the block number is non-zero, then the indirect block
359                  * must have been previously allocated and need not be written.
360                  * If the block number is zero, then we may have allocated
361                  * the indirect block and hence need to write it out.
362                  */
363                 if (blkno != 0)
364                         brelse(bp);
365                 else if (flags & IO_SYNC)
366                         bwrite(bp);
367                 else
368                         bdwrite(bp);
369         }
370         /*
371          * If the block number at the new end of the file is zero,
372          * then we must allocate it to ensure that the last block of 
373          * the file is allocated. Soft updates does not handle this
374          * case, so here we have to clean up the soft updates data
375          * structures describing the allocation past the truncation
376          * point. Finding and deallocating those structures is a lot of
377          * work. Since partial truncation with a hole at the end occurs
378          * rarely, we solve the problem by syncing the file so that it
379          * will have no soft updates data structures left.
380          */
381         if (blkno == 0 && (error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
382                 return (error);
383         if (blkno != 0 && DOINGSOFTDEP(vp)) {
384                 if (softdeptrunc == 0 && journaltrunc == 0) {
385                         /*
386                          * If soft updates cannot handle this truncation,
387                          * clean up soft dependency data structures and
388                          * fall through to the synchronous truncation.
389                          */
390                         if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
391                                 return (error);
392                 } else {
393                         flags = IO_NORMAL | (needextclean ? IO_EXT: 0);
394                         if (journaltrunc)
395                                 softdep_journal_freeblocks(ip, cred, length,
396                                     flags);
397                         else
398                                 softdep_setup_freeblocks(ip, length, flags);
399                         ASSERT_VOP_LOCKED(vp, "ffs_truncate1");
400                         if (journaltrunc == 0) {
401                                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
402                                 error = ffs_update(vp, 0);
403                         }
404                         return (error);
405                 }
406         }
407         /*
408          * Shorten the size of the file. If the last block of the
409          * shortened file is unallocated, we must allocate it.
410          * Additionally, if the file is not being truncated to a
411          * block boundary, the contents of the partial block
412          * following the end of the file must be zero'ed in
413          * case it ever becomes accessible again because of
414          * subsequent file growth. Directories however are not
415          * zero'ed as they should grow back initialized to empty.
416          */
417         offset = blkoff(fs, length);
418         if (blkno != 0 && offset == 0) {
419                 ip->i_size = length;
420                 DIP_SET(ip, i_size, length);
421         } else {
422                 lbn = lblkno(fs, length);
423                 flags |= BA_CLRBUF;
424                 error = UFS_BALLOC(vp, length - 1, 1, cred, flags, &bp);
425                 if (error)
426                         return (error);
427                 /*
428                  * When we are doing soft updates and the UFS_BALLOC
429                  * above fills in a direct block hole with a full sized
430                  * block that will be truncated down to a fragment below,
431                  * we must flush out the block dependency with an FSYNC
432                  * so that we do not get a soft updates inconsistency
433                  * when we create the fragment below.
434                  */
435                 if (DOINGSOFTDEP(vp) && lbn < UFS_NDADDR &&
436                     fragroundup(fs, blkoff(fs, length)) < fs->fs_bsize &&
437                     (error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
438                         return (error);
439                 ip->i_size = length;
440                 DIP_SET(ip, i_size, length);
441                 size = blksize(fs, ip, lbn);
442                 if (vp->v_type != VDIR && offset != 0)
443                         bzero((char *)bp->b_data + offset,
444                             (u_int)(size - offset));
445                 /* Kirk's code has reallocbuf(bp, size, 1) here */
446                 allocbuf(bp, size);
447                 if (bp->b_bufsize == fs->fs_bsize)
448                         bp->b_flags |= B_CLUSTEROK;
449                 if (flags & IO_SYNC)
450                         bwrite(bp);
451                 else if (DOINGASYNC(vp))
452                         bdwrite(bp);
453                 else
454                         bawrite(bp);
455         }
456         /*
457          * Calculate index into inode's block list of
458          * last direct and indirect blocks (if any)
459          * which we want to keep.  Lastblock is -1 when
460          * the file is truncated to 0.
461          */
462         lastblock = lblkno(fs, length + fs->fs_bsize - 1) - 1;
463         lastiblock[SINGLE] = lastblock - UFS_NDADDR;
464         lastiblock[DOUBLE] = lastiblock[SINGLE] - NINDIR(fs);
465         lastiblock[TRIPLE] = lastiblock[DOUBLE] - NINDIR(fs) * NINDIR(fs);
466         nblocks = btodb(fs->fs_bsize);
467         /*
468          * Update file and block pointers on disk before we start freeing
469          * blocks.  If we crash before free'ing blocks below, the blocks
470          * will be returned to the free list.  lastiblock values are also
471          * normalized to -1 for calls to ffs_indirtrunc below.
472          */
473         for (level = TRIPLE; level >= SINGLE; level--) {
474                 oldblks[UFS_NDADDR + level] = DIP(ip, i_ib[level]);
475                 if (lastiblock[level] < 0) {
476                         DIP_SET(ip, i_ib[level], 0);
477                         lastiblock[level] = -1;
478                 }
479         }
480         for (i = 0; i < UFS_NDADDR; i++) {
481                 oldblks[i] = DIP(ip, i_db[i]);
482                 if (i > lastblock)
483                         DIP_SET(ip, i_db[i], 0);
484         }
485         ip->i_flag |= IN_CHANGE | IN_UPDATE;
486         allerror = ffs_update(vp, waitforupdate);
487         
488         /*
489          * Having written the new inode to disk, save its new configuration
490          * and put back the old block pointers long enough to process them.
491          * Note that we save the new block configuration so we can check it
492          * when we are done.
493          */
494         for (i = 0; i < UFS_NDADDR; i++) {
495                 newblks[i] = DIP(ip, i_db[i]);
496                 DIP_SET(ip, i_db[i], oldblks[i]);
497         }
498         for (i = 0; i < UFS_NIADDR; i++) {
499                 newblks[UFS_NDADDR + i] = DIP(ip, i_ib[i]);
500                 DIP_SET(ip, i_ib[i], oldblks[UFS_NDADDR + i]);
501         }
502         ip->i_size = osize;
503         DIP_SET(ip, i_size, osize);
504
505         error = vtruncbuf(vp, cred, length, fs->fs_bsize);
506         if (error && (allerror == 0))
507                 allerror = error;
508
509         /*
510          * Indirect blocks first.
511          */
512         indir_lbn[SINGLE] = -UFS_NDADDR;
513         indir_lbn[DOUBLE] = indir_lbn[SINGLE] - NINDIR(fs) - 1;
514         indir_lbn[TRIPLE] = indir_lbn[DOUBLE] - NINDIR(fs) * NINDIR(fs) - 1;
515         for (level = TRIPLE; level >= SINGLE; level--) {
516                 bn = DIP(ip, i_ib[level]);
517                 if (bn != 0) {
518                         error = ffs_indirtrunc(ip, indir_lbn[level],
519                             fsbtodb(fs, bn), lastiblock[level], level, &count);
520                         if (error)
521                                 allerror = error;
522                         blocksreleased += count;
523                         if (lastiblock[level] < 0) {
524                                 DIP_SET(ip, i_ib[level], 0);
525                                 ffs_blkfree(ump, fs, ump->um_devvp, bn,
526                                     fs->fs_bsize, ip->i_number,
527                                     vp->v_type, NULL, SINGLETON_KEY);
528                                 blocksreleased += nblocks;
529                         }
530                 }
531                 if (lastiblock[level] >= 0)
532                         goto done;
533         }
534
535         /*
536          * All whole direct blocks or frags.
537          */
538         key = ffs_blkrelease_start(ump, ump->um_devvp, ip->i_number);
539         for (i = UFS_NDADDR - 1; i > lastblock; i--) {
540                 long bsize;
541
542                 bn = DIP(ip, i_db[i]);
543                 if (bn == 0)
544                         continue;
545                 DIP_SET(ip, i_db[i], 0);
546                 bsize = blksize(fs, ip, i);
547                 ffs_blkfree(ump, fs, ump->um_devvp, bn, bsize, ip->i_number,
548                     vp->v_type, NULL, key);
549                 blocksreleased += btodb(bsize);
550         }
551         ffs_blkrelease_finish(ump, key);
552         if (lastblock < 0)
553                 goto done;
554
555         /*
556          * Finally, look for a change in size of the
557          * last direct block; release any frags.
558          */
559         bn = DIP(ip, i_db[lastblock]);
560         if (bn != 0) {
561                 long oldspace, newspace;
562
563                 /*
564                  * Calculate amount of space we're giving
565                  * back as old block size minus new block size.
566                  */
567                 oldspace = blksize(fs, ip, lastblock);
568                 ip->i_size = length;
569                 DIP_SET(ip, i_size, length);
570                 newspace = blksize(fs, ip, lastblock);
571                 if (newspace == 0)
572                         panic("ffs_truncate: newspace");
573                 if (oldspace - newspace > 0) {
574                         /*
575                          * Block number of space to be free'd is
576                          * the old block # plus the number of frags
577                          * required for the storage we're keeping.
578                          */
579                         bn += numfrags(fs, newspace);
580                         ffs_blkfree(ump, fs, ump->um_devvp, bn,
581                            oldspace - newspace, ip->i_number, vp->v_type,
582                            NULL, SINGLETON_KEY);
583                         blocksreleased += btodb(oldspace - newspace);
584                 }
585         }
586 done:
587 #ifdef INVARIANTS
588         for (level = SINGLE; level <= TRIPLE; level++)
589                 if (newblks[UFS_NDADDR + level] != DIP(ip, i_ib[level]))
590                         panic("ffs_truncate1");
591         for (i = 0; i < UFS_NDADDR; i++)
592                 if (newblks[i] != DIP(ip, i_db[i]))
593                         panic("ffs_truncate2");
594         BO_LOCK(bo);
595         if (length == 0 &&
596             (fs->fs_magic != FS_UFS2_MAGIC || ip->i_din2->di_extsize == 0) &&
597             (bo->bo_dirty.bv_cnt > 0 || bo->bo_clean.bv_cnt > 0))
598                 panic("ffs_truncate3");
599         BO_UNLOCK(bo);
600 #endif /* INVARIANTS */
601         /*
602          * Put back the real size.
603          */
604         ip->i_size = length;
605         DIP_SET(ip, i_size, length);
606         if (DIP(ip, i_blocks) >= blocksreleased)
607                 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - blocksreleased);
608         else    /* sanity */
609                 DIP_SET(ip, i_blocks, 0);
610         ip->i_flag |= IN_CHANGE;
611 #ifdef QUOTA
612         (void) chkdq(ip, -blocksreleased, NOCRED, 0);
613 #endif
614         return (allerror);
615
616 extclean:
617         if (journaltrunc)
618                 softdep_journal_freeblocks(ip, cred, length, IO_EXT);
619         else
620                 softdep_setup_freeblocks(ip, length, IO_EXT);
621         return (ffs_update(vp, waitforupdate));
622 }
623
624 /*
625  * Release blocks associated with the inode ip and stored in the indirect
626  * block bn.  Blocks are free'd in LIFO order up to (but not including)
627  * lastbn.  If level is greater than SINGLE, the block is an indirect block
628  * and recursive calls to indirtrunc must be used to cleanse other indirect
629  * blocks.
630  */
631 static int
632 ffs_indirtrunc(ip, lbn, dbn, lastbn, level, countp)
633         struct inode *ip;
634         ufs2_daddr_t lbn, lastbn;
635         ufs2_daddr_t dbn;
636         int level;
637         ufs2_daddr_t *countp;
638 {
639         struct buf *bp;
640         struct fs *fs;
641         struct ufsmount *ump;
642         struct vnode *vp;
643         caddr_t copy = NULL;
644         u_long key;
645         int i, nblocks, error = 0, allerror = 0;
646         ufs2_daddr_t nb, nlbn, last;
647         ufs2_daddr_t blkcount, factor, blocksreleased = 0;
648         ufs1_daddr_t *bap1 = NULL;
649         ufs2_daddr_t *bap2 = NULL;
650 #define BAP(ip, i) (I_IS_UFS1(ip) ? bap1[i] : bap2[i])
651
652         fs = ITOFS(ip);
653         ump = ITOUMP(ip);
654
655         /*
656          * Calculate index in current block of last
657          * block to be kept.  -1 indicates the entire
658          * block so we need not calculate the index.
659          */
660         factor = lbn_offset(fs, level);
661         last = lastbn;
662         if (lastbn > 0)
663                 last /= factor;
664         nblocks = btodb(fs->fs_bsize);
665         /*
666          * Get buffer of block pointers, zero those entries corresponding
667          * to blocks to be free'd, and update on disk copy first.  Since
668          * double(triple) indirect before single(double) indirect, calls
669          * to bmap on these blocks will fail.  However, we already have
670          * the on disk address, so we have to set the b_blkno field
671          * explicitly instead of letting bread do everything for us.
672          */
673         vp = ITOV(ip);
674         bp = getblk(vp, lbn, (int)fs->fs_bsize, 0, 0, 0);
675         if ((bp->b_flags & B_CACHE) == 0) {
676 #ifdef RACCT
677                 if (racct_enable) {
678                         PROC_LOCK(curproc);
679                         racct_add_buf(curproc, bp, 0);
680                         PROC_UNLOCK(curproc);
681                 }
682 #endif /* RACCT */
683                 curthread->td_ru.ru_inblock++;  /* pay for read */
684                 bp->b_iocmd = BIO_READ;
685                 bp->b_flags &= ~B_INVAL;
686                 bp->b_ioflags &= ~BIO_ERROR;
687                 if (bp->b_bcount > bp->b_bufsize)
688                         panic("ffs_indirtrunc: bad buffer size");
689                 bp->b_blkno = dbn;
690                 vfs_busy_pages(bp, 0);
691                 bp->b_iooffset = dbtob(bp->b_blkno);
692                 bstrategy(bp);
693                 error = bufwait(bp);
694         }
695         if (error) {
696                 brelse(bp);
697                 *countp = 0;
698                 return (error);
699         }
700
701         if (I_IS_UFS1(ip))
702                 bap1 = (ufs1_daddr_t *)bp->b_data;
703         else
704                 bap2 = (ufs2_daddr_t *)bp->b_data;
705         if (lastbn != -1) {
706                 copy = malloc(fs->fs_bsize, M_TEMP, M_WAITOK);
707                 bcopy((caddr_t)bp->b_data, copy, (u_int)fs->fs_bsize);
708                 for (i = last + 1; i < NINDIR(fs); i++)
709                         if (I_IS_UFS1(ip))
710                                 bap1[i] = 0;
711                         else
712                                 bap2[i] = 0;
713                 if (DOINGASYNC(vp)) {
714                         bdwrite(bp);
715                 } else {
716                         error = bwrite(bp);
717                         if (error)
718                                 allerror = error;
719                 }
720                 if (I_IS_UFS1(ip))
721                         bap1 = (ufs1_daddr_t *)copy;
722                 else
723                         bap2 = (ufs2_daddr_t *)copy;
724         }
725
726         /*
727          * Recursively free totally unused blocks.
728          */
729         key = ffs_blkrelease_start(ump, ITODEVVP(ip), ip->i_number);
730         for (i = NINDIR(fs) - 1, nlbn = lbn + 1 - i * factor; i > last;
731             i--, nlbn += factor) {
732                 nb = BAP(ip, i);
733                 if (nb == 0)
734                         continue;
735                 if (level > SINGLE) {
736                         if ((error = ffs_indirtrunc(ip, nlbn, fsbtodb(fs, nb),
737                             (ufs2_daddr_t)-1, level - 1, &blkcount)) != 0)
738                                 allerror = error;
739                         blocksreleased += blkcount;
740                 }
741                 ffs_blkfree(ump, fs, ITODEVVP(ip), nb, fs->fs_bsize,
742                     ip->i_number, vp->v_type, NULL, key);
743                 blocksreleased += nblocks;
744         }
745         ffs_blkrelease_finish(ump, key);
746
747         /*
748          * Recursively free last partial block.
749          */
750         if (level > SINGLE && lastbn >= 0) {
751                 last = lastbn % factor;
752                 nb = BAP(ip, i);
753                 if (nb != 0) {
754                         error = ffs_indirtrunc(ip, nlbn, fsbtodb(fs, nb),
755                             last, level - 1, &blkcount);
756                         if (error)
757                                 allerror = error;
758                         blocksreleased += blkcount;
759                 }
760         }
761         if (copy != NULL) {
762                 free(copy, M_TEMP);
763         } else {
764                 bp->b_flags |= B_INVAL | B_NOCACHE;
765                 brelse(bp);
766         }
767
768         *countp = blocksreleased;
769         return (allerror);
770 }
771
772 int
773 ffs_rdonly(struct inode *ip)
774 {
775
776         return (ITOFS(ip)->fs_ronly != 0);
777 }
778