1/*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1989, 1991, 1993
5 *	The Regents of the University of California.  All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 *    notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 *    notice, this list of conditions and the following disclaimer in the
19 *    documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37#include <sys/param.h>
38#include <sys/systm.h>
39#include <sys/bio.h>
40#include <sys/buf.h>
41#include <sys/endian.h>
42#include <sys/proc.h>
43#include <sys/vnode.h>
44#include <sys/mount.h>
45#include <sys/racct.h>
46#include <sys/resourcevar.h>
47#include <sys/stat.h>
48
49#include <fs/ext2fs/fs.h>
50#include <fs/ext2fs/inode.h>
51#include <fs/ext2fs/ext2fs.h>
52#include <fs/ext2fs/ext2_dinode.h>
53#include <fs/ext2fs/ext2_extern.h>
54#include <fs/ext2fs/ext2_mount.h>
55
56/*
57 * Bmap converts the logical block number of a file to its physical block
58 * number on the disk. The conversion is done by using the logical block
59 * number to index into the array of block pointers described by the dinode.
60 */
61int
62ext2_bmap(struct vop_bmap_args *ap)
63{
64	daddr_t blkno;
65	int error;
66
67	/*
68	 * Check for underlying vnode requests and ensure that logical
69	 * to physical mapping is requested.
70	 */
71	if (ap->a_bop != NULL)
72		*ap->a_bop = &VTOI(ap->a_vp)->i_devvp->v_bufobj;
73	if (ap->a_bnp == NULL)
74		return (0);
75
76	if (VTOI(ap->a_vp)->i_flag & IN_E4EXTENTS)
77		error = ext4_bmapext(ap->a_vp, ap->a_bn, &blkno,
78		    ap->a_runp, ap->a_runb);
79	else
80		error = ext2_bmaparray(ap->a_vp, ap->a_bn, &blkno,
81		    ap->a_runp, ap->a_runb);
82	*ap->a_bnp = blkno;
83	return (error);
84}
85
86/*
87 * Convert the logical block number of a file to its physical block number
88 * on the disk within ext4 extents.
89 */
90int
91ext4_bmapext(struct vnode *vp, int32_t bn, int64_t *bnp, int *runp, int *runb)
92{
93	struct inode *ip;
94	struct m_ext2fs *fs;
95	struct mount *mp;
96	struct ext2mount *ump;
97	struct ext4_extent_header *ehp;
98	struct ext4_extent *ep;
99	struct ext4_extent_path *path = NULL;
100	daddr_t lbn;
101	int error, depth, maxrun = 0, bsize;
102
103	ip = VTOI(vp);
104	fs = ip->i_e2fs;
105	mp = vp->v_mount;
106	ump = VFSTOEXT2(mp);
107	lbn = bn;
108	ehp = (struct ext4_extent_header *)ip->i_data;
109	depth = le16toh(ehp->eh_depth);
110	bsize = EXT2_BLOCK_SIZE(ump->um_e2fs);
111
112	*bnp = -1;
113	if (runp != NULL) {
114		maxrun = mp->mnt_iosize_max / bsize - 1;
115		*runp = 0;
116	}
117	if (runb != NULL)
118		*runb = 0;
119
120	error = ext4_ext_find_extent(ip, lbn, &path);
121	if (error)
122		return (error);
123
124	ep = path[depth].ep_ext;
125	if(ep) {
126		if (lbn < le32toh(ep->e_blk)) {
127			if (runp != NULL) {
128				*runp = min(maxrun, le32toh(ep->e_blk) - lbn - 1);
129			}
130		} else if (le32toh(ep->e_blk) <= lbn &&
131			    lbn < le32toh(ep->e_blk) + le16toh(ep->e_len)) {
132			*bnp = fsbtodb(fs, lbn - le32toh(ep->e_blk) +
133			    (le32toh(ep->e_start_lo) |
134			    (daddr_t)le16toh(ep->e_start_hi) << 32));
135			if (runp != NULL) {
136				*runp = min(maxrun,
137				    le16toh(ep->e_len) -
138				    (lbn - le32toh(ep->e_blk)) - 1);
139			}
140			if (runb != NULL)
141				*runb = min(maxrun, lbn - le32toh(ep->e_blk));
142		} else {
143			if (runb != NULL)
144				*runb = min(maxrun, le32toh(ep->e_blk) + lbn -
145				    le16toh(ep->e_len));
146		}
147	}
148
149	ext4_ext_path_free(path);
150
151	return (error);
152}
153
154static int
155readindir(struct vnode *vp, e2fs_lbn_t lbn, e2fs_daddr_t daddr, struct buf **bpp)
156{
157	struct buf *bp;
158	struct mount *mp;
159	struct ext2mount *ump;
160	int error;
161
162	mp = vp->v_mount;
163	ump = VFSTOEXT2(mp);
164
165	bp = getblk(vp, lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
166	if ((bp->b_flags & B_CACHE) == 0) {
167		KASSERT(daddr != 0,
168		    ("readindir: indirect block not in cache"));
169
170		bp->b_blkno = blkptrtodb(ump, daddr);
171		bp->b_iocmd = BIO_READ;
172		bp->b_flags &= ~B_INVAL;
173		bp->b_ioflags &= ~BIO_ERROR;
174		vfs_busy_pages(bp, 0);
175		bp->b_iooffset = dbtob(bp->b_blkno);
176		bstrategy(bp);
177#ifdef RACCT
178		if (racct_enable) {
179			PROC_LOCK(curproc);
180			racct_add_buf(curproc, bp, 0);
181			PROC_UNLOCK(curproc);
182		}
183#endif
184		curthread->td_ru.ru_inblock++;
185		error = bufwait(bp);
186		if (error != 0) {
187			brelse(bp);
188			return (error);
189		}
190	}
191	*bpp = bp;
192	return (0);
193}
194
195/*
196 * Indirect blocks are now on the vnode for the file.  They are given negative
197 * logical block numbers.  Indirect blocks are addressed by the negative
198 * address of the first data block to which they point.  Double indirect blocks
199 * are addressed by one less than the address of the first indirect block to
200 * which they point.  Triple indirect blocks are addressed by one less than
201 * the address of the first double indirect block to which they point.
202 *
203 * ext2_bmaparray does the bmap conversion, and if requested returns the
204 * array of logical blocks which must be traversed to get to a block.
205 * Each entry contains the offset into that block that gets you to the
206 * next block and the disk address of the block (if it is assigned).
207 */
208
209int
210ext2_bmaparray(struct vnode *vp, daddr_t bn, daddr_t *bnp, int *runp, int *runb)
211{
212	struct inode *ip;
213	struct buf *bp;
214	struct ext2mount *ump;
215	struct mount *mp;
216	struct indir a[EXT2_NIADDR + 1], *ap;
217	daddr_t daddr;
218	e2fs_lbn_t metalbn;
219	int error, num, maxrun = 0, bsize;
220	int *nump;
221
222	ap = NULL;
223	ip = VTOI(vp);
224	mp = vp->v_mount;
225	ump = VFSTOEXT2(mp);
226
227	bsize = EXT2_BLOCK_SIZE(ump->um_e2fs);
228
229	if (runp) {
230		maxrun = mp->mnt_iosize_max / bsize - 1;
231		*runp = 0;
232	}
233	if (runb)
234		*runb = 0;
235
236	ap = a;
237	nump = &num;
238	error = ext2_getlbns(vp, bn, ap, nump);
239	if (error)
240		return (error);
241
242	num = *nump;
243	if (num == 0) {
244		*bnp = blkptrtodb(ump, ip->i_db[bn]);
245		if (*bnp == 0) {
246			*bnp = -1;
247		} else if (runp) {
248			daddr_t bnb = bn;
249
250			for (++bn; bn < EXT2_NDADDR && *runp < maxrun &&
251			    is_sequential(ump, ip->i_db[bn - 1], ip->i_db[bn]);
252			    ++bn, ++*runp);
253			bn = bnb;
254			if (runb && (bn > 0)) {
255				for (--bn; (bn >= 0) && (*runb < maxrun) &&
256					is_sequential(ump, ip->i_db[bn],
257						ip->i_db[bn + 1]);
258						--bn, ++*runb);
259			}
260		}
261		return (0);
262	}
263
264	/* Get disk address out of indirect block array */
265	daddr = ip->i_ib[ap->in_off];
266
267	for (bp = NULL, ++ap; --num; ++ap) {
268		/*
269		 * Exit the loop if there is no disk address assigned yet and
270		 * the indirect block isn't in the cache, or if we were
271		 * looking for an indirect block and we've found it.
272		 */
273
274		metalbn = ap->in_lbn;
275		if ((daddr == 0 && !incore(&vp->v_bufobj, metalbn)) || metalbn == bn)
276			break;
277		/*
278		 * If we get here, we've either got the block in the cache
279		 * or we have a disk address for it, go fetch it.
280		 */
281		if (bp)
282			bqrelse(bp);
283		error = readindir(vp, metalbn, daddr, &bp);
284		if (error != 0)
285			return (error);
286
287		daddr = le32toh(((e2fs_daddr_t *)bp->b_data)[ap->in_off]);
288		if (num == 1 && daddr && runp) {
289			for (bn = ap->in_off + 1;
290			    bn < MNINDIR(ump) && *runp < maxrun &&
291			    is_sequential(ump,
292			    ((e2fs_daddr_t *)bp->b_data)[bn - 1],
293			    ((e2fs_daddr_t *)bp->b_data)[bn]);
294			    ++bn, ++*runp);
295			bn = ap->in_off;
296			if (runb && bn) {
297				for (--bn; bn >= 0 && *runb < maxrun &&
298					is_sequential(ump,
299					((e2fs_daddr_t *)bp->b_data)[bn],
300					((e2fs_daddr_t *)bp->b_data)[bn + 1]);
301					--bn, ++*runb);
302			}
303		}
304	}
305	if (bp)
306		bqrelse(bp);
307
308	*bnp = blkptrtodb(ump, daddr);
309	if (*bnp == 0) {
310		*bnp = -1;
311	}
312	return (0);
313}
314
315static e2fs_lbn_t
316lbn_count(struct ext2mount *ump, int level)
317
318{
319	e2fs_lbn_t blockcnt;
320
321	for (blockcnt = 1; level > 0; level--)
322		blockcnt *= MNINDIR(ump);
323	return (blockcnt);
324}
325
326int
327ext2_bmap_seekdata(struct vnode *vp, off_t *offp)
328{
329	struct buf *bp;
330	struct indir a[EXT2_NIADDR + 1], *ap;
331	struct inode *ip;
332	struct mount *mp;
333	struct ext2mount *ump;
334	e2fs_daddr_t bn, daddr, nextbn;
335	uint64_t bsize;
336	off_t numblks;
337	int error, num, num1, off;
338
339	bp = NULL;
340	error = 0;
341	ip = VTOI(vp);
342	mp = vp->v_mount;
343	ump = VFSTOEXT2(mp);
344
345	if (vp->v_type != VREG)
346		return (EINVAL);
347	if (*offp < 0 || *offp >= ip->i_size)
348		return (ENXIO);
349
350	bsize = mp->mnt_stat.f_iosize;
351	for (bn = *offp / bsize, numblks = howmany(ip->i_size, bsize);
352	    bn < numblks; bn = nextbn) {
353		if (bn < EXT2_NDADDR) {
354			daddr = ip->i_db[bn];
355			if (daddr != 0)
356				break;
357			nextbn = bn + 1;
358			continue;
359		}
360
361		ap = a;
362		error = ext2_getlbns(vp, bn, ap, &num);
363		if (error != 0)
364			break;
365		MPASS(num >= 2);
366		daddr = ip->i_ib[ap->in_off];
367		ap++, num--;
368		for (nextbn = EXT2_NDADDR, num1 = num - 1; num1 > 0; num1--)
369			nextbn += lbn_count(ump, num1);
370		if (daddr == 0) {
371			nextbn += lbn_count(ump, num);
372			continue;
373		}
374
375		for (; daddr != 0 && num > 0; ap++, num--) {
376			if (bp != NULL)
377				bqrelse(bp);
378			error = readindir(vp, ap->in_lbn, daddr, &bp);
379			if (error != 0)
380				return (error);
381
382			/*
383			 * Scan the indirect block until we find a non-zero
384			 * pointer.
385			 */
386			off = ap->in_off;
387			do {
388				daddr = le32toh(((e2fs_daddr_t *)bp->b_data)[off]);
389			} while (daddr == 0 && ++off < MNINDIR(ump));
390			nextbn += off * lbn_count(ump, num - 1);
391
392			/*
393			 * We need to recompute the LBNs of indirect
394			 * blocks, so restart with the updated block offset.
395			 */
396			if (off != ap->in_off)
397				break;
398		}
399		if (num == 0) {
400			/*
401			 * We found a data block.
402			 */
403			bn = nextbn;
404			break;
405		}
406	}
407	if (bp != NULL)
408		bqrelse(bp);
409	if (bn >= numblks)
410		error = ENXIO;
411	if (error == 0 && *offp < bn * bsize)
412		*offp = bn * bsize;
413	return (error);
414}
415
416/*
417 * Create an array of logical block number/offset pairs which represent the
418 * path of indirect blocks required to access a data block.  The first "pair"
419 * contains the logical block number of the appropriate single, double or
420 * triple indirect block and the offset into the inode indirect block array.
421 * Note, the logical block number of the inode single/double/triple indirect
422 * block appears twice in the array, once with the offset into the i_ib and
423 * once with the offset into the page itself.
424 */
425int
426ext2_getlbns(struct vnode *vp, daddr_t bn, struct indir *ap, int *nump)
427{
428	long blockcnt;
429	e2fs_lbn_t metalbn, realbn;
430	struct ext2mount *ump;
431	int i, numlevels, off;
432	int64_t qblockcnt;
433
434	ump = VFSTOEXT2(vp->v_mount);
435	if (nump)
436		*nump = 0;
437	numlevels = 0;
438	realbn = bn;
439	if ((long)bn < 0)
440		bn = -(long)bn;
441
442	/* The first EXT2_NDADDR blocks are direct blocks. */
443	if (bn < EXT2_NDADDR)
444		return (0);
445
446	/*
447	 * Determine the number of levels of indirection.  After this loop
448	 * is done, blockcnt indicates the number of data blocks possible
449	 * at the previous level of indirection, and EXT2_NIADDR - i is the
450	 * number of levels of indirection needed to locate the requested block.
451	 */
452	for (blockcnt = 1, i = EXT2_NIADDR, bn -= EXT2_NDADDR; ;
453	    i--, bn -= blockcnt) {
454		if (i == 0)
455			return (EFBIG);
456		/*
457		 * Use int64_t's here to avoid overflow for triple indirect
458		 * blocks when longs have 32 bits and the block size is more
459		 * than 4K.
460		 */
461		qblockcnt = (int64_t)blockcnt * MNINDIR(ump);
462		if (bn < qblockcnt)
463			break;
464		blockcnt = qblockcnt;
465	}
466
467	/* Calculate the address of the first meta-block. */
468	if (realbn >= 0)
469		metalbn = -(realbn - bn + EXT2_NIADDR - i);
470	else
471		metalbn = -(-realbn - bn + EXT2_NIADDR - i);
472
473	/*
474	 * At each iteration, off is the offset into the bap array which is
475	 * an array of disk addresses at the current level of indirection.
476	 * The logical block number and the offset in that block are stored
477	 * into the argument array.
478	 */
479	ap->in_lbn = metalbn;
480	ap->in_off = off = EXT2_NIADDR - i;
481	ap++;
482	for (++numlevels; i <= EXT2_NIADDR; i++) {
483		/* If searching for a meta-data block, quit when found. */
484		if (metalbn == realbn)
485			break;
486
487		off = (bn / blockcnt) % MNINDIR(ump);
488
489		++numlevels;
490		ap->in_lbn = metalbn;
491		ap->in_off = off;
492		++ap;
493
494		metalbn -= -1 + off * blockcnt;
495		blockcnt /= MNINDIR(ump);
496	}
497	if (nump)
498		*nump = numlevels;
499	return (0);
500}
501