Merge branch 'vendor/LIBEDIT'
[dragonfly.git] / sys / gnu / vfs / ext2fs / ext2_alloc.c
1 /*
2  *  modified for Lites 1.1
3  *
4  *  Aug 1995, Godmar Back (gback@cs.utah.edu)
5  *  University of Utah, Department of Computer Science
6  */
7 /*
8  * Copyright (c) 1982, 1986, 1989, 1993
9  *      The Regents of the University of California.  All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *      This product includes software developed by the University of
22  *      California, Berkeley and its contributors.
23  * 4. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  *
39  *      @(#)ext2_alloc.c        8.8 (Berkeley) 2/21/94
40  * $FreeBSD: src/sys/gnu/ext2fs/ext2_alloc.c,v 1.28.2.2 2002/07/01 00:18:51 iedowse Exp $
41  */
42
43 #include "opt_quota.h"
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/conf.h>
48 #include <sys/vnode.h>
49 #include <sys/stat.h>
50 #include <sys/mount.h>
51 #include <sys/syslog.h>
52
53 #include <machine/inttypes.h>
54
55 #include <sys/buf2.h>
56
57 #include "quota.h"
58 #include "inode.h"
59 #include "ext2mount.h"
60
61 #include "ext2_fs.h"
62 #include "ext2_fs_sb.h"
63 #include "fs.h"
64 #include "ext2_extern.h"
65
66 static void     ext2_fserr (struct ext2_sb_info *, u_int, char *);
67
68 /*
69  * Linux calls this functions at the following locations:
70  * (1) the inode is freed
71  * (2) a preallocation miss occurs
72  * (3) truncate is called
73  * (4) release_file is called and f_mode & 2
74  *
75  * I call it in ext2_inactive, ext2_truncate, ext2_vfree and in (2)
76  * the call in vfree might be redundant
77  */
78 void
79 ext2_discard_prealloc(struct inode *ip)
80 {
81 #ifdef EXT2_PREALLOCATE
82         if (ip->i_prealloc_count) {
83                 int i = ip->i_prealloc_count;
84                 ip->i_prealloc_count = 0;
85                 ext2_free_blocks (ITOV(ip)->v_mount,
86                                   ip->i_prealloc_block,
87                                   i);
88         }
89 #endif
90 }
91
92 /*
93  * Allocate a block in the file system.
94  *
95  * this takes the framework from ffs_alloc. To implement the
96  * actual allocation, it calls ext2_new_block, the ported version
97  * of the same Linux routine.
98  *
99  * we note that this is always called in connection with ext2_blkpref
100  *
101  * preallocation is done as Linux does it
102  */
103 int
104 ext2_alloc(struct inode *ip, daddr_t lbn, daddr_t bpref, int size,
105            struct ucred *cred, daddr_t *bnp)
106 {
107         struct ext2_sb_info *fs;
108         daddr_t bno;
109 #if QUOTA
110         int error;
111 #endif
112
113         *bnp = 0;
114         fs = ip->i_e2fs;
115 #if DIAGNOSTIC
116         if ((u_int)size > fs->s_blocksize || blkoff(fs, size) != 0) {
117                 kprintf("dev = %s, bsize = %lu, size = %d, fs = %s\n",
118                     devtoname(ip->i_dev), fs->s_blocksize, size, fs->fs_fsmnt);
119                 panic("ext2_alloc: bad size");
120         }
121         if (cred == NOCRED)
122                 panic("ext2_alloc: missing credential");
123 #endif /* DIAGNOSTIC */
124         if (size == fs->s_blocksize && fs->s_es->s_free_blocks_count == 0)
125                 goto nospace;
126         if (cred->cr_uid != 0 &&
127                 fs->s_es->s_free_blocks_count < fs->s_es->s_r_blocks_count)
128                 goto nospace;
129 #if QUOTA
130         if ((error = ext2_chkdq(ip, (long)btodb(size), cred, 0)) != 0)
131                 return (error);
132 #endif
133         if (bpref >= fs->s_es->s_blocks_count)
134                 bpref = 0;
135         /* call the Linux code */
136 #ifdef EXT2_PREALLOCATE
137         /* To have a preallocation hit, we must
138          * - have at least one block preallocated
139          * - and our preferred block must have that block number or one below
140          */
141         if (ip->i_prealloc_count &&
142             (bpref == ip->i_prealloc_block ||
143              bpref + 1 == ip->i_prealloc_block))
144         {
145                 bno = ip->i_prealloc_block++;
146                 ip->i_prealloc_count--;
147                 /* ext2_debug ("preallocation hit (%lu/%lu).\n",
148                             ++alloc_hits, ++alloc_attempts); */
149
150                 /* Linux gets, clears, and releases the buffer at this
151                    point - we don't have to that; we leave it to the caller
152                  */
153         } else {
154                 ext2_discard_prealloc (ip);
155                 /* ext2_debug ("preallocation miss (%lu/%lu).\n",
156                             alloc_hits, ++alloc_attempts); */
157                 if (S_ISREG(ip->i_mode))
158                         bno = ext2_new_block
159                                 (ITOV(ip)->v_mount, bpref,
160                                  &ip->i_prealloc_count,
161                                  &ip->i_prealloc_block);
162                 else
163                         bno = (daddr_t)ext2_new_block(ITOV(ip)->v_mount,
164                                         bpref, 0, 0);
165         }
166 #else
167         bno = (daddr_t)ext2_new_block(ITOV(ip)->v_mount, bpref, 0, 0);
168 #endif
169
170         if (bno > 0) {
171                 /* set next_alloc fields as done in block_getblk */
172                 ip->i_next_alloc_block = lbn;
173                 ip->i_next_alloc_goal = bno;
174
175                 ip->i_blocks += btodb(size);
176                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
177                 *bnp = bno;
178                 return (0);
179         }
180 #if QUOTA
181         /*
182          * Restore user's disk quota because allocation failed.
183          */
184         ext2_chkdq(ip, (long)-btodb(size), cred, FORCE);
185 #endif
186 nospace:
187         ext2_fserr(fs, cred->cr_uid, "file system full");
188         uprintf("\n%s: write failed, file system is full\n", fs->fs_fsmnt);
189         return (ENOSPC);
190 }
191
192 /*
193  * Reallocate a sequence of blocks into a contiguous sequence of blocks.
194  *
195  * The vnode and an array of buffer pointers for a range of sequential
196  * logical blocks to be made contiguous is given. The allocator attempts
197  * to find a range of sequential blocks starting as close as possible to
198  * an fs_rotdelay offset from the end of the allocation for the logical
199  * block immediately preceeding the current range. If successful, the
200  * physical block numbers in the buffer pointers and in the inode are
201  * changed to reflect the new allocation. If unsuccessful, the allocation
202  * is left unchanged. The success in doing the reallocation is returned.
203  * Note that the error return is not reflected back to the user. Rather
204  * the previous block allocation will be used.
205  */
206
207 #ifdef FANCY_REALLOC
208 #include <sys/sysctl.h>
209 static int doasyncfree = 1;
210 #ifdef  OPT_DEBUG
211 SYSCTL_INT(_debug, 14, doasyncfree, CTLFLAG_RW, &doasyncfree, 0, "");
212 #endif  /* OPT_DEBUG */
213 #endif
214
215 /*
216  * ext2_reallocblks(struct vnode *a_vp, struct cluster_save *a_buflist)
217  */
218 int
219 ext2_reallocblks(struct vop_reallocblks_args *ap)
220 {
221 #ifndef FANCY_REALLOC
222 /* kprintf("ext2_reallocblks not implemented\n"); */
223 return ENOSPC;
224 #else
225
226         struct ext2_sb_info *fs;
227         struct inode *ip;
228         struct vnode *vp;
229         struct buf *sbp, *ebp;
230         daddr_t *bap, *sbap, *ebap;
231         struct cluster_save *buflist;
232         daddr_t start_lbn, end_lbn, soff, eoff, newblk, blkno;
233         struct indir start_ap[NIADDR + 1], end_ap[NIADDR + 1], *idp;
234         int i, len, start_lvl, end_lvl, pref, ssize;
235
236         vp = ap->a_vp;
237         ip = VTOI(vp);
238         fs = ip->i_e2fs;
239 #ifdef UNKLAR
240         if (fs->fs_contigsumsize <= 0)
241                 return (ENOSPC);
242 #endif
243         buflist = ap->a_buflist;
244         len = buflist->bs_nchildren;
245         start_lbn = lblkno(fs, buflist->bs_children[0]->b_loffset);
246         end_lbn = start_lbn + len - 1;
247 #if DIAGNOSTIC
248         for (i = 1; i < len; i++) {
249                 if (buflist->bs_children[i]->b_loffset != lblktodoff(fs, start_lbn) + lblktodoff(fs, i))
250                         panic("ext2_reallocblks: non-cluster");
251         }
252 #endif
253         /*
254          * If the latest allocation is in a new cylinder group, assume that
255          * the filesystem has decided to move and do not force it back to
256          * the previous cylinder group.
257          */
258         if (dtog(fs, dofftofsb(fs, buflist->bs_children[0]->b_bio2.bio_offset)) !=
259             dtog(fs, dofftofsb(fs, buflist->bs_children[len - 1]->b_bio2.bio_offset)))
260                 return (ENOSPC);
261         if (ext2_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
262             ext2_getlbns(vp, end_lbn, end_ap, &end_lvl))
263                 return (ENOSPC);
264         /*
265          * Get the starting offset and block map for the first block.
266          */
267         if (start_lvl == 0) {
268                 sbap = &ip->i_db[0];
269                 soff = start_lbn;
270         } else {
271                 idp = &start_ap[start_lvl - 1];
272                 if (bread(vp, lblktodoff(fs, idp->in_lbn), (int)fs->s_blocksize, NOCRED, &sbp)) {
273                         brelse(sbp);
274                         return (ENOSPC);
275                 }
276                 sbap = (daddr_t *)sbp->b_data;
277                 soff = idp->in_off;
278         }
279         /*
280          * Find the preferred location for the cluster.
281          */
282         pref = ext2_blkpref(ip, start_lbn, soff, sbap);
283         /*
284          * If the block range spans two block maps, get the second map.
285          */
286         if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
287                 ssize = len;
288         } else {
289 #if DIAGNOSTIC
290                 if (start_ap[start_lvl-1].in_lbn == idp->in_lbn)
291                         panic("ext2_reallocblk: start == end");
292 #endif
293                 ssize = len - (idp->in_off + 1);
294                 if (bread(vp, lblktodoff(fs, idp->in_lbn), (int)fs->s_blocksize, NOCRED, &ebp))
295                         goto fail;
296                 ebap = (daddr_t *)ebp->b_data;
297         }
298         /*
299          * Search the block map looking for an allocation of the desired size.
300          */
301         if ((newblk = (daddr_t)ext2_hashalloc(ip, dtog(fs, pref), (long)pref,
302             len, (u_long (*)())ext2_clusteralloc)) == 0)
303                 goto fail;
304         /*
305          * We have found a new contiguous block.
306          *
307          * First we have to replace the old block pointers with the new
308          * block pointers in the inode and indirect blocks associated
309          * with the file.
310          */
311         blkno = newblk;
312         for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->s_frags_per_block) {
313                 if (i == ssize)
314                         bap = ebap;
315 #if DIAGNOSTIC
316                 if (buflist->bs_children[i]->b_bio2.bio_offset != fsbtodoff(fs, *bap))
317                         panic("ext2_reallocblks: alloc mismatch");
318 #endif
319                 *bap++ = blkno;
320         }
321         /*
322          * Next we must write out the modified inode and indirect blocks.
323          * For strict correctness, the writes should be synchronous since
324          * the old block values may have been written to disk. In practise
325          * they are almost never written, but if we are concerned about
326          * strict correctness, the `doasyncfree' flag should be set to zero.
327          *
328          * The test on `doasyncfree' should be changed to test a flag
329          * that shows whether the associated buffers and inodes have
330          * been written. The flag should be set when the cluster is
331          * started and cleared whenever the buffer or inode is flushed.
332          * We can then check below to see if it is set, and do the
333          * synchronous write only when it has been cleared.
334          */
335         if (sbap != &ip->i_db[0]) {
336                 if (doasyncfree)
337                         bdwrite(sbp);
338                 else
339                         bwrite(sbp);
340         } else {
341                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
342                 if (!doasyncfree)
343                         EXT2_UPDATE(vp, 1);
344         }
345         if (ssize < len)
346                 if (doasyncfree)
347                         bdwrite(ebp);
348                 else
349                         bwrite(ebp);
350         /*
351          * Last, free the old blocks and assign the new blocks to the buffers.
352          */
353         for (blkno = newblk, i = 0; i < len; i++, blkno += fs->s_frags_per_block) {
354                 ext2_blkfree(ip, dofftofsb(fs, buflist->bs_children[i]->b_bio2.bio_offset),
355                     fs->s_blocksize);
356                 buflist->bs_children[i]->b_bio2.bio_offset = fsbtodoff(fs, blkno);
357         }
358         return (0);
359
360 fail:
361         if (ssize < len)
362                 brelse(ebp);
363         if (sbap != &ip->i_db[0])
364                 brelse(sbp);
365         return (ENOSPC);
366
367 #endif /* FANCY_REALLOC */
368 }
369
370 /*
371  * Allocate an inode in the file system.
372  *
373  * we leave the actual allocation strategy to the (modified)
374  * ext2_new_inode(), to make sure we get the policies right
375  */
376 int
377 ext2_valloc(struct vnode *pvp, int mode, struct ucred *cred, struct vnode **vpp)
378 {
379         struct inode *pip;
380         struct ext2_sb_info *fs;
381         struct inode *ip;
382         ino_t ino;
383         int i, error;
384
385         *vpp = NULL;
386         pip = VTOI(pvp);
387         fs = pip->i_e2fs;
388         if (fs->s_es->s_free_inodes_count == 0)
389                 goto noinodes;
390
391         /* call the Linux routine - it returns the inode number only */
392         ino = ext2_new_inode(pip, mode);
393
394         if (ino == 0)
395                 goto noinodes;
396         error = VFS_VGET(pvp->v_mount, NULL, ino, vpp);
397         if (error) {
398                 EXT2_VFREE(pvp, ino, mode);
399                 return (error);
400         }
401         ip = VTOI(*vpp);
402
403         /*
404           the question is whether using VGET was such good idea at all -
405           Linux doesn't read the old inode in when it's allocating a
406           new one. I will set at least i_size & i_blocks the zero.
407         */
408         ip->i_mode = 0;
409         ip->i_size = 0;
410         ip->i_blocks = 0;
411         ip->i_flags = 0;
412         /* now we want to make sure that the block pointers are zeroed out */
413         for (i = 0; i < NDADDR; i++)
414                 ip->i_db[i] = 0;
415         for (i = 0; i < NIADDR; i++)
416                 ip->i_ib[i] = 0;
417
418         /*
419          * Set up a new generation number for this inode.
420          * XXX check if this makes sense in ext2
421          */
422         if (ip->i_gen == 0 || ++ip->i_gen == 0)
423                 ip->i_gen = krandom() / 2 + 1;
424 /*
425 kprintf("ext2_valloc: allocated inode %d\n", ino);
426 */
427         return (0);
428 noinodes:
429         ext2_fserr(fs, cred->cr_uid, "out of inodes");
430         uprintf("\n%s: create/symlink failed, no inodes free\n", fs->fs_fsmnt);
431         return (ENOSPC);
432 }
433
434 /*
435  * Select the desired position for the next block in a file.
436  *
437  * we try to mimic what Remy does in inode_getblk/block_getblk
438  *
439  * we note: blocknr == 0 means that we're about to allocate either
440  * a direct block or a pointer block at the first level of indirection
441  * (In other words, stuff that will go in i_db[] or i_ib[])
442  *
443  * blocknr != 0 means that we're allocating a block that is none
444  * of the above. Then, blocknr tells us the number of the block
445  * that will hold the pointer
446  */
447 daddr_t
448 ext2_blkpref(struct inode *ip, daddr_t lbn, int indx, daddr_t *bap,
449              daddr_t blocknr)
450 {
451         int     tmp;
452
453         /*
454          * if the next block is actually what we thought it is,
455          * then set the goal to what we thought it should be
456          */
457         if (ip->i_next_alloc_block == lbn && ip->i_next_alloc_goal != 0)
458                 return ip->i_next_alloc_goal;
459
460         /* now check whether we were provided with an array that basically
461            tells us previous blocks to which we want to stay closeby
462         */
463         if(bap)
464                 for (tmp = indx - 1; tmp >= 0; tmp--)
465                         if (bap[tmp])
466                                 return bap[tmp];
467
468         /*
469          * else let's fall back to the blocknr, or, if there is none,
470          * follow the rule that a block should be allocated near its inode
471          */
472         return blocknr ? blocknr :
473                         (daddr_t)(ip->i_block_group *
474                         EXT2_BLOCKS_PER_GROUP(ip->i_e2fs)) +
475                         ip->i_e2fs->s_es->s_first_data_block;
476 }
477
478 /*
479  * Free a block or fragment.
480  *
481  * pass on to the Linux code
482  */
483 void
484 ext2_blkfree(struct inode *ip, daddr_t bno, long size)
485 {
486         struct ext2_sb_info *fs;
487
488         fs = ip->i_e2fs;
489         /*
490          *      call Linux code with mount *, block number, count
491          */
492         ext2_free_blocks(ITOV(ip)->v_mount, bno, size / fs->s_frag_size);
493 }
494
495 /*
496  * Free an inode.
497  *
498  * the maintenance of the actual bitmaps is again up to the linux code
499  */
500 int
501 ext2_vfree(struct vnode *pvp, ino_t ino, int mode)
502 {
503         struct ext2_sb_info *fs;
504         struct inode *pip;
505         mode_t save_i_mode;
506
507         pip = VTOI(pvp);
508         fs = pip->i_e2fs;
509         if ((u_int)ino > fs->s_inodes_per_group * fs->s_groups_count)
510                 panic("ext2_vfree: range: dev = (%d, %d), ino = %"PRId64", fs = %s",
511                     major(pip->i_dev), minor(pip->i_dev), ino, fs->fs_fsmnt);
512
513 /* ext2_debug("ext2_vfree (%d, %d) called\n", pip->i_number, mode);
514  */
515         ext2_discard_prealloc(pip);
516
517         /* we need to make sure that ext2_free_inode can adjust the
518            used_dir_counts in the group summary information - I'd
519            really like to know what the rationale behind this
520            'set i_mode to zero to denote an unused inode' is
521          */
522         save_i_mode = pip->i_mode;
523         pip->i_mode = mode;
524         ext2_free_inode(pip);
525         pip->i_mode = save_i_mode;
526         return (0);
527 }
528
529 /*
530  * Fserr prints the name of a file system with an error diagnostic.
531  *
532  * The form of the error message is:
533  *      fs: error message
534  */
535 static void
536 ext2_fserr(struct ext2_sb_info *fs, u_int uid, char *cp)
537 {
538         log(LOG_ERR, "uid %d on %s: %s\n", uid, fs->fs_fsmnt, cp);
539 }