• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   Copyright (C) International Business Machines Corp., 2000-2004
4  *   Portions Copyright (C) Tino Reichardt, 2012
5  */
6 
7 #include <linux/fs.h>
8 #include <linux/slab.h>
9 #include "jfs_incore.h"
10 #include "jfs_superblock.h"
11 #include "jfs_dmap.h"
12 #include "jfs_imap.h"
13 #include "jfs_lock.h"
14 #include "jfs_metapage.h"
15 #include "jfs_debug.h"
16 #include "jfs_discard.h"
17 
18 /*
19  *	SERIALIZATION of the Block Allocation Map.
20  *
21  *	the working state of the block allocation map is accessed in
22  *	two directions:
23  *
24  *	1) allocation and free requests that start at the dmap
25  *	   level and move up through the dmap control pages (i.e.
26  *	   the vast majority of requests).
27  *
28  *	2) allocation requests that start at dmap control page
29  *	   level and work down towards the dmaps.
30  *
31  *	the serialization scheme used here is as follows.
32  *
33  *	requests which start at the bottom are serialized against each
34  *	other through buffers and each requests holds onto its buffers
35  *	as it works it way up from a single dmap to the required level
36  *	of dmap control page.
37  *	requests that start at the top are serialized against each other
38  *	and request that start from the bottom by the multiple read/single
39  *	write inode lock of the bmap inode. requests starting at the top
40  *	take this lock in write mode while request starting at the bottom
41  *	take the lock in read mode.  a single top-down request may proceed
42  *	exclusively while multiple bottoms-up requests may proceed
43  *	simultaneously (under the protection of busy buffers).
44  *
45  *	in addition to information found in dmaps and dmap control pages,
46  *	the working state of the block allocation map also includes read/
47  *	write information maintained in the bmap descriptor (i.e. total
48  *	free block count, allocation group level free block counts).
49  *	a single exclusive lock (BMAP_LOCK) is used to guard this information
50  *	in the face of multiple-bottoms up requests.
51  *	(lock ordering: IREAD_LOCK, BMAP_LOCK);
52  *
53  *	accesses to the persistent state of the block allocation map (limited
54  *	to the persistent bitmaps in dmaps) is guarded by (busy) buffers.
55  */
56 
57 #define BMAP_LOCK_INIT(bmp)	mutex_init(&bmp->db_bmaplock)
58 #define BMAP_LOCK(bmp)		mutex_lock(&bmp->db_bmaplock)
59 #define BMAP_UNLOCK(bmp)	mutex_unlock(&bmp->db_bmaplock)
60 
61 /*
62  * forward references
63  */
64 static void dbAllocBits(struct bmap * bmp, struct dmap * dp, s64 blkno,
65 			int nblocks);
66 static void dbSplit(dmtree_t * tp, int leafno, int splitsz, int newval);
67 static int dbBackSplit(dmtree_t * tp, int leafno);
68 static int dbJoin(dmtree_t * tp, int leafno, int newval);
69 static void dbAdjTree(dmtree_t * tp, int leafno, int newval);
70 static int dbAdjCtl(struct bmap * bmp, s64 blkno, int newval, int alloc,
71 		    int level);
72 static int dbAllocAny(struct bmap * bmp, s64 nblocks, int l2nb, s64 * results);
73 static int dbAllocNext(struct bmap * bmp, struct dmap * dp, s64 blkno,
74 		       int nblocks);
75 static int dbAllocNear(struct bmap * bmp, struct dmap * dp, s64 blkno,
76 		       int nblocks,
77 		       int l2nb, s64 * results);
78 static int dbAllocDmap(struct bmap * bmp, struct dmap * dp, s64 blkno,
79 		       int nblocks);
80 static int dbAllocDmapLev(struct bmap * bmp, struct dmap * dp, int nblocks,
81 			  int l2nb,
82 			  s64 * results);
83 static int dbAllocAG(struct bmap * bmp, int agno, s64 nblocks, int l2nb,
84 		     s64 * results);
85 static int dbAllocCtl(struct bmap * bmp, s64 nblocks, int l2nb, s64 blkno,
86 		      s64 * results);
87 static int dbExtend(struct inode *ip, s64 blkno, s64 nblocks, s64 addnblocks);
88 static int dbFindBits(u32 word, int l2nb);
89 static int dbFindCtl(struct bmap * bmp, int l2nb, int level, s64 * blkno);
90 static int dbFindLeaf(dmtree_t * tp, int l2nb, int *leafidx);
91 static int dbFreeBits(struct bmap * bmp, struct dmap * dp, s64 blkno,
92 		      int nblocks);
93 static int dbFreeDmap(struct bmap * bmp, struct dmap * dp, s64 blkno,
94 		      int nblocks);
95 static int dbMaxBud(u8 * cp);
96 static int blkstol2(s64 nb);
97 
98 static int cntlz(u32 value);
99 static int cnttz(u32 word);
100 
101 static int dbAllocDmapBU(struct bmap * bmp, struct dmap * dp, s64 blkno,
102 			 int nblocks);
103 static int dbInitDmap(struct dmap * dp, s64 blkno, int nblocks);
104 static int dbInitDmapTree(struct dmap * dp);
105 static int dbInitTree(struct dmaptree * dtp);
106 static int dbInitDmapCtl(struct dmapctl * dcp, int level, int i);
107 static int dbGetL2AGSize(s64 nblocks);
108 
109 /*
110  *	buddy table
111  *
112  * table used for determining buddy sizes within characters of
113  * dmap bitmap words.  the characters themselves serve as indexes
114  * into the table, with the table elements yielding the maximum
115  * binary buddy of free bits within the character.
116  */
117 static const s8 budtab[256] = {
118 	3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
119 	2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
120 	2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
121 	2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
122 	2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
123 	2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
124 	2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
125 	2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
126 	2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
127 	2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
128 	2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
129 	2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
130 	2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
131 	2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
132 	2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
133 	2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, -1
134 };
135 
136 /*
137  * NAME:	dbMount()
138  *
139  * FUNCTION:	initializate the block allocation map.
140  *
141  *		memory is allocated for the in-core bmap descriptor and
142  *		the in-core descriptor is initialized from disk.
143  *
144  * PARAMETERS:
145  *	ipbmap	- pointer to in-core inode for the block map.
146  *
147  * RETURN VALUES:
148  *	0	- success
149  *	-ENOMEM	- insufficient memory
150  *	-EIO	- i/o error
151  *	-EINVAL - wrong bmap data
152  */
dbMount(struct inode * ipbmap)153 int dbMount(struct inode *ipbmap)
154 {
155 	struct bmap *bmp;
156 	struct dbmap_disk *dbmp_le;
157 	struct metapage *mp;
158 	int i, err;
159 
160 	/*
161 	 * allocate/initialize the in-memory bmap descriptor
162 	 */
163 	/* allocate memory for the in-memory bmap descriptor */
164 	bmp = kmalloc(sizeof(struct bmap), GFP_KERNEL);
165 	if (bmp == NULL)
166 		return -ENOMEM;
167 
168 	/* read the on-disk bmap descriptor. */
169 	mp = read_metapage(ipbmap,
170 			   BMAPBLKNO << JFS_SBI(ipbmap->i_sb)->l2nbperpage,
171 			   PSIZE, 0);
172 	if (mp == NULL) {
173 		err = -EIO;
174 		goto err_kfree_bmp;
175 	}
176 
177 	/* copy the on-disk bmap descriptor to its in-memory version. */
178 	dbmp_le = (struct dbmap_disk *) mp->data;
179 	bmp->db_mapsize = le64_to_cpu(dbmp_le->dn_mapsize);
180 	bmp->db_nfree = le64_to_cpu(dbmp_le->dn_nfree);
181 	bmp->db_l2nbperpage = le32_to_cpu(dbmp_le->dn_l2nbperpage);
182 	bmp->db_numag = le32_to_cpu(dbmp_le->dn_numag);
183 	if (!bmp->db_numag) {
184 		err = -EINVAL;
185 		goto err_release_metapage;
186 	}
187 
188 	bmp->db_maxlevel = le32_to_cpu(dbmp_le->dn_maxlevel);
189 	bmp->db_maxag = le32_to_cpu(dbmp_le->dn_maxag);
190 	bmp->db_agpref = le32_to_cpu(dbmp_le->dn_agpref);
191 	bmp->db_aglevel = le32_to_cpu(dbmp_le->dn_aglevel);
192 	bmp->db_agheight = le32_to_cpu(dbmp_le->dn_agheight);
193 	bmp->db_agwidth = le32_to_cpu(dbmp_le->dn_agwidth);
194 	bmp->db_agstart = le32_to_cpu(dbmp_le->dn_agstart);
195 	bmp->db_agl2size = le32_to_cpu(dbmp_le->dn_agl2size);
196 	if (bmp->db_agl2size > L2MAXL2SIZE - L2MAXAG) {
197 		err = -EINVAL;
198 		goto err_release_metapage;
199 	}
200 
201 	if (((bmp->db_mapsize - 1) >> bmp->db_agl2size) > MAXAG) {
202 		err = -EINVAL;
203 		goto err_release_metapage;
204 	}
205 
206 	for (i = 0; i < MAXAG; i++)
207 		bmp->db_agfree[i] = le64_to_cpu(dbmp_le->dn_agfree[i]);
208 	bmp->db_agsize = le64_to_cpu(dbmp_le->dn_agsize);
209 	bmp->db_maxfreebud = dbmp_le->dn_maxfreebud;
210 
211 	/* release the buffer. */
212 	release_metapage(mp);
213 
214 	/* bind the bmap inode and the bmap descriptor to each other. */
215 	bmp->db_ipbmap = ipbmap;
216 	JFS_SBI(ipbmap->i_sb)->bmap = bmp;
217 
218 	memset(bmp->db_active, 0, sizeof(bmp->db_active));
219 
220 	/*
221 	 * allocate/initialize the bmap lock
222 	 */
223 	BMAP_LOCK_INIT(bmp);
224 
225 	return (0);
226 
227 err_release_metapage:
228 	release_metapage(mp);
229 err_kfree_bmp:
230 	kfree(bmp);
231 	return err;
232 }
233 
234 
235 /*
236  * NAME:	dbUnmount()
237  *
238  * FUNCTION:	terminate the block allocation map in preparation for
239  *		file system unmount.
240  *
241  *		the in-core bmap descriptor is written to disk and
242  *		the memory for this descriptor is freed.
243  *
244  * PARAMETERS:
245  *	ipbmap	- pointer to in-core inode for the block map.
246  *
247  * RETURN VALUES:
248  *	0	- success
249  *	-EIO	- i/o error
250  */
dbUnmount(struct inode * ipbmap,int mounterror)251 int dbUnmount(struct inode *ipbmap, int mounterror)
252 {
253 	struct bmap *bmp = JFS_SBI(ipbmap->i_sb)->bmap;
254 
255 	if (!(mounterror || isReadOnly(ipbmap)))
256 		dbSync(ipbmap);
257 
258 	/*
259 	 * Invalidate the page cache buffers
260 	 */
261 	truncate_inode_pages(ipbmap->i_mapping, 0);
262 
263 	/* free the memory for the in-memory bmap. */
264 	kfree(bmp);
265 
266 	return (0);
267 }
268 
269 /*
270  *	dbSync()
271  */
dbSync(struct inode * ipbmap)272 int dbSync(struct inode *ipbmap)
273 {
274 	struct dbmap_disk *dbmp_le;
275 	struct bmap *bmp = JFS_SBI(ipbmap->i_sb)->bmap;
276 	struct metapage *mp;
277 	int i;
278 
279 	/*
280 	 * write bmap global control page
281 	 */
282 	/* get the buffer for the on-disk bmap descriptor. */
283 	mp = read_metapage(ipbmap,
284 			   BMAPBLKNO << JFS_SBI(ipbmap->i_sb)->l2nbperpage,
285 			   PSIZE, 0);
286 	if (mp == NULL) {
287 		jfs_err("dbSync: read_metapage failed!");
288 		return -EIO;
289 	}
290 	/* copy the in-memory version of the bmap to the on-disk version */
291 	dbmp_le = (struct dbmap_disk *) mp->data;
292 	dbmp_le->dn_mapsize = cpu_to_le64(bmp->db_mapsize);
293 	dbmp_le->dn_nfree = cpu_to_le64(bmp->db_nfree);
294 	dbmp_le->dn_l2nbperpage = cpu_to_le32(bmp->db_l2nbperpage);
295 	dbmp_le->dn_numag = cpu_to_le32(bmp->db_numag);
296 	dbmp_le->dn_maxlevel = cpu_to_le32(bmp->db_maxlevel);
297 	dbmp_le->dn_maxag = cpu_to_le32(bmp->db_maxag);
298 	dbmp_le->dn_agpref = cpu_to_le32(bmp->db_agpref);
299 	dbmp_le->dn_aglevel = cpu_to_le32(bmp->db_aglevel);
300 	dbmp_le->dn_agheight = cpu_to_le32(bmp->db_agheight);
301 	dbmp_le->dn_agwidth = cpu_to_le32(bmp->db_agwidth);
302 	dbmp_le->dn_agstart = cpu_to_le32(bmp->db_agstart);
303 	dbmp_le->dn_agl2size = cpu_to_le32(bmp->db_agl2size);
304 	for (i = 0; i < MAXAG; i++)
305 		dbmp_le->dn_agfree[i] = cpu_to_le64(bmp->db_agfree[i]);
306 	dbmp_le->dn_agsize = cpu_to_le64(bmp->db_agsize);
307 	dbmp_le->dn_maxfreebud = bmp->db_maxfreebud;
308 
309 	/* write the buffer */
310 	write_metapage(mp);
311 
312 	/*
313 	 * write out dirty pages of bmap
314 	 */
315 	filemap_write_and_wait(ipbmap->i_mapping);
316 
317 	diWriteSpecial(ipbmap, 0);
318 
319 	return (0);
320 }
321 
322 /*
323  * NAME:	dbFree()
324  *
325  * FUNCTION:	free the specified block range from the working block
326  *		allocation map.
327  *
328  *		the blocks will be free from the working map one dmap
329  *		at a time.
330  *
331  * PARAMETERS:
332  *	ip	- pointer to in-core inode;
333  *	blkno	- starting block number to be freed.
334  *	nblocks	- number of blocks to be freed.
335  *
336  * RETURN VALUES:
337  *	0	- success
338  *	-EIO	- i/o error
339  */
dbFree(struct inode * ip,s64 blkno,s64 nblocks)340 int dbFree(struct inode *ip, s64 blkno, s64 nblocks)
341 {
342 	struct metapage *mp;
343 	struct dmap *dp;
344 	int nb, rc;
345 	s64 lblkno, rem;
346 	struct inode *ipbmap = JFS_SBI(ip->i_sb)->ipbmap;
347 	struct bmap *bmp = JFS_SBI(ip->i_sb)->bmap;
348 	struct super_block *sb = ipbmap->i_sb;
349 
350 	IREAD_LOCK(ipbmap, RDWRLOCK_DMAP);
351 
352 	/* block to be freed better be within the mapsize. */
353 	if (unlikely((blkno == 0) || (blkno + nblocks > bmp->db_mapsize))) {
354 		IREAD_UNLOCK(ipbmap);
355 		printk(KERN_ERR "blkno = %Lx, nblocks = %Lx\n",
356 		       (unsigned long long) blkno,
357 		       (unsigned long long) nblocks);
358 		jfs_error(ip->i_sb, "block to be freed is outside the map\n");
359 		return -EIO;
360 	}
361 
362 	/**
363 	 * TRIM the blocks, when mounted with discard option
364 	 */
365 	if (JFS_SBI(sb)->flag & JFS_DISCARD)
366 		if (JFS_SBI(sb)->minblks_trim <= nblocks)
367 			jfs_issue_discard(ipbmap, blkno, nblocks);
368 
369 	/*
370 	 * free the blocks a dmap at a time.
371 	 */
372 	mp = NULL;
373 	for (rem = nblocks; rem > 0; rem -= nb, blkno += nb) {
374 		/* release previous dmap if any */
375 		if (mp) {
376 			write_metapage(mp);
377 		}
378 
379 		/* get the buffer for the current dmap. */
380 		lblkno = BLKTODMAP(blkno, bmp->db_l2nbperpage);
381 		mp = read_metapage(ipbmap, lblkno, PSIZE, 0);
382 		if (mp == NULL) {
383 			IREAD_UNLOCK(ipbmap);
384 			return -EIO;
385 		}
386 		dp = (struct dmap *) mp->data;
387 
388 		/* determine the number of blocks to be freed from
389 		 * this dmap.
390 		 */
391 		nb = min(rem, BPERDMAP - (blkno & (BPERDMAP - 1)));
392 
393 		/* free the blocks. */
394 		if ((rc = dbFreeDmap(bmp, dp, blkno, nb))) {
395 			jfs_error(ip->i_sb, "error in block map\n");
396 			release_metapage(mp);
397 			IREAD_UNLOCK(ipbmap);
398 			return (rc);
399 		}
400 	}
401 
402 	/* write the last buffer. */
403 	if (mp)
404 		write_metapage(mp);
405 
406 	IREAD_UNLOCK(ipbmap);
407 
408 	return (0);
409 }
410 
411 
412 /*
413  * NAME:	dbUpdatePMap()
414  *
415  * FUNCTION:	update the allocation state (free or allocate) of the
416  *		specified block range in the persistent block allocation map.
417  *
418  *		the blocks will be updated in the persistent map one
419  *		dmap at a time.
420  *
421  * PARAMETERS:
422  *	ipbmap	- pointer to in-core inode for the block map.
423  *	free	- 'true' if block range is to be freed from the persistent
424  *		  map; 'false' if it is to be allocated.
425  *	blkno	- starting block number of the range.
426  *	nblocks	- number of contiguous blocks in the range.
427  *	tblk	- transaction block;
428  *
429  * RETURN VALUES:
430  *	0	- success
431  *	-EIO	- i/o error
432  */
433 int
dbUpdatePMap(struct inode * ipbmap,int free,s64 blkno,s64 nblocks,struct tblock * tblk)434 dbUpdatePMap(struct inode *ipbmap,
435 	     int free, s64 blkno, s64 nblocks, struct tblock * tblk)
436 {
437 	int nblks, dbitno, wbitno, rbits;
438 	int word, nbits, nwords;
439 	struct bmap *bmp = JFS_SBI(ipbmap->i_sb)->bmap;
440 	s64 lblkno, rem, lastlblkno;
441 	u32 mask;
442 	struct dmap *dp;
443 	struct metapage *mp;
444 	struct jfs_log *log;
445 	int lsn, difft, diffp;
446 	unsigned long flags;
447 
448 	/* the blocks better be within the mapsize. */
449 	if (blkno + nblocks > bmp->db_mapsize) {
450 		printk(KERN_ERR "blkno = %Lx, nblocks = %Lx\n",
451 		       (unsigned long long) blkno,
452 		       (unsigned long long) nblocks);
453 		jfs_error(ipbmap->i_sb, "blocks are outside the map\n");
454 		return -EIO;
455 	}
456 
457 	/* compute delta of transaction lsn from log syncpt */
458 	lsn = tblk->lsn;
459 	log = (struct jfs_log *) JFS_SBI(tblk->sb)->log;
460 	logdiff(difft, lsn, log);
461 
462 	/*
463 	 * update the block state a dmap at a time.
464 	 */
465 	mp = NULL;
466 	lastlblkno = 0;
467 	for (rem = nblocks; rem > 0; rem -= nblks, blkno += nblks) {
468 		/* get the buffer for the current dmap. */
469 		lblkno = BLKTODMAP(blkno, bmp->db_l2nbperpage);
470 		if (lblkno != lastlblkno) {
471 			if (mp) {
472 				write_metapage(mp);
473 			}
474 
475 			mp = read_metapage(bmp->db_ipbmap, lblkno, PSIZE,
476 					   0);
477 			if (mp == NULL)
478 				return -EIO;
479 			metapage_wait_for_io(mp);
480 		}
481 		dp = (struct dmap *) mp->data;
482 
483 		/* determine the bit number and word within the dmap of
484 		 * the starting block.  also determine how many blocks
485 		 * are to be updated within this dmap.
486 		 */
487 		dbitno = blkno & (BPERDMAP - 1);
488 		word = dbitno >> L2DBWORD;
489 		nblks = min(rem, (s64)BPERDMAP - dbitno);
490 
491 		/* update the bits of the dmap words. the first and last
492 		 * words may only have a subset of their bits updated. if
493 		 * this is the case, we'll work against that word (i.e.
494 		 * partial first and/or last) only in a single pass.  a
495 		 * single pass will also be used to update all words that
496 		 * are to have all their bits updated.
497 		 */
498 		for (rbits = nblks; rbits > 0;
499 		     rbits -= nbits, dbitno += nbits) {
500 			/* determine the bit number within the word and
501 			 * the number of bits within the word.
502 			 */
503 			wbitno = dbitno & (DBWORD - 1);
504 			nbits = min(rbits, DBWORD - wbitno);
505 
506 			/* check if only part of the word is to be updated. */
507 			if (nbits < DBWORD) {
508 				/* update (free or allocate) the bits
509 				 * in this word.
510 				 */
511 				mask =
512 				    (ONES << (DBWORD - nbits) >> wbitno);
513 				if (free)
514 					dp->pmap[word] &=
515 					    cpu_to_le32(~mask);
516 				else
517 					dp->pmap[word] |=
518 					    cpu_to_le32(mask);
519 
520 				word += 1;
521 			} else {
522 				/* one or more words are to have all
523 				 * their bits updated.  determine how
524 				 * many words and how many bits.
525 				 */
526 				nwords = rbits >> L2DBWORD;
527 				nbits = nwords << L2DBWORD;
528 
529 				/* update (free or allocate) the bits
530 				 * in these words.
531 				 */
532 				if (free)
533 					memset(&dp->pmap[word], 0,
534 					       nwords * 4);
535 				else
536 					memset(&dp->pmap[word], (int) ONES,
537 					       nwords * 4);
538 
539 				word += nwords;
540 			}
541 		}
542 
543 		/*
544 		 * update dmap lsn
545 		 */
546 		if (lblkno == lastlblkno)
547 			continue;
548 
549 		lastlblkno = lblkno;
550 
551 		LOGSYNC_LOCK(log, flags);
552 		if (mp->lsn != 0) {
553 			/* inherit older/smaller lsn */
554 			logdiff(diffp, mp->lsn, log);
555 			if (difft < diffp) {
556 				mp->lsn = lsn;
557 
558 				/* move bp after tblock in logsync list */
559 				list_move(&mp->synclist, &tblk->synclist);
560 			}
561 
562 			/* inherit younger/larger clsn */
563 			logdiff(difft, tblk->clsn, log);
564 			logdiff(diffp, mp->clsn, log);
565 			if (difft > diffp)
566 				mp->clsn = tblk->clsn;
567 		} else {
568 			mp->log = log;
569 			mp->lsn = lsn;
570 
571 			/* insert bp after tblock in logsync list */
572 			log->count++;
573 			list_add(&mp->synclist, &tblk->synclist);
574 
575 			mp->clsn = tblk->clsn;
576 		}
577 		LOGSYNC_UNLOCK(log, flags);
578 	}
579 
580 	/* write the last buffer. */
581 	if (mp) {
582 		write_metapage(mp);
583 	}
584 
585 	return (0);
586 }
587 
588 
589 /*
590  * NAME:	dbNextAG()
591  *
592  * FUNCTION:	find the preferred allocation group for new allocations.
593  *
594  *		Within the allocation groups, we maintain a preferred
595  *		allocation group which consists of a group with at least
596  *		average free space.  It is the preferred group that we target
597  *		new inode allocation towards.  The tie-in between inode
598  *		allocation and block allocation occurs as we allocate the
599  *		first (data) block of an inode and specify the inode (block)
600  *		as the allocation hint for this block.
601  *
602  *		We try to avoid having more than one open file growing in
603  *		an allocation group, as this will lead to fragmentation.
604  *		This differs from the old OS/2 method of trying to keep
605  *		empty ags around for large allocations.
606  *
607  * PARAMETERS:
608  *	ipbmap	- pointer to in-core inode for the block map.
609  *
610  * RETURN VALUES:
611  *	the preferred allocation group number.
612  */
dbNextAG(struct inode * ipbmap)613 int dbNextAG(struct inode *ipbmap)
614 {
615 	s64 avgfree;
616 	int agpref;
617 	s64 hwm = 0;
618 	int i;
619 	int next_best = -1;
620 	struct bmap *bmp = JFS_SBI(ipbmap->i_sb)->bmap;
621 
622 	BMAP_LOCK(bmp);
623 
624 	/* determine the average number of free blocks within the ags. */
625 	avgfree = (u32)bmp->db_nfree / bmp->db_numag;
626 
627 	/*
628 	 * if the current preferred ag does not have an active allocator
629 	 * and has at least average freespace, return it
630 	 */
631 	agpref = bmp->db_agpref;
632 	if ((atomic_read(&bmp->db_active[agpref]) == 0) &&
633 	    (bmp->db_agfree[agpref] >= avgfree))
634 		goto unlock;
635 
636 	/* From the last preferred ag, find the next one with at least
637 	 * average free space.
638 	 */
639 	for (i = 0 ; i < bmp->db_numag; i++, agpref++) {
640 		if (agpref == bmp->db_numag)
641 			agpref = 0;
642 
643 		if (atomic_read(&bmp->db_active[agpref]))
644 			/* open file is currently growing in this ag */
645 			continue;
646 		if (bmp->db_agfree[agpref] >= avgfree) {
647 			/* Return this one */
648 			bmp->db_agpref = agpref;
649 			goto unlock;
650 		} else if (bmp->db_agfree[agpref] > hwm) {
651 			/* Less than avg. freespace, but best so far */
652 			hwm = bmp->db_agfree[agpref];
653 			next_best = agpref;
654 		}
655 	}
656 
657 	/*
658 	 * If no inactive ag was found with average freespace, use the
659 	 * next best
660 	 */
661 	if (next_best != -1)
662 		bmp->db_agpref = next_best;
663 	/* else leave db_agpref unchanged */
664 unlock:
665 	BMAP_UNLOCK(bmp);
666 
667 	/* return the preferred group.
668 	 */
669 	return (bmp->db_agpref);
670 }
671 
672 /*
673  * NAME:	dbAlloc()
674  *
675  * FUNCTION:	attempt to allocate a specified number of contiguous free
676  *		blocks from the working allocation block map.
677  *
678  *		the block allocation policy uses hints and a multi-step
679  *		approach.
680  *
681  *		for allocation requests smaller than the number of blocks
682  *		per dmap, we first try to allocate the new blocks
683  *		immediately following the hint.  if these blocks are not
684  *		available, we try to allocate blocks near the hint.  if
685  *		no blocks near the hint are available, we next try to
686  *		allocate within the same dmap as contains the hint.
687  *
688  *		if no blocks are available in the dmap or the allocation
689  *		request is larger than the dmap size, we try to allocate
690  *		within the same allocation group as contains the hint. if
691  *		this does not succeed, we finally try to allocate anywhere
692  *		within the aggregate.
693  *
694  *		we also try to allocate anywhere within the aggregate for
695  *		for allocation requests larger than the allocation group
696  *		size or requests that specify no hint value.
697  *
698  * PARAMETERS:
699  *	ip	- pointer to in-core inode;
700  *	hint	- allocation hint.
701  *	nblocks	- number of contiguous blocks in the range.
702  *	results	- on successful return, set to the starting block number
703  *		  of the newly allocated contiguous range.
704  *
705  * RETURN VALUES:
706  *	0	- success
707  *	-ENOSPC	- insufficient disk resources
708  *	-EIO	- i/o error
709  */
dbAlloc(struct inode * ip,s64 hint,s64 nblocks,s64 * results)710 int dbAlloc(struct inode *ip, s64 hint, s64 nblocks, s64 * results)
711 {
712 	int rc, agno;
713 	struct inode *ipbmap = JFS_SBI(ip->i_sb)->ipbmap;
714 	struct bmap *bmp;
715 	struct metapage *mp;
716 	s64 lblkno, blkno;
717 	struct dmap *dp;
718 	int l2nb;
719 	s64 mapSize;
720 	int writers;
721 
722 	/* assert that nblocks is valid */
723 	assert(nblocks > 0);
724 
725 	/* get the log2 number of blocks to be allocated.
726 	 * if the number of blocks is not a log2 multiple,
727 	 * it will be rounded up to the next log2 multiple.
728 	 */
729 	l2nb = BLKSTOL2(nblocks);
730 
731 	bmp = JFS_SBI(ip->i_sb)->bmap;
732 
733 	mapSize = bmp->db_mapsize;
734 
735 	/* the hint should be within the map */
736 	if (hint >= mapSize) {
737 		jfs_error(ip->i_sb, "the hint is outside the map\n");
738 		return -EIO;
739 	}
740 
741 	/* if the number of blocks to be allocated is greater than the
742 	 * allocation group size, try to allocate anywhere.
743 	 */
744 	if (l2nb > bmp->db_agl2size) {
745 		IWRITE_LOCK(ipbmap, RDWRLOCK_DMAP);
746 
747 		rc = dbAllocAny(bmp, nblocks, l2nb, results);
748 
749 		goto write_unlock;
750 	}
751 
752 	/*
753 	 * If no hint, let dbNextAG recommend an allocation group
754 	 */
755 	if (hint == 0)
756 		goto pref_ag;
757 
758 	/* we would like to allocate close to the hint.  adjust the
759 	 * hint to the block following the hint since the allocators
760 	 * will start looking for free space starting at this point.
761 	 */
762 	blkno = hint + 1;
763 
764 	if (blkno >= bmp->db_mapsize)
765 		goto pref_ag;
766 
767 	agno = blkno >> bmp->db_agl2size;
768 
769 	/* check if blkno crosses over into a new allocation group.
770 	 * if so, check if we should allow allocations within this
771 	 * allocation group.
772 	 */
773 	if ((blkno & (bmp->db_agsize - 1)) == 0)
774 		/* check if the AG is currently being written to.
775 		 * if so, call dbNextAG() to find a non-busy
776 		 * AG with sufficient free space.
777 		 */
778 		if (atomic_read(&bmp->db_active[agno]))
779 			goto pref_ag;
780 
781 	/* check if the allocation request size can be satisfied from a
782 	 * single dmap.  if so, try to allocate from the dmap containing
783 	 * the hint using a tiered strategy.
784 	 */
785 	if (nblocks <= BPERDMAP) {
786 		IREAD_LOCK(ipbmap, RDWRLOCK_DMAP);
787 
788 		/* get the buffer for the dmap containing the hint.
789 		 */
790 		rc = -EIO;
791 		lblkno = BLKTODMAP(blkno, bmp->db_l2nbperpage);
792 		mp = read_metapage(ipbmap, lblkno, PSIZE, 0);
793 		if (mp == NULL)
794 			goto read_unlock;
795 
796 		dp = (struct dmap *) mp->data;
797 
798 		/* first, try to satisfy the allocation request with the
799 		 * blocks beginning at the hint.
800 		 */
801 		if ((rc = dbAllocNext(bmp, dp, blkno, (int) nblocks))
802 		    != -ENOSPC) {
803 			if (rc == 0) {
804 				*results = blkno;
805 				mark_metapage_dirty(mp);
806 			}
807 
808 			release_metapage(mp);
809 			goto read_unlock;
810 		}
811 
812 		writers = atomic_read(&bmp->db_active[agno]);
813 		if ((writers > 1) ||
814 		    ((writers == 1) && (JFS_IP(ip)->active_ag != agno))) {
815 			/*
816 			 * Someone else is writing in this allocation
817 			 * group.  To avoid fragmenting, try another ag
818 			 */
819 			release_metapage(mp);
820 			IREAD_UNLOCK(ipbmap);
821 			goto pref_ag;
822 		}
823 
824 		/* next, try to satisfy the allocation request with blocks
825 		 * near the hint.
826 		 */
827 		if ((rc =
828 		     dbAllocNear(bmp, dp, blkno, (int) nblocks, l2nb, results))
829 		    != -ENOSPC) {
830 			if (rc == 0)
831 				mark_metapage_dirty(mp);
832 
833 			release_metapage(mp);
834 			goto read_unlock;
835 		}
836 
837 		/* try to satisfy the allocation request with blocks within
838 		 * the same dmap as the hint.
839 		 */
840 		if ((rc = dbAllocDmapLev(bmp, dp, (int) nblocks, l2nb, results))
841 		    != -ENOSPC) {
842 			if (rc == 0)
843 				mark_metapage_dirty(mp);
844 
845 			release_metapage(mp);
846 			goto read_unlock;
847 		}
848 
849 		release_metapage(mp);
850 		IREAD_UNLOCK(ipbmap);
851 	}
852 
853 	/* try to satisfy the allocation request with blocks within
854 	 * the same allocation group as the hint.
855 	 */
856 	IWRITE_LOCK(ipbmap, RDWRLOCK_DMAP);
857 	if ((rc = dbAllocAG(bmp, agno, nblocks, l2nb, results)) != -ENOSPC)
858 		goto write_unlock;
859 
860 	IWRITE_UNLOCK(ipbmap);
861 
862 
863       pref_ag:
864 	/*
865 	 * Let dbNextAG recommend a preferred allocation group
866 	 */
867 	agno = dbNextAG(ipbmap);
868 	IWRITE_LOCK(ipbmap, RDWRLOCK_DMAP);
869 
870 	/* Try to allocate within this allocation group.  if that fails, try to
871 	 * allocate anywhere in the map.
872 	 */
873 	if ((rc = dbAllocAG(bmp, agno, nblocks, l2nb, results)) == -ENOSPC)
874 		rc = dbAllocAny(bmp, nblocks, l2nb, results);
875 
876       write_unlock:
877 	IWRITE_UNLOCK(ipbmap);
878 
879 	return (rc);
880 
881       read_unlock:
882 	IREAD_UNLOCK(ipbmap);
883 
884 	return (rc);
885 }
886 
887 #ifdef _NOTYET
888 /*
889  * NAME:	dbAllocExact()
890  *
891  * FUNCTION:	try to allocate the requested extent;
892  *
893  * PARAMETERS:
894  *	ip	- pointer to in-core inode;
895  *	blkno	- extent address;
896  *	nblocks	- extent length;
897  *
898  * RETURN VALUES:
899  *	0	- success
900  *	-ENOSPC	- insufficient disk resources
901  *	-EIO	- i/o error
902  */
dbAllocExact(struct inode * ip,s64 blkno,int nblocks)903 int dbAllocExact(struct inode *ip, s64 blkno, int nblocks)
904 {
905 	int rc;
906 	struct inode *ipbmap = JFS_SBI(ip->i_sb)->ipbmap;
907 	struct bmap *bmp = JFS_SBI(ip->i_sb)->bmap;
908 	struct dmap *dp;
909 	s64 lblkno;
910 	struct metapage *mp;
911 
912 	IREAD_LOCK(ipbmap, RDWRLOCK_DMAP);
913 
914 	/*
915 	 * validate extent request:
916 	 *
917 	 * note: defragfs policy:
918 	 *  max 64 blocks will be moved.
919 	 *  allocation request size must be satisfied from a single dmap.
920 	 */
921 	if (nblocks <= 0 || nblocks > BPERDMAP || blkno >= bmp->db_mapsize) {
922 		IREAD_UNLOCK(ipbmap);
923 		return -EINVAL;
924 	}
925 
926 	if (nblocks > ((s64) 1 << bmp->db_maxfreebud)) {
927 		/* the free space is no longer available */
928 		IREAD_UNLOCK(ipbmap);
929 		return -ENOSPC;
930 	}
931 
932 	/* read in the dmap covering the extent */
933 	lblkno = BLKTODMAP(blkno, bmp->db_l2nbperpage);
934 	mp = read_metapage(ipbmap, lblkno, PSIZE, 0);
935 	if (mp == NULL) {
936 		IREAD_UNLOCK(ipbmap);
937 		return -EIO;
938 	}
939 	dp = (struct dmap *) mp->data;
940 
941 	/* try to allocate the requested extent */
942 	rc = dbAllocNext(bmp, dp, blkno, nblocks);
943 
944 	IREAD_UNLOCK(ipbmap);
945 
946 	if (rc == 0)
947 		mark_metapage_dirty(mp);
948 
949 	release_metapage(mp);
950 
951 	return (rc);
952 }
953 #endif /* _NOTYET */
954 
955 /*
956  * NAME:	dbReAlloc()
957  *
958  * FUNCTION:	attempt to extend a current allocation by a specified
959  *		number of blocks.
960  *
961  *		this routine attempts to satisfy the allocation request
962  *		by first trying to extend the existing allocation in
963  *		place by allocating the additional blocks as the blocks
964  *		immediately following the current allocation.  if these
965  *		blocks are not available, this routine will attempt to
966  *		allocate a new set of contiguous blocks large enough
967  *		to cover the existing allocation plus the additional
968  *		number of blocks required.
969  *
970  * PARAMETERS:
971  *	ip	    -  pointer to in-core inode requiring allocation.
972  *	blkno	    -  starting block of the current allocation.
973  *	nblocks	    -  number of contiguous blocks within the current
974  *		       allocation.
975  *	addnblocks  -  number of blocks to add to the allocation.
976  *	results	-      on successful return, set to the starting block number
977  *		       of the existing allocation if the existing allocation
978  *		       was extended in place or to a newly allocated contiguous
979  *		       range if the existing allocation could not be extended
980  *		       in place.
981  *
982  * RETURN VALUES:
983  *	0	- success
984  *	-ENOSPC	- insufficient disk resources
985  *	-EIO	- i/o error
986  */
987 int
dbReAlloc(struct inode * ip,s64 blkno,s64 nblocks,s64 addnblocks,s64 * results)988 dbReAlloc(struct inode *ip,
989 	  s64 blkno, s64 nblocks, s64 addnblocks, s64 * results)
990 {
991 	int rc;
992 
993 	/* try to extend the allocation in place.
994 	 */
995 	if ((rc = dbExtend(ip, blkno, nblocks, addnblocks)) == 0) {
996 		*results = blkno;
997 		return (0);
998 	} else {
999 		if (rc != -ENOSPC)
1000 			return (rc);
1001 	}
1002 
1003 	/* could not extend the allocation in place, so allocate a
1004 	 * new set of blocks for the entire request (i.e. try to get
1005 	 * a range of contiguous blocks large enough to cover the
1006 	 * existing allocation plus the additional blocks.)
1007 	 */
1008 	return (dbAlloc
1009 		(ip, blkno + nblocks - 1, addnblocks + nblocks, results));
1010 }
1011 
1012 
1013 /*
1014  * NAME:	dbExtend()
1015  *
1016  * FUNCTION:	attempt to extend a current allocation by a specified
1017  *		number of blocks.
1018  *
1019  *		this routine attempts to satisfy the allocation request
1020  *		by first trying to extend the existing allocation in
1021  *		place by allocating the additional blocks as the blocks
1022  *		immediately following the current allocation.
1023  *
1024  * PARAMETERS:
1025  *	ip	    -  pointer to in-core inode requiring allocation.
1026  *	blkno	    -  starting block of the current allocation.
1027  *	nblocks	    -  number of contiguous blocks within the current
1028  *		       allocation.
1029  *	addnblocks  -  number of blocks to add to the allocation.
1030  *
1031  * RETURN VALUES:
1032  *	0	- success
1033  *	-ENOSPC	- insufficient disk resources
1034  *	-EIO	- i/o error
1035  */
dbExtend(struct inode * ip,s64 blkno,s64 nblocks,s64 addnblocks)1036 static int dbExtend(struct inode *ip, s64 blkno, s64 nblocks, s64 addnblocks)
1037 {
1038 	struct jfs_sb_info *sbi = JFS_SBI(ip->i_sb);
1039 	s64 lblkno, lastblkno, extblkno;
1040 	uint rel_block;
1041 	struct metapage *mp;
1042 	struct dmap *dp;
1043 	int rc;
1044 	struct inode *ipbmap = sbi->ipbmap;
1045 	struct bmap *bmp;
1046 
1047 	/*
1048 	 * We don't want a non-aligned extent to cross a page boundary
1049 	 */
1050 	if (((rel_block = blkno & (sbi->nbperpage - 1))) &&
1051 	    (rel_block + nblocks + addnblocks > sbi->nbperpage))
1052 		return -ENOSPC;
1053 
1054 	/* get the last block of the current allocation */
1055 	lastblkno = blkno + nblocks - 1;
1056 
1057 	/* determine the block number of the block following
1058 	 * the existing allocation.
1059 	 */
1060 	extblkno = lastblkno + 1;
1061 
1062 	IREAD_LOCK(ipbmap, RDWRLOCK_DMAP);
1063 
1064 	/* better be within the file system */
1065 	bmp = sbi->bmap;
1066 	if (lastblkno < 0 || lastblkno >= bmp->db_mapsize) {
1067 		IREAD_UNLOCK(ipbmap);
1068 		jfs_error(ip->i_sb, "the block is outside the filesystem\n");
1069 		return -EIO;
1070 	}
1071 
1072 	/* we'll attempt to extend the current allocation in place by
1073 	 * allocating the additional blocks as the blocks immediately
1074 	 * following the current allocation.  we only try to extend the
1075 	 * current allocation in place if the number of additional blocks
1076 	 * can fit into a dmap, the last block of the current allocation
1077 	 * is not the last block of the file system, and the start of the
1078 	 * inplace extension is not on an allocation group boundary.
1079 	 */
1080 	if (addnblocks > BPERDMAP || extblkno >= bmp->db_mapsize ||
1081 	    (extblkno & (bmp->db_agsize - 1)) == 0) {
1082 		IREAD_UNLOCK(ipbmap);
1083 		return -ENOSPC;
1084 	}
1085 
1086 	/* get the buffer for the dmap containing the first block
1087 	 * of the extension.
1088 	 */
1089 	lblkno = BLKTODMAP(extblkno, bmp->db_l2nbperpage);
1090 	mp = read_metapage(ipbmap, lblkno, PSIZE, 0);
1091 	if (mp == NULL) {
1092 		IREAD_UNLOCK(ipbmap);
1093 		return -EIO;
1094 	}
1095 
1096 	dp = (struct dmap *) mp->data;
1097 
1098 	/* try to allocate the blocks immediately following the
1099 	 * current allocation.
1100 	 */
1101 	rc = dbAllocNext(bmp, dp, extblkno, (int) addnblocks);
1102 
1103 	IREAD_UNLOCK(ipbmap);
1104 
1105 	/* were we successful ? */
1106 	if (rc == 0)
1107 		write_metapage(mp);
1108 	else
1109 		/* we were not successful */
1110 		release_metapage(mp);
1111 
1112 	return (rc);
1113 }
1114 
1115 
1116 /*
1117  * NAME:	dbAllocNext()
1118  *
1119  * FUNCTION:	attempt to allocate the blocks of the specified block
1120  *		range within a dmap.
1121  *
1122  * PARAMETERS:
1123  *	bmp	-  pointer to bmap descriptor
1124  *	dp	-  pointer to dmap.
1125  *	blkno	-  starting block number of the range.
1126  *	nblocks	-  number of contiguous free blocks of the range.
1127  *
1128  * RETURN VALUES:
1129  *	0	- success
1130  *	-ENOSPC	- insufficient disk resources
1131  *	-EIO	- i/o error
1132  *
1133  * serialization: IREAD_LOCK(ipbmap) held on entry/exit;
1134  */
dbAllocNext(struct bmap * bmp,struct dmap * dp,s64 blkno,int nblocks)1135 static int dbAllocNext(struct bmap * bmp, struct dmap * dp, s64 blkno,
1136 		       int nblocks)
1137 {
1138 	int dbitno, word, rembits, nb, nwords, wbitno, nw;
1139 	int l2size;
1140 	s8 *leaf;
1141 	u32 mask;
1142 
1143 	if (dp->tree.leafidx != cpu_to_le32(LEAFIND)) {
1144 		jfs_error(bmp->db_ipbmap->i_sb, "Corrupt dmap page\n");
1145 		return -EIO;
1146 	}
1147 
1148 	/* pick up a pointer to the leaves of the dmap tree.
1149 	 */
1150 	leaf = dp->tree.stree + le32_to_cpu(dp->tree.leafidx);
1151 
1152 	/* determine the bit number and word within the dmap of the
1153 	 * starting block.
1154 	 */
1155 	dbitno = blkno & (BPERDMAP - 1);
1156 	word = dbitno >> L2DBWORD;
1157 
1158 	/* check if the specified block range is contained within
1159 	 * this dmap.
1160 	 */
1161 	if (dbitno + nblocks > BPERDMAP)
1162 		return -ENOSPC;
1163 
1164 	/* check if the starting leaf indicates that anything
1165 	 * is free.
1166 	 */
1167 	if (leaf[word] == NOFREE)
1168 		return -ENOSPC;
1169 
1170 	/* check the dmaps words corresponding to block range to see
1171 	 * if the block range is free.  not all bits of the first and
1172 	 * last words may be contained within the block range.  if this
1173 	 * is the case, we'll work against those words (i.e. partial first
1174 	 * and/or last) on an individual basis (a single pass) and examine
1175 	 * the actual bits to determine if they are free.  a single pass
1176 	 * will be used for all dmap words fully contained within the
1177 	 * specified range.  within this pass, the leaves of the dmap
1178 	 * tree will be examined to determine if the blocks are free. a
1179 	 * single leaf may describe the free space of multiple dmap
1180 	 * words, so we may visit only a subset of the actual leaves
1181 	 * corresponding to the dmap words of the block range.
1182 	 */
1183 	for (rembits = nblocks; rembits > 0; rembits -= nb, dbitno += nb) {
1184 		/* determine the bit number within the word and
1185 		 * the number of bits within the word.
1186 		 */
1187 		wbitno = dbitno & (DBWORD - 1);
1188 		nb = min(rembits, DBWORD - wbitno);
1189 
1190 		/* check if only part of the word is to be examined.
1191 		 */
1192 		if (nb < DBWORD) {
1193 			/* check if the bits are free.
1194 			 */
1195 			mask = (ONES << (DBWORD - nb) >> wbitno);
1196 			if ((mask & ~le32_to_cpu(dp->wmap[word])) != mask)
1197 				return -ENOSPC;
1198 
1199 			word += 1;
1200 		} else {
1201 			/* one or more dmap words are fully contained
1202 			 * within the block range.  determine how many
1203 			 * words and how many bits.
1204 			 */
1205 			nwords = rembits >> L2DBWORD;
1206 			nb = nwords << L2DBWORD;
1207 
1208 			/* now examine the appropriate leaves to determine
1209 			 * if the blocks are free.
1210 			 */
1211 			while (nwords > 0) {
1212 				/* does the leaf describe any free space ?
1213 				 */
1214 				if (leaf[word] < BUDMIN)
1215 					return -ENOSPC;
1216 
1217 				/* determine the l2 number of bits provided
1218 				 * by this leaf.
1219 				 */
1220 				l2size =
1221 				    min_t(int, leaf[word], NLSTOL2BSZ(nwords));
1222 
1223 				/* determine how many words were handled.
1224 				 */
1225 				nw = BUDSIZE(l2size, BUDMIN);
1226 
1227 				nwords -= nw;
1228 				word += nw;
1229 			}
1230 		}
1231 	}
1232 
1233 	/* allocate the blocks.
1234 	 */
1235 	return (dbAllocDmap(bmp, dp, blkno, nblocks));
1236 }
1237 
1238 
1239 /*
1240  * NAME:	dbAllocNear()
1241  *
1242  * FUNCTION:	attempt to allocate a number of contiguous free blocks near
1243  *		a specified block (hint) within a dmap.
1244  *
1245  *		starting with the dmap leaf that covers the hint, we'll
1246  *		check the next four contiguous leaves for sufficient free
1247  *		space.  if sufficient free space is found, we'll allocate
1248  *		the desired free space.
1249  *
1250  * PARAMETERS:
1251  *	bmp	-  pointer to bmap descriptor
1252  *	dp	-  pointer to dmap.
1253  *	blkno	-  block number to allocate near.
1254  *	nblocks	-  actual number of contiguous free blocks desired.
1255  *	l2nb	-  log2 number of contiguous free blocks desired.
1256  *	results	-  on successful return, set to the starting block number
1257  *		   of the newly allocated range.
1258  *
1259  * RETURN VALUES:
1260  *	0	- success
1261  *	-ENOSPC	- insufficient disk resources
1262  *	-EIO	- i/o error
1263  *
1264  * serialization: IREAD_LOCK(ipbmap) held on entry/exit;
1265  */
1266 static int
dbAllocNear(struct bmap * bmp,struct dmap * dp,s64 blkno,int nblocks,int l2nb,s64 * results)1267 dbAllocNear(struct bmap * bmp,
1268 	    struct dmap * dp, s64 blkno, int nblocks, int l2nb, s64 * results)
1269 {
1270 	int word, lword, rc;
1271 	s8 *leaf;
1272 
1273 	if (dp->tree.leafidx != cpu_to_le32(LEAFIND)) {
1274 		jfs_error(bmp->db_ipbmap->i_sb, "Corrupt dmap page\n");
1275 		return -EIO;
1276 	}
1277 
1278 	leaf = dp->tree.stree + le32_to_cpu(dp->tree.leafidx);
1279 
1280 	/* determine the word within the dmap that holds the hint
1281 	 * (i.e. blkno).  also, determine the last word in the dmap
1282 	 * that we'll include in our examination.
1283 	 */
1284 	word = (blkno & (BPERDMAP - 1)) >> L2DBWORD;
1285 	lword = min(word + 4, LPERDMAP);
1286 
1287 	/* examine the leaves for sufficient free space.
1288 	 */
1289 	for (; word < lword; word++) {
1290 		/* does the leaf describe sufficient free space ?
1291 		 */
1292 		if (leaf[word] < l2nb)
1293 			continue;
1294 
1295 		/* determine the block number within the file system
1296 		 * of the first block described by this dmap word.
1297 		 */
1298 		blkno = le64_to_cpu(dp->start) + (word << L2DBWORD);
1299 
1300 		/* if not all bits of the dmap word are free, get the
1301 		 * starting bit number within the dmap word of the required
1302 		 * string of free bits and adjust the block number with the
1303 		 * value.
1304 		 */
1305 		if (leaf[word] < BUDMIN)
1306 			blkno +=
1307 			    dbFindBits(le32_to_cpu(dp->wmap[word]), l2nb);
1308 
1309 		/* allocate the blocks.
1310 		 */
1311 		if ((rc = dbAllocDmap(bmp, dp, blkno, nblocks)) == 0)
1312 			*results = blkno;
1313 
1314 		return (rc);
1315 	}
1316 
1317 	return -ENOSPC;
1318 }
1319 
1320 
1321 /*
1322  * NAME:	dbAllocAG()
1323  *
1324  * FUNCTION:	attempt to allocate the specified number of contiguous
1325  *		free blocks within the specified allocation group.
1326  *
1327  *		unless the allocation group size is equal to the number
1328  *		of blocks per dmap, the dmap control pages will be used to
1329  *		find the required free space, if available.  we start the
1330  *		search at the highest dmap control page level which
1331  *		distinctly describes the allocation group's free space
1332  *		(i.e. the highest level at which the allocation group's
1333  *		free space is not mixed in with that of any other group).
1334  *		in addition, we start the search within this level at a
1335  *		height of the dmapctl dmtree at which the nodes distinctly
1336  *		describe the allocation group's free space.  at this height,
1337  *		the allocation group's free space may be represented by 1
1338  *		or two sub-trees, depending on the allocation group size.
1339  *		we search the top nodes of these subtrees left to right for
1340  *		sufficient free space.  if sufficient free space is found,
1341  *		the subtree is searched to find the leftmost leaf that
1342  *		has free space.  once we have made it to the leaf, we
1343  *		move the search to the next lower level dmap control page
1344  *		corresponding to this leaf.  we continue down the dmap control
1345  *		pages until we find the dmap that contains or starts the
1346  *		sufficient free space and we allocate at this dmap.
1347  *
1348  *		if the allocation group size is equal to the dmap size,
1349  *		we'll start at the dmap corresponding to the allocation
1350  *		group and attempt the allocation at this level.
1351  *
1352  *		the dmap control page search is also not performed if the
1353  *		allocation group is completely free and we go to the first
1354  *		dmap of the allocation group to do the allocation.  this is
1355  *		done because the allocation group may be part (not the first
1356  *		part) of a larger binary buddy system, causing the dmap
1357  *		control pages to indicate no free space (NOFREE) within
1358  *		the allocation group.
1359  *
1360  * PARAMETERS:
1361  *	bmp	-  pointer to bmap descriptor
1362  *	agno	- allocation group number.
1363  *	nblocks	-  actual number of contiguous free blocks desired.
1364  *	l2nb	-  log2 number of contiguous free blocks desired.
1365  *	results	-  on successful return, set to the starting block number
1366  *		   of the newly allocated range.
1367  *
1368  * RETURN VALUES:
1369  *	0	- success
1370  *	-ENOSPC	- insufficient disk resources
1371  *	-EIO	- i/o error
1372  *
1373  * note: IWRITE_LOCK(ipmap) held on entry/exit;
1374  */
1375 static int
dbAllocAG(struct bmap * bmp,int agno,s64 nblocks,int l2nb,s64 * results)1376 dbAllocAG(struct bmap * bmp, int agno, s64 nblocks, int l2nb, s64 * results)
1377 {
1378 	struct metapage *mp;
1379 	struct dmapctl *dcp;
1380 	int rc, ti, i, k, m, n, agperlev;
1381 	s64 blkno, lblkno;
1382 	int budmin;
1383 
1384 	/* allocation request should not be for more than the
1385 	 * allocation group size.
1386 	 */
1387 	if (l2nb > bmp->db_agl2size) {
1388 		jfs_error(bmp->db_ipbmap->i_sb,
1389 			  "allocation request is larger than the allocation group size\n");
1390 		return -EIO;
1391 	}
1392 
1393 	/* determine the starting block number of the allocation
1394 	 * group.
1395 	 */
1396 	blkno = (s64) agno << bmp->db_agl2size;
1397 
1398 	/* check if the allocation group size is the minimum allocation
1399 	 * group size or if the allocation group is completely free. if
1400 	 * the allocation group size is the minimum size of BPERDMAP (i.e.
1401 	 * 1 dmap), there is no need to search the dmap control page (below)
1402 	 * that fully describes the allocation group since the allocation
1403 	 * group is already fully described by a dmap.  in this case, we
1404 	 * just call dbAllocCtl() to search the dmap tree and allocate the
1405 	 * required space if available.
1406 	 *
1407 	 * if the allocation group is completely free, dbAllocCtl() is
1408 	 * also called to allocate the required space.  this is done for
1409 	 * two reasons.  first, it makes no sense searching the dmap control
1410 	 * pages for free space when we know that free space exists.  second,
1411 	 * the dmap control pages may indicate that the allocation group
1412 	 * has no free space if the allocation group is part (not the first
1413 	 * part) of a larger binary buddy system.
1414 	 */
1415 	if (bmp->db_agsize == BPERDMAP
1416 	    || bmp->db_agfree[agno] == bmp->db_agsize) {
1417 		rc = dbAllocCtl(bmp, nblocks, l2nb, blkno, results);
1418 		if ((rc == -ENOSPC) &&
1419 		    (bmp->db_agfree[agno] == bmp->db_agsize)) {
1420 			printk(KERN_ERR "blkno = %Lx, blocks = %Lx\n",
1421 			       (unsigned long long) blkno,
1422 			       (unsigned long long) nblocks);
1423 			jfs_error(bmp->db_ipbmap->i_sb,
1424 				  "dbAllocCtl failed in free AG\n");
1425 		}
1426 		return (rc);
1427 	}
1428 
1429 	/* the buffer for the dmap control page that fully describes the
1430 	 * allocation group.
1431 	 */
1432 	lblkno = BLKTOCTL(blkno, bmp->db_l2nbperpage, bmp->db_aglevel);
1433 	mp = read_metapage(bmp->db_ipbmap, lblkno, PSIZE, 0);
1434 	if (mp == NULL)
1435 		return -EIO;
1436 	dcp = (struct dmapctl *) mp->data;
1437 	budmin = dcp->budmin;
1438 
1439 	if (dcp->leafidx != cpu_to_le32(CTLLEAFIND)) {
1440 		jfs_error(bmp->db_ipbmap->i_sb, "Corrupt dmapctl page\n");
1441 		release_metapage(mp);
1442 		return -EIO;
1443 	}
1444 
1445 	/* search the subtree(s) of the dmap control page that describes
1446 	 * the allocation group, looking for sufficient free space.  to begin,
1447 	 * determine how many allocation groups are represented in a dmap
1448 	 * control page at the control page level (i.e. L0, L1, L2) that
1449 	 * fully describes an allocation group. next, determine the starting
1450 	 * tree index of this allocation group within the control page.
1451 	 */
1452 	agperlev =
1453 	    (1 << (L2LPERCTL - (bmp->db_agheight << 1))) / bmp->db_agwidth;
1454 	ti = bmp->db_agstart + bmp->db_agwidth * (agno & (agperlev - 1));
1455 
1456 	/* dmap control page trees fan-out by 4 and a single allocation
1457 	 * group may be described by 1 or 2 subtrees within the ag level
1458 	 * dmap control page, depending upon the ag size. examine the ag's
1459 	 * subtrees for sufficient free space, starting with the leftmost
1460 	 * subtree.
1461 	 */
1462 	for (i = 0; i < bmp->db_agwidth; i++, ti++) {
1463 		/* is there sufficient free space ?
1464 		 */
1465 		if (l2nb > dcp->stree[ti])
1466 			continue;
1467 
1468 		/* sufficient free space found in a subtree. now search down
1469 		 * the subtree to find the leftmost leaf that describes this
1470 		 * free space.
1471 		 */
1472 		for (k = bmp->db_agheight; k > 0; k--) {
1473 			for (n = 0, m = (ti << 2) + 1; n < 4; n++) {
1474 				if (l2nb <= dcp->stree[m + n]) {
1475 					ti = m + n;
1476 					break;
1477 				}
1478 			}
1479 			if (n == 4) {
1480 				jfs_error(bmp->db_ipbmap->i_sb,
1481 					  "failed descending stree\n");
1482 				release_metapage(mp);
1483 				return -EIO;
1484 			}
1485 		}
1486 
1487 		/* determine the block number within the file system
1488 		 * that corresponds to this leaf.
1489 		 */
1490 		if (bmp->db_aglevel == 2)
1491 			blkno = 0;
1492 		else if (bmp->db_aglevel == 1)
1493 			blkno &= ~(MAXL1SIZE - 1);
1494 		else		/* bmp->db_aglevel == 0 */
1495 			blkno &= ~(MAXL0SIZE - 1);
1496 
1497 		blkno +=
1498 		    ((s64) (ti - le32_to_cpu(dcp->leafidx))) << budmin;
1499 
1500 		/* release the buffer in preparation for going down
1501 		 * the next level of dmap control pages.
1502 		 */
1503 		release_metapage(mp);
1504 
1505 		/* check if we need to continue to search down the lower
1506 		 * level dmap control pages.  we need to if the number of
1507 		 * blocks required is less than maximum number of blocks
1508 		 * described at the next lower level.
1509 		 */
1510 		if (l2nb < budmin) {
1511 
1512 			/* search the lower level dmap control pages to get
1513 			 * the starting block number of the dmap that
1514 			 * contains or starts off the free space.
1515 			 */
1516 			if ((rc =
1517 			     dbFindCtl(bmp, l2nb, bmp->db_aglevel - 1,
1518 				       &blkno))) {
1519 				if (rc == -ENOSPC) {
1520 					jfs_error(bmp->db_ipbmap->i_sb,
1521 						  "control page inconsistent\n");
1522 					return -EIO;
1523 				}
1524 				return (rc);
1525 			}
1526 		}
1527 
1528 		/* allocate the blocks.
1529 		 */
1530 		rc = dbAllocCtl(bmp, nblocks, l2nb, blkno, results);
1531 		if (rc == -ENOSPC) {
1532 			jfs_error(bmp->db_ipbmap->i_sb,
1533 				  "unable to allocate blocks\n");
1534 			rc = -EIO;
1535 		}
1536 		return (rc);
1537 	}
1538 
1539 	/* no space in the allocation group.  release the buffer and
1540 	 * return -ENOSPC.
1541 	 */
1542 	release_metapage(mp);
1543 
1544 	return -ENOSPC;
1545 }
1546 
1547 
1548 /*
1549  * NAME:	dbAllocAny()
1550  *
1551  * FUNCTION:	attempt to allocate the specified number of contiguous
1552  *		free blocks anywhere in the file system.
1553  *
1554  *		dbAllocAny() attempts to find the sufficient free space by
1555  *		searching down the dmap control pages, starting with the
1556  *		highest level (i.e. L0, L1, L2) control page.  if free space
1557  *		large enough to satisfy the desired free space is found, the
1558  *		desired free space is allocated.
1559  *
1560  * PARAMETERS:
1561  *	bmp	-  pointer to bmap descriptor
1562  *	nblocks	 -  actual number of contiguous free blocks desired.
1563  *	l2nb	 -  log2 number of contiguous free blocks desired.
1564  *	results	-  on successful return, set to the starting block number
1565  *		   of the newly allocated range.
1566  *
1567  * RETURN VALUES:
1568  *	0	- success
1569  *	-ENOSPC	- insufficient disk resources
1570  *	-EIO	- i/o error
1571  *
1572  * serialization: IWRITE_LOCK(ipbmap) held on entry/exit;
1573  */
dbAllocAny(struct bmap * bmp,s64 nblocks,int l2nb,s64 * results)1574 static int dbAllocAny(struct bmap * bmp, s64 nblocks, int l2nb, s64 * results)
1575 {
1576 	int rc;
1577 	s64 blkno = 0;
1578 
1579 	/* starting with the top level dmap control page, search
1580 	 * down the dmap control levels for sufficient free space.
1581 	 * if free space is found, dbFindCtl() returns the starting
1582 	 * block number of the dmap that contains or starts off the
1583 	 * range of free space.
1584 	 */
1585 	if ((rc = dbFindCtl(bmp, l2nb, bmp->db_maxlevel, &blkno)))
1586 		return (rc);
1587 
1588 	/* allocate the blocks.
1589 	 */
1590 	rc = dbAllocCtl(bmp, nblocks, l2nb, blkno, results);
1591 	if (rc == -ENOSPC) {
1592 		jfs_error(bmp->db_ipbmap->i_sb, "unable to allocate blocks\n");
1593 		return -EIO;
1594 	}
1595 	return (rc);
1596 }
1597 
1598 
1599 /*
1600  * NAME:	dbDiscardAG()
1601  *
1602  * FUNCTION:	attempt to discard (TRIM) all free blocks of specific AG
1603  *
1604  *		algorithm:
1605  *		1) allocate blocks, as large as possible and save them
1606  *		   while holding IWRITE_LOCK on ipbmap
1607  *		2) trim all these saved block/length values
1608  *		3) mark the blocks free again
1609  *
1610  *		benefit:
1611  *		- we work only on one ag at some time, minimizing how long we
1612  *		  need to lock ipbmap
1613  *		- reading / writing the fs is possible most time, even on
1614  *		  trimming
1615  *
1616  *		downside:
1617  *		- we write two times to the dmapctl and dmap pages
1618  *		- but for me, this seems the best way, better ideas?
1619  *		/TR 2012
1620  *
1621  * PARAMETERS:
1622  *	ip	- pointer to in-core inode
1623  *	agno	- ag to trim
1624  *	minlen	- minimum value of contiguous blocks
1625  *
1626  * RETURN VALUES:
1627  *	s64	- actual number of blocks trimmed
1628  */
dbDiscardAG(struct inode * ip,int agno,s64 minlen)1629 s64 dbDiscardAG(struct inode *ip, int agno, s64 minlen)
1630 {
1631 	struct inode *ipbmap = JFS_SBI(ip->i_sb)->ipbmap;
1632 	struct bmap *bmp = JFS_SBI(ip->i_sb)->bmap;
1633 	s64 nblocks, blkno;
1634 	u64 trimmed = 0;
1635 	int rc, l2nb;
1636 	struct super_block *sb = ipbmap->i_sb;
1637 
1638 	struct range2trim {
1639 		u64 blkno;
1640 		u64 nblocks;
1641 	} *totrim, *tt;
1642 
1643 	/* max blkno / nblocks pairs to trim */
1644 	int count = 0, range_cnt;
1645 	u64 max_ranges;
1646 
1647 	/* prevent others from writing new stuff here, while trimming */
1648 	IWRITE_LOCK(ipbmap, RDWRLOCK_DMAP);
1649 
1650 	nblocks = bmp->db_agfree[agno];
1651 	max_ranges = nblocks;
1652 	do_div(max_ranges, minlen);
1653 	range_cnt = min_t(u64, max_ranges + 1, 32 * 1024);
1654 	totrim = kmalloc_array(range_cnt, sizeof(struct range2trim), GFP_NOFS);
1655 	if (totrim == NULL) {
1656 		jfs_error(bmp->db_ipbmap->i_sb, "no memory for trim array\n");
1657 		IWRITE_UNLOCK(ipbmap);
1658 		return 0;
1659 	}
1660 
1661 	tt = totrim;
1662 	while (nblocks >= minlen) {
1663 		l2nb = BLKSTOL2(nblocks);
1664 
1665 		/* 0 = okay, -EIO = fatal, -ENOSPC -> try smaller block */
1666 		rc = dbAllocAG(bmp, agno, nblocks, l2nb, &blkno);
1667 		if (rc == 0) {
1668 			tt->blkno = blkno;
1669 			tt->nblocks = nblocks;
1670 			tt++; count++;
1671 
1672 			/* the whole ag is free, trim now */
1673 			if (bmp->db_agfree[agno] == 0)
1674 				break;
1675 
1676 			/* give a hint for the next while */
1677 			nblocks = bmp->db_agfree[agno];
1678 			continue;
1679 		} else if (rc == -ENOSPC) {
1680 			/* search for next smaller log2 block */
1681 			l2nb = BLKSTOL2(nblocks) - 1;
1682 			nblocks = 1LL << l2nb;
1683 		} else {
1684 			/* Trim any already allocated blocks */
1685 			jfs_error(bmp->db_ipbmap->i_sb, "-EIO\n");
1686 			break;
1687 		}
1688 
1689 		/* check, if our trim array is full */
1690 		if (unlikely(count >= range_cnt - 1))
1691 			break;
1692 	}
1693 	IWRITE_UNLOCK(ipbmap);
1694 
1695 	tt->nblocks = 0; /* mark the current end */
1696 	for (tt = totrim; tt->nblocks != 0; tt++) {
1697 		/* when mounted with online discard, dbFree() will
1698 		 * call jfs_issue_discard() itself */
1699 		if (!(JFS_SBI(sb)->flag & JFS_DISCARD))
1700 			jfs_issue_discard(ip, tt->blkno, tt->nblocks);
1701 		dbFree(ip, tt->blkno, tt->nblocks);
1702 		trimmed += tt->nblocks;
1703 	}
1704 	kfree(totrim);
1705 
1706 	return trimmed;
1707 }
1708 
1709 /*
1710  * NAME:	dbFindCtl()
1711  *
1712  * FUNCTION:	starting at a specified dmap control page level and block
1713  *		number, search down the dmap control levels for a range of
1714  *		contiguous free blocks large enough to satisfy an allocation
1715  *		request for the specified number of free blocks.
1716  *
1717  *		if sufficient contiguous free blocks are found, this routine
1718  *		returns the starting block number within a dmap page that
1719  *		contains or starts a range of contiqious free blocks that
1720  *		is sufficient in size.
1721  *
1722  * PARAMETERS:
1723  *	bmp	-  pointer to bmap descriptor
1724  *	level	-  starting dmap control page level.
1725  *	l2nb	-  log2 number of contiguous free blocks desired.
1726  *	*blkno	-  on entry, starting block number for conducting the search.
1727  *		   on successful return, the first block within a dmap page
1728  *		   that contains or starts a range of contiguous free blocks.
1729  *
1730  * RETURN VALUES:
1731  *	0	- success
1732  *	-ENOSPC	- insufficient disk resources
1733  *	-EIO	- i/o error
1734  *
1735  * serialization: IWRITE_LOCK(ipbmap) held on entry/exit;
1736  */
dbFindCtl(struct bmap * bmp,int l2nb,int level,s64 * blkno)1737 static int dbFindCtl(struct bmap * bmp, int l2nb, int level, s64 * blkno)
1738 {
1739 	int rc, leafidx, lev;
1740 	s64 b, lblkno;
1741 	struct dmapctl *dcp;
1742 	int budmin;
1743 	struct metapage *mp;
1744 
1745 	/* starting at the specified dmap control page level and block
1746 	 * number, search down the dmap control levels for the starting
1747 	 * block number of a dmap page that contains or starts off
1748 	 * sufficient free blocks.
1749 	 */
1750 	for (lev = level, b = *blkno; lev >= 0; lev--) {
1751 		/* get the buffer of the dmap control page for the block
1752 		 * number and level (i.e. L0, L1, L2).
1753 		 */
1754 		lblkno = BLKTOCTL(b, bmp->db_l2nbperpage, lev);
1755 		mp = read_metapage(bmp->db_ipbmap, lblkno, PSIZE, 0);
1756 		if (mp == NULL)
1757 			return -EIO;
1758 		dcp = (struct dmapctl *) mp->data;
1759 		budmin = dcp->budmin;
1760 
1761 		if (dcp->leafidx != cpu_to_le32(CTLLEAFIND)) {
1762 			jfs_error(bmp->db_ipbmap->i_sb,
1763 				  "Corrupt dmapctl page\n");
1764 			release_metapage(mp);
1765 			return -EIO;
1766 		}
1767 
1768 		/* search the tree within the dmap control page for
1769 		 * sufficient free space.  if sufficient free space is found,
1770 		 * dbFindLeaf() returns the index of the leaf at which
1771 		 * free space was found.
1772 		 */
1773 		rc = dbFindLeaf((dmtree_t *) dcp, l2nb, &leafidx);
1774 
1775 		/* release the buffer.
1776 		 */
1777 		release_metapage(mp);
1778 
1779 		/* space found ?
1780 		 */
1781 		if (rc) {
1782 			if (lev != level) {
1783 				jfs_error(bmp->db_ipbmap->i_sb,
1784 					  "dmap inconsistent\n");
1785 				return -EIO;
1786 			}
1787 			return -ENOSPC;
1788 		}
1789 
1790 		/* adjust the block number to reflect the location within
1791 		 * the dmap control page (i.e. the leaf) at which free
1792 		 * space was found.
1793 		 */
1794 		b += (((s64) leafidx) << budmin);
1795 
1796 		/* we stop the search at this dmap control page level if
1797 		 * the number of blocks required is greater than or equal
1798 		 * to the maximum number of blocks described at the next
1799 		 * (lower) level.
1800 		 */
1801 		if (l2nb >= budmin)
1802 			break;
1803 	}
1804 
1805 	*blkno = b;
1806 	return (0);
1807 }
1808 
1809 
1810 /*
1811  * NAME:	dbAllocCtl()
1812  *
1813  * FUNCTION:	attempt to allocate a specified number of contiguous
1814  *		blocks starting within a specific dmap.
1815  *
1816  *		this routine is called by higher level routines that search
1817  *		the dmap control pages above the actual dmaps for contiguous
1818  *		free space.  the result of successful searches by these
1819  *		routines are the starting block numbers within dmaps, with
1820  *		the dmaps themselves containing the desired contiguous free
1821  *		space or starting a contiguous free space of desired size
1822  *		that is made up of the blocks of one or more dmaps. these
1823  *		calls should not fail due to insufficent resources.
1824  *
1825  *		this routine is called in some cases where it is not known
1826  *		whether it will fail due to insufficient resources.  more
1827  *		specifically, this occurs when allocating from an allocation
1828  *		group whose size is equal to the number of blocks per dmap.
1829  *		in this case, the dmap control pages are not examined prior
1830  *		to calling this routine (to save pathlength) and the call
1831  *		might fail.
1832  *
1833  *		for a request size that fits within a dmap, this routine relies
1834  *		upon the dmap's dmtree to find the requested contiguous free
1835  *		space.  for request sizes that are larger than a dmap, the
1836  *		requested free space will start at the first block of the
1837  *		first dmap (i.e. blkno).
1838  *
1839  * PARAMETERS:
1840  *	bmp	-  pointer to bmap descriptor
1841  *	nblocks	 -  actual number of contiguous free blocks to allocate.
1842  *	l2nb	 -  log2 number of contiguous free blocks to allocate.
1843  *	blkno	 -  starting block number of the dmap to start the allocation
1844  *		    from.
1845  *	results	-  on successful return, set to the starting block number
1846  *		   of the newly allocated range.
1847  *
1848  * RETURN VALUES:
1849  *	0	- success
1850  *	-ENOSPC	- insufficient disk resources
1851  *	-EIO	- i/o error
1852  *
1853  * serialization: IWRITE_LOCK(ipbmap) held on entry/exit;
1854  */
1855 static int
dbAllocCtl(struct bmap * bmp,s64 nblocks,int l2nb,s64 blkno,s64 * results)1856 dbAllocCtl(struct bmap * bmp, s64 nblocks, int l2nb, s64 blkno, s64 * results)
1857 {
1858 	int rc, nb;
1859 	s64 b, lblkno, n;
1860 	struct metapage *mp;
1861 	struct dmap *dp;
1862 
1863 	/* check if the allocation request is confined to a single dmap.
1864 	 */
1865 	if (l2nb <= L2BPERDMAP) {
1866 		/* get the buffer for the dmap.
1867 		 */
1868 		lblkno = BLKTODMAP(blkno, bmp->db_l2nbperpage);
1869 		mp = read_metapage(bmp->db_ipbmap, lblkno, PSIZE, 0);
1870 		if (mp == NULL)
1871 			return -EIO;
1872 		dp = (struct dmap *) mp->data;
1873 
1874 		/* try to allocate the blocks.
1875 		 */
1876 		rc = dbAllocDmapLev(bmp, dp, (int) nblocks, l2nb, results);
1877 		if (rc == 0)
1878 			mark_metapage_dirty(mp);
1879 
1880 		release_metapage(mp);
1881 
1882 		return (rc);
1883 	}
1884 
1885 	/* allocation request involving multiple dmaps. it must start on
1886 	 * a dmap boundary.
1887 	 */
1888 	assert((blkno & (BPERDMAP - 1)) == 0);
1889 
1890 	/* allocate the blocks dmap by dmap.
1891 	 */
1892 	for (n = nblocks, b = blkno; n > 0; n -= nb, b += nb) {
1893 		/* get the buffer for the dmap.
1894 		 */
1895 		lblkno = BLKTODMAP(b, bmp->db_l2nbperpage);
1896 		mp = read_metapage(bmp->db_ipbmap, lblkno, PSIZE, 0);
1897 		if (mp == NULL) {
1898 			rc = -EIO;
1899 			goto backout;
1900 		}
1901 		dp = (struct dmap *) mp->data;
1902 
1903 		/* the dmap better be all free.
1904 		 */
1905 		if (dp->tree.stree[ROOT] != L2BPERDMAP) {
1906 			release_metapage(mp);
1907 			jfs_error(bmp->db_ipbmap->i_sb,
1908 				  "the dmap is not all free\n");
1909 			rc = -EIO;
1910 			goto backout;
1911 		}
1912 
1913 		/* determine how many blocks to allocate from this dmap.
1914 		 */
1915 		nb = min_t(s64, n, BPERDMAP);
1916 
1917 		/* allocate the blocks from the dmap.
1918 		 */
1919 		if ((rc = dbAllocDmap(bmp, dp, b, nb))) {
1920 			release_metapage(mp);
1921 			goto backout;
1922 		}
1923 
1924 		/* write the buffer.
1925 		 */
1926 		write_metapage(mp);
1927 	}
1928 
1929 	/* set the results (starting block number) and return.
1930 	 */
1931 	*results = blkno;
1932 	return (0);
1933 
1934 	/* something failed in handling an allocation request involving
1935 	 * multiple dmaps.  we'll try to clean up by backing out any
1936 	 * allocation that has already happened for this request.  if
1937 	 * we fail in backing out the allocation, we'll mark the file
1938 	 * system to indicate that blocks have been leaked.
1939 	 */
1940       backout:
1941 
1942 	/* try to backout the allocations dmap by dmap.
1943 	 */
1944 	for (n = nblocks - n, b = blkno; n > 0;
1945 	     n -= BPERDMAP, b += BPERDMAP) {
1946 		/* get the buffer for this dmap.
1947 		 */
1948 		lblkno = BLKTODMAP(b, bmp->db_l2nbperpage);
1949 		mp = read_metapage(bmp->db_ipbmap, lblkno, PSIZE, 0);
1950 		if (mp == NULL) {
1951 			/* could not back out.  mark the file system
1952 			 * to indicate that we have leaked blocks.
1953 			 */
1954 			jfs_error(bmp->db_ipbmap->i_sb,
1955 				  "I/O Error: Block Leakage\n");
1956 			continue;
1957 		}
1958 		dp = (struct dmap *) mp->data;
1959 
1960 		/* free the blocks is this dmap.
1961 		 */
1962 		if (dbFreeDmap(bmp, dp, b, BPERDMAP)) {
1963 			/* could not back out.  mark the file system
1964 			 * to indicate that we have leaked blocks.
1965 			 */
1966 			release_metapage(mp);
1967 			jfs_error(bmp->db_ipbmap->i_sb, "Block Leakage\n");
1968 			continue;
1969 		}
1970 
1971 		/* write the buffer.
1972 		 */
1973 		write_metapage(mp);
1974 	}
1975 
1976 	return (rc);
1977 }
1978 
1979 
1980 /*
1981  * NAME:	dbAllocDmapLev()
1982  *
1983  * FUNCTION:	attempt to allocate a specified number of contiguous blocks
1984  *		from a specified dmap.
1985  *
1986  *		this routine checks if the contiguous blocks are available.
1987  *		if so, nblocks of blocks are allocated; otherwise, ENOSPC is
1988  *		returned.
1989  *
1990  * PARAMETERS:
1991  *	mp	-  pointer to bmap descriptor
1992  *	dp	-  pointer to dmap to attempt to allocate blocks from.
1993  *	l2nb	-  log2 number of contiguous block desired.
1994  *	nblocks	-  actual number of contiguous block desired.
1995  *	results	-  on successful return, set to the starting block number
1996  *		   of the newly allocated range.
1997  *
1998  * RETURN VALUES:
1999  *	0	- success
2000  *	-ENOSPC	- insufficient disk resources
2001  *	-EIO	- i/o error
2002  *
2003  * serialization: IREAD_LOCK(ipbmap), e.g., from dbAlloc(), or
2004  *	IWRITE_LOCK(ipbmap), e.g., dbAllocCtl(), held on entry/exit;
2005  */
2006 static int
dbAllocDmapLev(struct bmap * bmp,struct dmap * dp,int nblocks,int l2nb,s64 * results)2007 dbAllocDmapLev(struct bmap * bmp,
2008 	       struct dmap * dp, int nblocks, int l2nb, s64 * results)
2009 {
2010 	s64 blkno;
2011 	int leafidx, rc;
2012 
2013 	/* can't be more than a dmaps worth of blocks */
2014 	assert(l2nb <= L2BPERDMAP);
2015 
2016 	/* search the tree within the dmap page for sufficient
2017 	 * free space.  if sufficient free space is found, dbFindLeaf()
2018 	 * returns the index of the leaf at which free space was found.
2019 	 */
2020 	if (dbFindLeaf((dmtree_t *) & dp->tree, l2nb, &leafidx))
2021 		return -ENOSPC;
2022 
2023 	/* determine the block number within the file system corresponding
2024 	 * to the leaf at which free space was found.
2025 	 */
2026 	blkno = le64_to_cpu(dp->start) + (leafidx << L2DBWORD);
2027 
2028 	/* if not all bits of the dmap word are free, get the starting
2029 	 * bit number within the dmap word of the required string of free
2030 	 * bits and adjust the block number with this value.
2031 	 */
2032 	if (dp->tree.stree[leafidx + LEAFIND] < BUDMIN)
2033 		blkno += dbFindBits(le32_to_cpu(dp->wmap[leafidx]), l2nb);
2034 
2035 	/* allocate the blocks */
2036 	if ((rc = dbAllocDmap(bmp, dp, blkno, nblocks)) == 0)
2037 		*results = blkno;
2038 
2039 	return (rc);
2040 }
2041 
2042 
2043 /*
2044  * NAME:	dbAllocDmap()
2045  *
2046  * FUNCTION:	adjust the disk allocation map to reflect the allocation
2047  *		of a specified block range within a dmap.
2048  *
2049  *		this routine allocates the specified blocks from the dmap
2050  *		through a call to dbAllocBits(). if the allocation of the
2051  *		block range causes the maximum string of free blocks within
2052  *		the dmap to change (i.e. the value of the root of the dmap's
2053  *		dmtree), this routine will cause this change to be reflected
2054  *		up through the appropriate levels of the dmap control pages
2055  *		by a call to dbAdjCtl() for the L0 dmap control page that
2056  *		covers this dmap.
2057  *
2058  * PARAMETERS:
2059  *	bmp	-  pointer to bmap descriptor
2060  *	dp	-  pointer to dmap to allocate the block range from.
2061  *	blkno	-  starting block number of the block to be allocated.
2062  *	nblocks	-  number of blocks to be allocated.
2063  *
2064  * RETURN VALUES:
2065  *	0	- success
2066  *	-EIO	- i/o error
2067  *
2068  * serialization: IREAD_LOCK(ipbmap) or IWRITE_LOCK(ipbmap) held on entry/exit;
2069  */
dbAllocDmap(struct bmap * bmp,struct dmap * dp,s64 blkno,int nblocks)2070 static int dbAllocDmap(struct bmap * bmp, struct dmap * dp, s64 blkno,
2071 		       int nblocks)
2072 {
2073 	s8 oldroot;
2074 	int rc;
2075 
2076 	/* save the current value of the root (i.e. maximum free string)
2077 	 * of the dmap tree.
2078 	 */
2079 	oldroot = dp->tree.stree[ROOT];
2080 
2081 	/* allocate the specified (blocks) bits */
2082 	dbAllocBits(bmp, dp, blkno, nblocks);
2083 
2084 	/* if the root has not changed, done. */
2085 	if (dp->tree.stree[ROOT] == oldroot)
2086 		return (0);
2087 
2088 	/* root changed. bubble the change up to the dmap control pages.
2089 	 * if the adjustment of the upper level control pages fails,
2090 	 * backout the bit allocation (thus making everything consistent).
2091 	 */
2092 	if ((rc = dbAdjCtl(bmp, blkno, dp->tree.stree[ROOT], 1, 0)))
2093 		dbFreeBits(bmp, dp, blkno, nblocks);
2094 
2095 	return (rc);
2096 }
2097 
2098 
2099 /*
2100  * NAME:	dbFreeDmap()
2101  *
2102  * FUNCTION:	adjust the disk allocation map to reflect the allocation
2103  *		of a specified block range within a dmap.
2104  *
2105  *		this routine frees the specified blocks from the dmap through
2106  *		a call to dbFreeBits(). if the deallocation of the block range
2107  *		causes the maximum string of free blocks within the dmap to
2108  *		change (i.e. the value of the root of the dmap's dmtree), this
2109  *		routine will cause this change to be reflected up through the
2110  *		appropriate levels of the dmap control pages by a call to
2111  *		dbAdjCtl() for the L0 dmap control page that covers this dmap.
2112  *
2113  * PARAMETERS:
2114  *	bmp	-  pointer to bmap descriptor
2115  *	dp	-  pointer to dmap to free the block range from.
2116  *	blkno	-  starting block number of the block to be freed.
2117  *	nblocks	-  number of blocks to be freed.
2118  *
2119  * RETURN VALUES:
2120  *	0	- success
2121  *	-EIO	- i/o error
2122  *
2123  * serialization: IREAD_LOCK(ipbmap) or IWRITE_LOCK(ipbmap) held on entry/exit;
2124  */
dbFreeDmap(struct bmap * bmp,struct dmap * dp,s64 blkno,int nblocks)2125 static int dbFreeDmap(struct bmap * bmp, struct dmap * dp, s64 blkno,
2126 		      int nblocks)
2127 {
2128 	s8 oldroot;
2129 	int rc = 0, word;
2130 
2131 	/* save the current value of the root (i.e. maximum free string)
2132 	 * of the dmap tree.
2133 	 */
2134 	oldroot = dp->tree.stree[ROOT];
2135 
2136 	/* free the specified (blocks) bits */
2137 	rc = dbFreeBits(bmp, dp, blkno, nblocks);
2138 
2139 	/* if error or the root has not changed, done. */
2140 	if (rc || (dp->tree.stree[ROOT] == oldroot))
2141 		return (rc);
2142 
2143 	/* root changed. bubble the change up to the dmap control pages.
2144 	 * if the adjustment of the upper level control pages fails,
2145 	 * backout the deallocation.
2146 	 */
2147 	if ((rc = dbAdjCtl(bmp, blkno, dp->tree.stree[ROOT], 0, 0))) {
2148 		word = (blkno & (BPERDMAP - 1)) >> L2DBWORD;
2149 
2150 		/* as part of backing out the deallocation, we will have
2151 		 * to back split the dmap tree if the deallocation caused
2152 		 * the freed blocks to become part of a larger binary buddy
2153 		 * system.
2154 		 */
2155 		if (dp->tree.stree[word] == NOFREE)
2156 			dbBackSplit((dmtree_t *) & dp->tree, word);
2157 
2158 		dbAllocBits(bmp, dp, blkno, nblocks);
2159 	}
2160 
2161 	return (rc);
2162 }
2163 
2164 
2165 /*
2166  * NAME:	dbAllocBits()
2167  *
2168  * FUNCTION:	allocate a specified block range from a dmap.
2169  *
2170  *		this routine updates the dmap to reflect the working
2171  *		state allocation of the specified block range. it directly
2172  *		updates the bits of the working map and causes the adjustment
2173  *		of the binary buddy system described by the dmap's dmtree
2174  *		leaves to reflect the bits allocated.  it also causes the
2175  *		dmap's dmtree, as a whole, to reflect the allocated range.
2176  *
2177  * PARAMETERS:
2178  *	bmp	-  pointer to bmap descriptor
2179  *	dp	-  pointer to dmap to allocate bits from.
2180  *	blkno	-  starting block number of the bits to be allocated.
2181  *	nblocks	-  number of bits to be allocated.
2182  *
2183  * RETURN VALUES: none
2184  *
2185  * serialization: IREAD_LOCK(ipbmap) or IWRITE_LOCK(ipbmap) held on entry/exit;
2186  */
dbAllocBits(struct bmap * bmp,struct dmap * dp,s64 blkno,int nblocks)2187 static void dbAllocBits(struct bmap * bmp, struct dmap * dp, s64 blkno,
2188 			int nblocks)
2189 {
2190 	int dbitno, word, rembits, nb, nwords, wbitno, nw, agno;
2191 	dmtree_t *tp = (dmtree_t *) & dp->tree;
2192 	int size;
2193 	s8 *leaf;
2194 
2195 	/* pick up a pointer to the leaves of the dmap tree */
2196 	leaf = dp->tree.stree + LEAFIND;
2197 
2198 	/* determine the bit number and word within the dmap of the
2199 	 * starting block.
2200 	 */
2201 	dbitno = blkno & (BPERDMAP - 1);
2202 	word = dbitno >> L2DBWORD;
2203 
2204 	/* block range better be within the dmap */
2205 	assert(dbitno + nblocks <= BPERDMAP);
2206 
2207 	/* allocate the bits of the dmap's words corresponding to the block
2208 	 * range. not all bits of the first and last words may be contained
2209 	 * within the block range.  if this is the case, we'll work against
2210 	 * those words (i.e. partial first and/or last) on an individual basis
2211 	 * (a single pass), allocating the bits of interest by hand and
2212 	 * updating the leaf corresponding to the dmap word. a single pass
2213 	 * will be used for all dmap words fully contained within the
2214 	 * specified range.  within this pass, the bits of all fully contained
2215 	 * dmap words will be marked as free in a single shot and the leaves
2216 	 * will be updated. a single leaf may describe the free space of
2217 	 * multiple dmap words, so we may update only a subset of the actual
2218 	 * leaves corresponding to the dmap words of the block range.
2219 	 */
2220 	for (rembits = nblocks; rembits > 0; rembits -= nb, dbitno += nb) {
2221 		/* determine the bit number within the word and
2222 		 * the number of bits within the word.
2223 		 */
2224 		wbitno = dbitno & (DBWORD - 1);
2225 		nb = min(rembits, DBWORD - wbitno);
2226 
2227 		/* check if only part of a word is to be allocated.
2228 		 */
2229 		if (nb < DBWORD) {
2230 			/* allocate (set to 1) the appropriate bits within
2231 			 * this dmap word.
2232 			 */
2233 			dp->wmap[word] |= cpu_to_le32(ONES << (DBWORD - nb)
2234 						      >> wbitno);
2235 
2236 			/* update the leaf for this dmap word. in addition
2237 			 * to setting the leaf value to the binary buddy max
2238 			 * of the updated dmap word, dbSplit() will split
2239 			 * the binary system of the leaves if need be.
2240 			 */
2241 			dbSplit(tp, word, BUDMIN,
2242 				dbMaxBud((u8 *) & dp->wmap[word]));
2243 
2244 			word += 1;
2245 		} else {
2246 			/* one or more dmap words are fully contained
2247 			 * within the block range.  determine how many
2248 			 * words and allocate (set to 1) the bits of these
2249 			 * words.
2250 			 */
2251 			nwords = rembits >> L2DBWORD;
2252 			memset(&dp->wmap[word], (int) ONES, nwords * 4);
2253 
2254 			/* determine how many bits.
2255 			 */
2256 			nb = nwords << L2DBWORD;
2257 
2258 			/* now update the appropriate leaves to reflect
2259 			 * the allocated words.
2260 			 */
2261 			for (; nwords > 0; nwords -= nw) {
2262 				if (leaf[word] < BUDMIN) {
2263 					jfs_error(bmp->db_ipbmap->i_sb,
2264 						  "leaf page corrupt\n");
2265 					break;
2266 				}
2267 
2268 				/* determine what the leaf value should be
2269 				 * updated to as the minimum of the l2 number
2270 				 * of bits being allocated and the l2 number
2271 				 * of bits currently described by this leaf.
2272 				 */
2273 				size = min_t(int, leaf[word],
2274 					     NLSTOL2BSZ(nwords));
2275 
2276 				/* update the leaf to reflect the allocation.
2277 				 * in addition to setting the leaf value to
2278 				 * NOFREE, dbSplit() will split the binary
2279 				 * system of the leaves to reflect the current
2280 				 * allocation (size).
2281 				 */
2282 				dbSplit(tp, word, size, NOFREE);
2283 
2284 				/* get the number of dmap words handled */
2285 				nw = BUDSIZE(size, BUDMIN);
2286 				word += nw;
2287 			}
2288 		}
2289 	}
2290 
2291 	/* update the free count for this dmap */
2292 	le32_add_cpu(&dp->nfree, -nblocks);
2293 
2294 	BMAP_LOCK(bmp);
2295 
2296 	/* if this allocation group is completely free,
2297 	 * update the maximum allocation group number if this allocation
2298 	 * group is the new max.
2299 	 */
2300 	agno = blkno >> bmp->db_agl2size;
2301 	if (agno > bmp->db_maxag)
2302 		bmp->db_maxag = agno;
2303 
2304 	/* update the free count for the allocation group and map */
2305 	bmp->db_agfree[agno] -= nblocks;
2306 	bmp->db_nfree -= nblocks;
2307 
2308 	BMAP_UNLOCK(bmp);
2309 }
2310 
2311 
2312 /*
2313  * NAME:	dbFreeBits()
2314  *
2315  * FUNCTION:	free a specified block range from a dmap.
2316  *
2317  *		this routine updates the dmap to reflect the working
2318  *		state allocation of the specified block range. it directly
2319  *		updates the bits of the working map and causes the adjustment
2320  *		of the binary buddy system described by the dmap's dmtree
2321  *		leaves to reflect the bits freed.  it also causes the dmap's
2322  *		dmtree, as a whole, to reflect the deallocated range.
2323  *
2324  * PARAMETERS:
2325  *	bmp	-  pointer to bmap descriptor
2326  *	dp	-  pointer to dmap to free bits from.
2327  *	blkno	-  starting block number of the bits to be freed.
2328  *	nblocks	-  number of bits to be freed.
2329  *
2330  * RETURN VALUES: 0 for success
2331  *
2332  * serialization: IREAD_LOCK(ipbmap) or IWRITE_LOCK(ipbmap) held on entry/exit;
2333  */
dbFreeBits(struct bmap * bmp,struct dmap * dp,s64 blkno,int nblocks)2334 static int dbFreeBits(struct bmap * bmp, struct dmap * dp, s64 blkno,
2335 		       int nblocks)
2336 {
2337 	int dbitno, word, rembits, nb, nwords, wbitno, nw, agno;
2338 	dmtree_t *tp = (dmtree_t *) & dp->tree;
2339 	int rc = 0;
2340 	int size;
2341 
2342 	/* determine the bit number and word within the dmap of the
2343 	 * starting block.
2344 	 */
2345 	dbitno = blkno & (BPERDMAP - 1);
2346 	word = dbitno >> L2DBWORD;
2347 
2348 	/* block range better be within the dmap.
2349 	 */
2350 	assert(dbitno + nblocks <= BPERDMAP);
2351 
2352 	/* free the bits of the dmaps words corresponding to the block range.
2353 	 * not all bits of the first and last words may be contained within
2354 	 * the block range.  if this is the case, we'll work against those
2355 	 * words (i.e. partial first and/or last) on an individual basis
2356 	 * (a single pass), freeing the bits of interest by hand and updating
2357 	 * the leaf corresponding to the dmap word. a single pass will be used
2358 	 * for all dmap words fully contained within the specified range.
2359 	 * within this pass, the bits of all fully contained dmap words will
2360 	 * be marked as free in a single shot and the leaves will be updated. a
2361 	 * single leaf may describe the free space of multiple dmap words,
2362 	 * so we may update only a subset of the actual leaves corresponding
2363 	 * to the dmap words of the block range.
2364 	 *
2365 	 * dbJoin() is used to update leaf values and will join the binary
2366 	 * buddy system of the leaves if the new leaf values indicate this
2367 	 * should be done.
2368 	 */
2369 	for (rembits = nblocks; rembits > 0; rembits -= nb, dbitno += nb) {
2370 		/* determine the bit number within the word and
2371 		 * the number of bits within the word.
2372 		 */
2373 		wbitno = dbitno & (DBWORD - 1);
2374 		nb = min(rembits, DBWORD - wbitno);
2375 
2376 		/* check if only part of a word is to be freed.
2377 		 */
2378 		if (nb < DBWORD) {
2379 			/* free (zero) the appropriate bits within this
2380 			 * dmap word.
2381 			 */
2382 			dp->wmap[word] &=
2383 			    cpu_to_le32(~(ONES << (DBWORD - nb)
2384 					  >> wbitno));
2385 
2386 			/* update the leaf for this dmap word.
2387 			 */
2388 			rc = dbJoin(tp, word,
2389 				    dbMaxBud((u8 *) & dp->wmap[word]));
2390 			if (rc)
2391 				return rc;
2392 
2393 			word += 1;
2394 		} else {
2395 			/* one or more dmap words are fully contained
2396 			 * within the block range.  determine how many
2397 			 * words and free (zero) the bits of these words.
2398 			 */
2399 			nwords = rembits >> L2DBWORD;
2400 			memset(&dp->wmap[word], 0, nwords * 4);
2401 
2402 			/* determine how many bits.
2403 			 */
2404 			nb = nwords << L2DBWORD;
2405 
2406 			/* now update the appropriate leaves to reflect
2407 			 * the freed words.
2408 			 */
2409 			for (; nwords > 0; nwords -= nw) {
2410 				/* determine what the leaf value should be
2411 				 * updated to as the minimum of the l2 number
2412 				 * of bits being freed and the l2 (max) number
2413 				 * of bits that can be described by this leaf.
2414 				 */
2415 				size =
2416 				    min(LITOL2BSZ
2417 					(word, L2LPERDMAP, BUDMIN),
2418 					NLSTOL2BSZ(nwords));
2419 
2420 				/* update the leaf.
2421 				 */
2422 				rc = dbJoin(tp, word, size);
2423 				if (rc)
2424 					return rc;
2425 
2426 				/* get the number of dmap words handled.
2427 				 */
2428 				nw = BUDSIZE(size, BUDMIN);
2429 				word += nw;
2430 			}
2431 		}
2432 	}
2433 
2434 	/* update the free count for this dmap.
2435 	 */
2436 	le32_add_cpu(&dp->nfree, nblocks);
2437 
2438 	BMAP_LOCK(bmp);
2439 
2440 	/* update the free count for the allocation group and
2441 	 * map.
2442 	 */
2443 	agno = blkno >> bmp->db_agl2size;
2444 	bmp->db_nfree += nblocks;
2445 	bmp->db_agfree[agno] += nblocks;
2446 
2447 	/* check if this allocation group is not completely free and
2448 	 * if it is currently the maximum (rightmost) allocation group.
2449 	 * if so, establish the new maximum allocation group number by
2450 	 * searching left for the first allocation group with allocation.
2451 	 */
2452 	if ((bmp->db_agfree[agno] == bmp->db_agsize && agno == bmp->db_maxag) ||
2453 	    (agno == bmp->db_numag - 1 &&
2454 	     bmp->db_agfree[agno] == (bmp-> db_mapsize & (BPERDMAP - 1)))) {
2455 		while (bmp->db_maxag > 0) {
2456 			bmp->db_maxag -= 1;
2457 			if (bmp->db_agfree[bmp->db_maxag] !=
2458 			    bmp->db_agsize)
2459 				break;
2460 		}
2461 
2462 		/* re-establish the allocation group preference if the
2463 		 * current preference is right of the maximum allocation
2464 		 * group.
2465 		 */
2466 		if (bmp->db_agpref > bmp->db_maxag)
2467 			bmp->db_agpref = bmp->db_maxag;
2468 	}
2469 
2470 	BMAP_UNLOCK(bmp);
2471 
2472 	return 0;
2473 }
2474 
2475 
2476 /*
2477  * NAME:	dbAdjCtl()
2478  *
2479  * FUNCTION:	adjust a dmap control page at a specified level to reflect
2480  *		the change in a lower level dmap or dmap control page's
2481  *		maximum string of free blocks (i.e. a change in the root
2482  *		of the lower level object's dmtree) due to the allocation
2483  *		or deallocation of a range of blocks with a single dmap.
2484  *
2485  *		on entry, this routine is provided with the new value of
2486  *		the lower level dmap or dmap control page root and the
2487  *		starting block number of the block range whose allocation
2488  *		or deallocation resulted in the root change.  this range
2489  *		is respresented by a single leaf of the current dmapctl
2490  *		and the leaf will be updated with this value, possibly
2491  *		causing a binary buddy system within the leaves to be
2492  *		split or joined.  the update may also cause the dmapctl's
2493  *		dmtree to be updated.
2494  *
2495  *		if the adjustment of the dmap control page, itself, causes its
2496  *		root to change, this change will be bubbled up to the next dmap
2497  *		control level by a recursive call to this routine, specifying
2498  *		the new root value and the next dmap control page level to
2499  *		be adjusted.
2500  * PARAMETERS:
2501  *	bmp	-  pointer to bmap descriptor
2502  *	blkno	-  the first block of a block range within a dmap.  it is
2503  *		   the allocation or deallocation of this block range that
2504  *		   requires the dmap control page to be adjusted.
2505  *	newval	-  the new value of the lower level dmap or dmap control
2506  *		   page root.
2507  *	alloc	-  'true' if adjustment is due to an allocation.
2508  *	level	-  current level of dmap control page (i.e. L0, L1, L2) to
2509  *		   be adjusted.
2510  *
2511  * RETURN VALUES:
2512  *	0	- success
2513  *	-EIO	- i/o error
2514  *
2515  * serialization: IREAD_LOCK(ipbmap) or IWRITE_LOCK(ipbmap) held on entry/exit;
2516  */
2517 static int
dbAdjCtl(struct bmap * bmp,s64 blkno,int newval,int alloc,int level)2518 dbAdjCtl(struct bmap * bmp, s64 blkno, int newval, int alloc, int level)
2519 {
2520 	struct metapage *mp;
2521 	s8 oldroot;
2522 	int oldval;
2523 	s64 lblkno;
2524 	struct dmapctl *dcp;
2525 	int rc, leafno, ti;
2526 
2527 	/* get the buffer for the dmap control page for the specified
2528 	 * block number and control page level.
2529 	 */
2530 	lblkno = BLKTOCTL(blkno, bmp->db_l2nbperpage, level);
2531 	mp = read_metapage(bmp->db_ipbmap, lblkno, PSIZE, 0);
2532 	if (mp == NULL)
2533 		return -EIO;
2534 	dcp = (struct dmapctl *) mp->data;
2535 
2536 	if (dcp->leafidx != cpu_to_le32(CTLLEAFIND)) {
2537 		jfs_error(bmp->db_ipbmap->i_sb, "Corrupt dmapctl page\n");
2538 		release_metapage(mp);
2539 		return -EIO;
2540 	}
2541 
2542 	/* determine the leaf number corresponding to the block and
2543 	 * the index within the dmap control tree.
2544 	 */
2545 	leafno = BLKTOCTLLEAF(blkno, dcp->budmin);
2546 	ti = leafno + le32_to_cpu(dcp->leafidx);
2547 
2548 	/* save the current leaf value and the current root level (i.e.
2549 	 * maximum l2 free string described by this dmapctl).
2550 	 */
2551 	oldval = dcp->stree[ti];
2552 	oldroot = dcp->stree[ROOT];
2553 
2554 	/* check if this is a control page update for an allocation.
2555 	 * if so, update the leaf to reflect the new leaf value using
2556 	 * dbSplit(); otherwise (deallocation), use dbJoin() to update
2557 	 * the leaf with the new value.  in addition to updating the
2558 	 * leaf, dbSplit() will also split the binary buddy system of
2559 	 * the leaves, if required, and bubble new values within the
2560 	 * dmapctl tree, if required.  similarly, dbJoin() will join
2561 	 * the binary buddy system of leaves and bubble new values up
2562 	 * the dmapctl tree as required by the new leaf value.
2563 	 */
2564 	if (alloc) {
2565 		/* check if we are in the middle of a binary buddy
2566 		 * system.  this happens when we are performing the
2567 		 * first allocation out of an allocation group that
2568 		 * is part (not the first part) of a larger binary
2569 		 * buddy system.  if we are in the middle, back split
2570 		 * the system prior to calling dbSplit() which assumes
2571 		 * that it is at the front of a binary buddy system.
2572 		 */
2573 		if (oldval == NOFREE) {
2574 			rc = dbBackSplit((dmtree_t *) dcp, leafno);
2575 			if (rc)
2576 				return rc;
2577 			oldval = dcp->stree[ti];
2578 		}
2579 		dbSplit((dmtree_t *) dcp, leafno, dcp->budmin, newval);
2580 	} else {
2581 		rc = dbJoin((dmtree_t *) dcp, leafno, newval);
2582 		if (rc)
2583 			return rc;
2584 	}
2585 
2586 	/* check if the root of the current dmap control page changed due
2587 	 * to the update and if the current dmap control page is not at
2588 	 * the current top level (i.e. L0, L1, L2) of the map.  if so (i.e.
2589 	 * root changed and this is not the top level), call this routine
2590 	 * again (recursion) for the next higher level of the mapping to
2591 	 * reflect the change in root for the current dmap control page.
2592 	 */
2593 	if (dcp->stree[ROOT] != oldroot) {
2594 		/* are we below the top level of the map.  if so,
2595 		 * bubble the root up to the next higher level.
2596 		 */
2597 		if (level < bmp->db_maxlevel) {
2598 			/* bubble up the new root of this dmap control page to
2599 			 * the next level.
2600 			 */
2601 			if ((rc =
2602 			     dbAdjCtl(bmp, blkno, dcp->stree[ROOT], alloc,
2603 				      level + 1))) {
2604 				/* something went wrong in bubbling up the new
2605 				 * root value, so backout the changes to the
2606 				 * current dmap control page.
2607 				 */
2608 				if (alloc) {
2609 					dbJoin((dmtree_t *) dcp, leafno,
2610 					       oldval);
2611 				} else {
2612 					/* the dbJoin() above might have
2613 					 * caused a larger binary buddy system
2614 					 * to form and we may now be in the
2615 					 * middle of it.  if this is the case,
2616 					 * back split the buddies.
2617 					 */
2618 					if (dcp->stree[ti] == NOFREE)
2619 						dbBackSplit((dmtree_t *)
2620 							    dcp, leafno);
2621 					dbSplit((dmtree_t *) dcp, leafno,
2622 						dcp->budmin, oldval);
2623 				}
2624 
2625 				/* release the buffer and return the error.
2626 				 */
2627 				release_metapage(mp);
2628 				return (rc);
2629 			}
2630 		} else {
2631 			/* we're at the top level of the map. update
2632 			 * the bmap control page to reflect the size
2633 			 * of the maximum free buddy system.
2634 			 */
2635 			assert(level == bmp->db_maxlevel);
2636 			if (bmp->db_maxfreebud != oldroot) {
2637 				jfs_error(bmp->db_ipbmap->i_sb,
2638 					  "the maximum free buddy is not the old root\n");
2639 			}
2640 			bmp->db_maxfreebud = dcp->stree[ROOT];
2641 		}
2642 	}
2643 
2644 	/* write the buffer.
2645 	 */
2646 	write_metapage(mp);
2647 
2648 	return (0);
2649 }
2650 
2651 
2652 /*
2653  * NAME:	dbSplit()
2654  *
2655  * FUNCTION:	update the leaf of a dmtree with a new value, splitting
2656  *		the leaf from the binary buddy system of the dmtree's
2657  *		leaves, as required.
2658  *
2659  * PARAMETERS:
2660  *	tp	- pointer to the tree containing the leaf.
2661  *	leafno	- the number of the leaf to be updated.
2662  *	splitsz	- the size the binary buddy system starting at the leaf
2663  *		  must be split to, specified as the log2 number of blocks.
2664  *	newval	- the new value for the leaf.
2665  *
2666  * RETURN VALUES: none
2667  *
2668  * serialization: IREAD_LOCK(ipbmap) or IWRITE_LOCK(ipbmap) held on entry/exit;
2669  */
dbSplit(dmtree_t * tp,int leafno,int splitsz,int newval)2670 static void dbSplit(dmtree_t * tp, int leafno, int splitsz, int newval)
2671 {
2672 	int budsz;
2673 	int cursz;
2674 	s8 *leaf = tp->dmt_stree + le32_to_cpu(tp->dmt_leafidx);
2675 
2676 	/* check if the leaf needs to be split.
2677 	 */
2678 	if (leaf[leafno] > tp->dmt_budmin) {
2679 		/* the split occurs by cutting the buddy system in half
2680 		 * at the specified leaf until we reach the specified
2681 		 * size.  pick up the starting split size (current size
2682 		 * - 1 in l2) and the corresponding buddy size.
2683 		 */
2684 		cursz = leaf[leafno] - 1;
2685 		budsz = BUDSIZE(cursz, tp->dmt_budmin);
2686 
2687 		/* split until we reach the specified size.
2688 		 */
2689 		while (cursz >= splitsz) {
2690 			/* update the buddy's leaf with its new value.
2691 			 */
2692 			dbAdjTree(tp, leafno ^ budsz, cursz);
2693 
2694 			/* on to the next size and buddy.
2695 			 */
2696 			cursz -= 1;
2697 			budsz >>= 1;
2698 		}
2699 	}
2700 
2701 	/* adjust the dmap tree to reflect the specified leaf's new
2702 	 * value.
2703 	 */
2704 	dbAdjTree(tp, leafno, newval);
2705 }
2706 
2707 
2708 /*
2709  * NAME:	dbBackSplit()
2710  *
2711  * FUNCTION:	back split the binary buddy system of dmtree leaves
2712  *		that hold a specified leaf until the specified leaf
2713  *		starts its own binary buddy system.
2714  *
2715  *		the allocators typically perform allocations at the start
2716  *		of binary buddy systems and dbSplit() is used to accomplish
2717  *		any required splits.  in some cases, however, allocation
2718  *		may occur in the middle of a binary system and requires a
2719  *		back split, with the split proceeding out from the middle of
2720  *		the system (less efficient) rather than the start of the
2721  *		system (more efficient).  the cases in which a back split
2722  *		is required are rare and are limited to the first allocation
2723  *		within an allocation group which is a part (not first part)
2724  *		of a larger binary buddy system and a few exception cases
2725  *		in which a previous join operation must be backed out.
2726  *
2727  * PARAMETERS:
2728  *	tp	- pointer to the tree containing the leaf.
2729  *	leafno	- the number of the leaf to be updated.
2730  *
2731  * RETURN VALUES: none
2732  *
2733  * serialization: IREAD_LOCK(ipbmap) or IWRITE_LOCK(ipbmap) held on entry/exit;
2734  */
dbBackSplit(dmtree_t * tp,int leafno)2735 static int dbBackSplit(dmtree_t * tp, int leafno)
2736 {
2737 	int budsz, bud, w, bsz, size;
2738 	int cursz;
2739 	s8 *leaf = tp->dmt_stree + le32_to_cpu(tp->dmt_leafidx);
2740 
2741 	/* leaf should be part (not first part) of a binary
2742 	 * buddy system.
2743 	 */
2744 	assert(leaf[leafno] == NOFREE);
2745 
2746 	/* the back split is accomplished by iteratively finding the leaf
2747 	 * that starts the buddy system that contains the specified leaf and
2748 	 * splitting that system in two.  this iteration continues until
2749 	 * the specified leaf becomes the start of a buddy system.
2750 	 *
2751 	 * determine maximum possible l2 size for the specified leaf.
2752 	 */
2753 	size =
2754 	    LITOL2BSZ(leafno, le32_to_cpu(tp->dmt_l2nleafs),
2755 		      tp->dmt_budmin);
2756 
2757 	/* determine the number of leaves covered by this size.  this
2758 	 * is the buddy size that we will start with as we search for
2759 	 * the buddy system that contains the specified leaf.
2760 	 */
2761 	budsz = BUDSIZE(size, tp->dmt_budmin);
2762 
2763 	/* back split.
2764 	 */
2765 	while (leaf[leafno] == NOFREE) {
2766 		/* find the leftmost buddy leaf.
2767 		 */
2768 		for (w = leafno, bsz = budsz;; bsz <<= 1,
2769 		     w = (w < bud) ? w : bud) {
2770 			if (bsz >= le32_to_cpu(tp->dmt_nleafs)) {
2771 				jfs_err("JFS: block map error in dbBackSplit");
2772 				return -EIO;
2773 			}
2774 
2775 			/* determine the buddy.
2776 			 */
2777 			bud = w ^ bsz;
2778 
2779 			/* check if this buddy is the start of the system.
2780 			 */
2781 			if (leaf[bud] != NOFREE) {
2782 				/* split the leaf at the start of the
2783 				 * system in two.
2784 				 */
2785 				cursz = leaf[bud] - 1;
2786 				dbSplit(tp, bud, cursz, cursz);
2787 				break;
2788 			}
2789 		}
2790 	}
2791 
2792 	if (leaf[leafno] != size) {
2793 		jfs_err("JFS: wrong leaf value in dbBackSplit");
2794 		return -EIO;
2795 	}
2796 	return 0;
2797 }
2798 
2799 
2800 /*
2801  * NAME:	dbJoin()
2802  *
2803  * FUNCTION:	update the leaf of a dmtree with a new value, joining
2804  *		the leaf with other leaves of the dmtree into a multi-leaf
2805  *		binary buddy system, as required.
2806  *
2807  * PARAMETERS:
2808  *	tp	- pointer to the tree containing the leaf.
2809  *	leafno	- the number of the leaf to be updated.
2810  *	newval	- the new value for the leaf.
2811  *
2812  * RETURN VALUES: none
2813  */
dbJoin(dmtree_t * tp,int leafno,int newval)2814 static int dbJoin(dmtree_t * tp, int leafno, int newval)
2815 {
2816 	int budsz, buddy;
2817 	s8 *leaf;
2818 
2819 	/* can the new leaf value require a join with other leaves ?
2820 	 */
2821 	if (newval >= tp->dmt_budmin) {
2822 		/* pickup a pointer to the leaves of the tree.
2823 		 */
2824 		leaf = tp->dmt_stree + le32_to_cpu(tp->dmt_leafidx);
2825 
2826 		/* try to join the specified leaf into a large binary
2827 		 * buddy system.  the join proceeds by attempting to join
2828 		 * the specified leafno with its buddy (leaf) at new value.
2829 		 * if the join occurs, we attempt to join the left leaf
2830 		 * of the joined buddies with its buddy at new value + 1.
2831 		 * we continue to join until we find a buddy that cannot be
2832 		 * joined (does not have a value equal to the size of the
2833 		 * last join) or until all leaves have been joined into a
2834 		 * single system.
2835 		 *
2836 		 * get the buddy size (number of words covered) of
2837 		 * the new value.
2838 		 */
2839 		budsz = BUDSIZE(newval, tp->dmt_budmin);
2840 
2841 		/* try to join.
2842 		 */
2843 		while (budsz < le32_to_cpu(tp->dmt_nleafs)) {
2844 			/* get the buddy leaf.
2845 			 */
2846 			buddy = leafno ^ budsz;
2847 
2848 			/* if the leaf's new value is greater than its
2849 			 * buddy's value, we join no more.
2850 			 */
2851 			if (newval > leaf[buddy])
2852 				break;
2853 
2854 			/* It shouldn't be less */
2855 			if (newval < leaf[buddy])
2856 				return -EIO;
2857 
2858 			/* check which (leafno or buddy) is the left buddy.
2859 			 * the left buddy gets to claim the blocks resulting
2860 			 * from the join while the right gets to claim none.
2861 			 * the left buddy is also eligible to participate in
2862 			 * a join at the next higher level while the right
2863 			 * is not.
2864 			 *
2865 			 */
2866 			if (leafno < buddy) {
2867 				/* leafno is the left buddy.
2868 				 */
2869 				dbAdjTree(tp, buddy, NOFREE);
2870 			} else {
2871 				/* buddy is the left buddy and becomes
2872 				 * leafno.
2873 				 */
2874 				dbAdjTree(tp, leafno, NOFREE);
2875 				leafno = buddy;
2876 			}
2877 
2878 			/* on to try the next join.
2879 			 */
2880 			newval += 1;
2881 			budsz <<= 1;
2882 		}
2883 	}
2884 
2885 	/* update the leaf value.
2886 	 */
2887 	dbAdjTree(tp, leafno, newval);
2888 
2889 	return 0;
2890 }
2891 
2892 
2893 /*
2894  * NAME:	dbAdjTree()
2895  *
2896  * FUNCTION:	update a leaf of a dmtree with a new value, adjusting
2897  *		the dmtree, as required, to reflect the new leaf value.
2898  *		the combination of any buddies must already be done before
2899  *		this is called.
2900  *
2901  * PARAMETERS:
2902  *	tp	- pointer to the tree to be adjusted.
2903  *	leafno	- the number of the leaf to be updated.
2904  *	newval	- the new value for the leaf.
2905  *
2906  * RETURN VALUES: none
2907  */
dbAdjTree(dmtree_t * tp,int leafno,int newval)2908 static void dbAdjTree(dmtree_t * tp, int leafno, int newval)
2909 {
2910 	int lp, pp, k;
2911 	int max;
2912 
2913 	/* pick up the index of the leaf for this leafno.
2914 	 */
2915 	lp = leafno + le32_to_cpu(tp->dmt_leafidx);
2916 
2917 	/* is the current value the same as the old value ?  if so,
2918 	 * there is nothing to do.
2919 	 */
2920 	if (tp->dmt_stree[lp] == newval)
2921 		return;
2922 
2923 	/* set the new value.
2924 	 */
2925 	tp->dmt_stree[lp] = newval;
2926 
2927 	/* bubble the new value up the tree as required.
2928 	 */
2929 	for (k = 0; k < le32_to_cpu(tp->dmt_height); k++) {
2930 		/* get the index of the first leaf of the 4 leaf
2931 		 * group containing the specified leaf (leafno).
2932 		 */
2933 		lp = ((lp - 1) & ~0x03) + 1;
2934 
2935 		/* get the index of the parent of this 4 leaf group.
2936 		 */
2937 		pp = (lp - 1) >> 2;
2938 
2939 		/* determine the maximum of the 4 leaves.
2940 		 */
2941 		max = TREEMAX(&tp->dmt_stree[lp]);
2942 
2943 		/* if the maximum of the 4 is the same as the
2944 		 * parent's value, we're done.
2945 		 */
2946 		if (tp->dmt_stree[pp] == max)
2947 			break;
2948 
2949 		/* parent gets new value.
2950 		 */
2951 		tp->dmt_stree[pp] = max;
2952 
2953 		/* parent becomes leaf for next go-round.
2954 		 */
2955 		lp = pp;
2956 	}
2957 }
2958 
2959 
2960 /*
2961  * NAME:	dbFindLeaf()
2962  *
2963  * FUNCTION:	search a dmtree_t for sufficient free blocks, returning
2964  *		the index of a leaf describing the free blocks if
2965  *		sufficient free blocks are found.
2966  *
2967  *		the search starts at the top of the dmtree_t tree and
2968  *		proceeds down the tree to the leftmost leaf with sufficient
2969  *		free space.
2970  *
2971  * PARAMETERS:
2972  *	tp	- pointer to the tree to be searched.
2973  *	l2nb	- log2 number of free blocks to search for.
2974  *	leafidx	- return pointer to be set to the index of the leaf
2975  *		  describing at least l2nb free blocks if sufficient
2976  *		  free blocks are found.
2977  *
2978  * RETURN VALUES:
2979  *	0	- success
2980  *	-ENOSPC	- insufficient free blocks.
2981  */
dbFindLeaf(dmtree_t * tp,int l2nb,int * leafidx)2982 static int dbFindLeaf(dmtree_t * tp, int l2nb, int *leafidx)
2983 {
2984 	int ti, n = 0, k, x = 0;
2985 
2986 	/* first check the root of the tree to see if there is
2987 	 * sufficient free space.
2988 	 */
2989 	if (l2nb > tp->dmt_stree[ROOT])
2990 		return -ENOSPC;
2991 
2992 	/* sufficient free space available. now search down the tree
2993 	 * starting at the next level for the leftmost leaf that
2994 	 * describes sufficient free space.
2995 	 */
2996 	for (k = le32_to_cpu(tp->dmt_height), ti = 1;
2997 	     k > 0; k--, ti = ((ti + n) << 2) + 1) {
2998 		/* search the four nodes at this level, starting from
2999 		 * the left.
3000 		 */
3001 		for (x = ti, n = 0; n < 4; n++) {
3002 			/* sufficient free space found.  move to the next
3003 			 * level (or quit if this is the last level).
3004 			 */
3005 			if (l2nb <= tp->dmt_stree[x + n])
3006 				break;
3007 		}
3008 
3009 		/* better have found something since the higher
3010 		 * levels of the tree said it was here.
3011 		 */
3012 		assert(n < 4);
3013 	}
3014 
3015 	/* set the return to the leftmost leaf describing sufficient
3016 	 * free space.
3017 	 */
3018 	*leafidx = x + n - le32_to_cpu(tp->dmt_leafidx);
3019 
3020 	return (0);
3021 }
3022 
3023 
3024 /*
3025  * NAME:	dbFindBits()
3026  *
3027  * FUNCTION:	find a specified number of binary buddy free bits within a
3028  *		dmap bitmap word value.
3029  *
3030  *		this routine searches the bitmap value for (1 << l2nb) free
3031  *		bits at (1 << l2nb) alignments within the value.
3032  *
3033  * PARAMETERS:
3034  *	word	-  dmap bitmap word value.
3035  *	l2nb	-  number of free bits specified as a log2 number.
3036  *
3037  * RETURN VALUES:
3038  *	starting bit number of free bits.
3039  */
dbFindBits(u32 word,int l2nb)3040 static int dbFindBits(u32 word, int l2nb)
3041 {
3042 	int bitno, nb;
3043 	u32 mask;
3044 
3045 	/* get the number of bits.
3046 	 */
3047 	nb = 1 << l2nb;
3048 	assert(nb <= DBWORD);
3049 
3050 	/* complement the word so we can use a mask (i.e. 0s represent
3051 	 * free bits) and compute the mask.
3052 	 */
3053 	word = ~word;
3054 	mask = ONES << (DBWORD - nb);
3055 
3056 	/* scan the word for nb free bits at nb alignments.
3057 	 */
3058 	for (bitno = 0; mask != 0; bitno += nb, mask >>= nb) {
3059 		if ((mask & word) == mask)
3060 			break;
3061 	}
3062 
3063 	ASSERT(bitno < 32);
3064 
3065 	/* return the bit number.
3066 	 */
3067 	return (bitno);
3068 }
3069 
3070 
3071 /*
3072  * NAME:	dbMaxBud(u8 *cp)
3073  *
3074  * FUNCTION:	determine the largest binary buddy string of free
3075  *		bits within 32-bits of the map.
3076  *
3077  * PARAMETERS:
3078  *	cp	-  pointer to the 32-bit value.
3079  *
3080  * RETURN VALUES:
3081  *	largest binary buddy of free bits within a dmap word.
3082  */
dbMaxBud(u8 * cp)3083 static int dbMaxBud(u8 * cp)
3084 {
3085 	signed char tmp1, tmp2;
3086 
3087 	/* check if the wmap word is all free. if so, the
3088 	 * free buddy size is BUDMIN.
3089 	 */
3090 	if (*((uint *) cp) == 0)
3091 		return (BUDMIN);
3092 
3093 	/* check if the wmap word is half free. if so, the
3094 	 * free buddy size is BUDMIN-1.
3095 	 */
3096 	if (*((u16 *) cp) == 0 || *((u16 *) cp + 1) == 0)
3097 		return (BUDMIN - 1);
3098 
3099 	/* not all free or half free. determine the free buddy
3100 	 * size thru table lookup using quarters of the wmap word.
3101 	 */
3102 	tmp1 = max(budtab[cp[2]], budtab[cp[3]]);
3103 	tmp2 = max(budtab[cp[0]], budtab[cp[1]]);
3104 	return (max(tmp1, tmp2));
3105 }
3106 
3107 
3108 /*
3109  * NAME:	cnttz(uint word)
3110  *
3111  * FUNCTION:	determine the number of trailing zeros within a 32-bit
3112  *		value.
3113  *
3114  * PARAMETERS:
3115  *	value	-  32-bit value to be examined.
3116  *
3117  * RETURN VALUES:
3118  *	count of trailing zeros
3119  */
cnttz(u32 word)3120 static int cnttz(u32 word)
3121 {
3122 	int n;
3123 
3124 	for (n = 0; n < 32; n++, word >>= 1) {
3125 		if (word & 0x01)
3126 			break;
3127 	}
3128 
3129 	return (n);
3130 }
3131 
3132 
3133 /*
3134  * NAME:	cntlz(u32 value)
3135  *
3136  * FUNCTION:	determine the number of leading zeros within a 32-bit
3137  *		value.
3138  *
3139  * PARAMETERS:
3140  *	value	-  32-bit value to be examined.
3141  *
3142  * RETURN VALUES:
3143  *	count of leading zeros
3144  */
cntlz(u32 value)3145 static int cntlz(u32 value)
3146 {
3147 	int n;
3148 
3149 	for (n = 0; n < 32; n++, value <<= 1) {
3150 		if (value & HIGHORDER)
3151 			break;
3152 	}
3153 	return (n);
3154 }
3155 
3156 
3157 /*
3158  * NAME:	blkstol2(s64 nb)
3159  *
3160  * FUNCTION:	convert a block count to its log2 value. if the block
3161  *		count is not a l2 multiple, it is rounded up to the next
3162  *		larger l2 multiple.
3163  *
3164  * PARAMETERS:
3165  *	nb	-  number of blocks
3166  *
3167  * RETURN VALUES:
3168  *	log2 number of blocks
3169  */
blkstol2(s64 nb)3170 static int blkstol2(s64 nb)
3171 {
3172 	int l2nb;
3173 	s64 mask;		/* meant to be signed */
3174 
3175 	mask = (s64) 1 << (64 - 1);
3176 
3177 	/* count the leading bits.
3178 	 */
3179 	for (l2nb = 0; l2nb < 64; l2nb++, mask >>= 1) {
3180 		/* leading bit found.
3181 		 */
3182 		if (nb & mask) {
3183 			/* determine the l2 value.
3184 			 */
3185 			l2nb = (64 - 1) - l2nb;
3186 
3187 			/* check if we need to round up.
3188 			 */
3189 			if (~mask & nb)
3190 				l2nb++;
3191 
3192 			return (l2nb);
3193 		}
3194 	}
3195 	assert(0);
3196 	return 0;		/* fix compiler warning */
3197 }
3198 
3199 
3200 /*
3201  * NAME:	dbAllocBottomUp()
3202  *
3203  * FUNCTION:	alloc the specified block range from the working block
3204  *		allocation map.
3205  *
3206  *		the blocks will be alloc from the working map one dmap
3207  *		at a time.
3208  *
3209  * PARAMETERS:
3210  *	ip	-  pointer to in-core inode;
3211  *	blkno	-  starting block number to be freed.
3212  *	nblocks	-  number of blocks to be freed.
3213  *
3214  * RETURN VALUES:
3215  *	0	- success
3216  *	-EIO	- i/o error
3217  */
dbAllocBottomUp(struct inode * ip,s64 blkno,s64 nblocks)3218 int dbAllocBottomUp(struct inode *ip, s64 blkno, s64 nblocks)
3219 {
3220 	struct metapage *mp;
3221 	struct dmap *dp;
3222 	int nb, rc;
3223 	s64 lblkno, rem;
3224 	struct inode *ipbmap = JFS_SBI(ip->i_sb)->ipbmap;
3225 	struct bmap *bmp = JFS_SBI(ip->i_sb)->bmap;
3226 
3227 	IREAD_LOCK(ipbmap, RDWRLOCK_DMAP);
3228 
3229 	/* block to be allocated better be within the mapsize. */
3230 	ASSERT(nblocks <= bmp->db_mapsize - blkno);
3231 
3232 	/*
3233 	 * allocate the blocks a dmap at a time.
3234 	 */
3235 	mp = NULL;
3236 	for (rem = nblocks; rem > 0; rem -= nb, blkno += nb) {
3237 		/* release previous dmap if any */
3238 		if (mp) {
3239 			write_metapage(mp);
3240 		}
3241 
3242 		/* get the buffer for the current dmap. */
3243 		lblkno = BLKTODMAP(blkno, bmp->db_l2nbperpage);
3244 		mp = read_metapage(ipbmap, lblkno, PSIZE, 0);
3245 		if (mp == NULL) {
3246 			IREAD_UNLOCK(ipbmap);
3247 			return -EIO;
3248 		}
3249 		dp = (struct dmap *) mp->data;
3250 
3251 		/* determine the number of blocks to be allocated from
3252 		 * this dmap.
3253 		 */
3254 		nb = min(rem, BPERDMAP - (blkno & (BPERDMAP - 1)));
3255 
3256 		/* allocate the blocks. */
3257 		if ((rc = dbAllocDmapBU(bmp, dp, blkno, nb))) {
3258 			release_metapage(mp);
3259 			IREAD_UNLOCK(ipbmap);
3260 			return (rc);
3261 		}
3262 	}
3263 
3264 	/* write the last buffer. */
3265 	write_metapage(mp);
3266 
3267 	IREAD_UNLOCK(ipbmap);
3268 
3269 	return (0);
3270 }
3271 
3272 
dbAllocDmapBU(struct bmap * bmp,struct dmap * dp,s64 blkno,int nblocks)3273 static int dbAllocDmapBU(struct bmap * bmp, struct dmap * dp, s64 blkno,
3274 			 int nblocks)
3275 {
3276 	int rc;
3277 	int dbitno, word, rembits, nb, nwords, wbitno, agno;
3278 	s8 oldroot;
3279 	struct dmaptree *tp = (struct dmaptree *) & dp->tree;
3280 
3281 	/* save the current value of the root (i.e. maximum free string)
3282 	 * of the dmap tree.
3283 	 */
3284 	oldroot = tp->stree[ROOT];
3285 
3286 	/* determine the bit number and word within the dmap of the
3287 	 * starting block.
3288 	 */
3289 	dbitno = blkno & (BPERDMAP - 1);
3290 	word = dbitno >> L2DBWORD;
3291 
3292 	/* block range better be within the dmap */
3293 	assert(dbitno + nblocks <= BPERDMAP);
3294 
3295 	/* allocate the bits of the dmap's words corresponding to the block
3296 	 * range. not all bits of the first and last words may be contained
3297 	 * within the block range.  if this is the case, we'll work against
3298 	 * those words (i.e. partial first and/or last) on an individual basis
3299 	 * (a single pass), allocating the bits of interest by hand and
3300 	 * updating the leaf corresponding to the dmap word. a single pass
3301 	 * will be used for all dmap words fully contained within the
3302 	 * specified range.  within this pass, the bits of all fully contained
3303 	 * dmap words will be marked as free in a single shot and the leaves
3304 	 * will be updated. a single leaf may describe the free space of
3305 	 * multiple dmap words, so we may update only a subset of the actual
3306 	 * leaves corresponding to the dmap words of the block range.
3307 	 */
3308 	for (rembits = nblocks; rembits > 0; rembits -= nb, dbitno += nb) {
3309 		/* determine the bit number within the word and
3310 		 * the number of bits within the word.
3311 		 */
3312 		wbitno = dbitno & (DBWORD - 1);
3313 		nb = min(rembits, DBWORD - wbitno);
3314 
3315 		/* check if only part of a word is to be allocated.
3316 		 */
3317 		if (nb < DBWORD) {
3318 			/* allocate (set to 1) the appropriate bits within
3319 			 * this dmap word.
3320 			 */
3321 			dp->wmap[word] |= cpu_to_le32(ONES << (DBWORD - nb)
3322 						      >> wbitno);
3323 
3324 			word++;
3325 		} else {
3326 			/* one or more dmap words are fully contained
3327 			 * within the block range.  determine how many
3328 			 * words and allocate (set to 1) the bits of these
3329 			 * words.
3330 			 */
3331 			nwords = rembits >> L2DBWORD;
3332 			memset(&dp->wmap[word], (int) ONES, nwords * 4);
3333 
3334 			/* determine how many bits */
3335 			nb = nwords << L2DBWORD;
3336 			word += nwords;
3337 		}
3338 	}
3339 
3340 	/* update the free count for this dmap */
3341 	le32_add_cpu(&dp->nfree, -nblocks);
3342 
3343 	/* reconstruct summary tree */
3344 	dbInitDmapTree(dp);
3345 
3346 	BMAP_LOCK(bmp);
3347 
3348 	/* if this allocation group is completely free,
3349 	 * update the highest active allocation group number
3350 	 * if this allocation group is the new max.
3351 	 */
3352 	agno = blkno >> bmp->db_agl2size;
3353 	if (agno > bmp->db_maxag)
3354 		bmp->db_maxag = agno;
3355 
3356 	/* update the free count for the allocation group and map */
3357 	bmp->db_agfree[agno] -= nblocks;
3358 	bmp->db_nfree -= nblocks;
3359 
3360 	BMAP_UNLOCK(bmp);
3361 
3362 	/* if the root has not changed, done. */
3363 	if (tp->stree[ROOT] == oldroot)
3364 		return (0);
3365 
3366 	/* root changed. bubble the change up to the dmap control pages.
3367 	 * if the adjustment of the upper level control pages fails,
3368 	 * backout the bit allocation (thus making everything consistent).
3369 	 */
3370 	if ((rc = dbAdjCtl(bmp, blkno, tp->stree[ROOT], 1, 0)))
3371 		dbFreeBits(bmp, dp, blkno, nblocks);
3372 
3373 	return (rc);
3374 }
3375 
3376 
3377 /*
3378  * NAME:	dbExtendFS()
3379  *
3380  * FUNCTION:	extend bmap from blkno for nblocks;
3381  *		dbExtendFS() updates bmap ready for dbAllocBottomUp();
3382  *
3383  * L2
3384  *  |
3385  *   L1---------------------------------L1
3386  *    |					 |
3387  *     L0---------L0---------L0		  L0---------L0---------L0
3388  *      |	   |	      |		   |	      |		 |
3389  *	 d0,...,dn  d0,...,dn  d0,...,dn    d0,...,dn  d0,...,dn  d0,.,dm;
3390  * L2L1L0d0,...,dnL0d0,...,dnL0d0,...,dnL1L0d0,...,dnL0d0,...,dnL0d0,..dm
3391  *
3392  * <---old---><----------------------------extend----------------------->
3393  */
dbExtendFS(struct inode * ipbmap,s64 blkno,s64 nblocks)3394 int dbExtendFS(struct inode *ipbmap, s64 blkno,	s64 nblocks)
3395 {
3396 	struct jfs_sb_info *sbi = JFS_SBI(ipbmap->i_sb);
3397 	int nbperpage = sbi->nbperpage;
3398 	int i, i0 = true, j, j0 = true, k, n;
3399 	s64 newsize;
3400 	s64 p;
3401 	struct metapage *mp, *l2mp, *l1mp = NULL, *l0mp = NULL;
3402 	struct dmapctl *l2dcp, *l1dcp, *l0dcp;
3403 	struct dmap *dp;
3404 	s8 *l0leaf, *l1leaf, *l2leaf;
3405 	struct bmap *bmp = sbi->bmap;
3406 	int agno, l2agsize, oldl2agsize;
3407 	s64 ag_rem;
3408 
3409 	newsize = blkno + nblocks;
3410 
3411 	jfs_info("dbExtendFS: blkno:%Ld nblocks:%Ld newsize:%Ld",
3412 		 (long long) blkno, (long long) nblocks, (long long) newsize);
3413 
3414 	/*
3415 	 *	initialize bmap control page.
3416 	 *
3417 	 * all the data in bmap control page should exclude
3418 	 * the mkfs hidden dmap page.
3419 	 */
3420 
3421 	/* update mapsize */
3422 	bmp->db_mapsize = newsize;
3423 	bmp->db_maxlevel = BMAPSZTOLEV(bmp->db_mapsize);
3424 
3425 	/* compute new AG size */
3426 	l2agsize = dbGetL2AGSize(newsize);
3427 	oldl2agsize = bmp->db_agl2size;
3428 
3429 	bmp->db_agl2size = l2agsize;
3430 	bmp->db_agsize = 1 << l2agsize;
3431 
3432 	/* compute new number of AG */
3433 	agno = bmp->db_numag;
3434 	bmp->db_numag = newsize >> l2agsize;
3435 	bmp->db_numag += ((u32) newsize % (u32) bmp->db_agsize) ? 1 : 0;
3436 
3437 	/*
3438 	 *	reconfigure db_agfree[]
3439 	 * from old AG configuration to new AG configuration;
3440 	 *
3441 	 * coalesce contiguous k (newAGSize/oldAGSize) AGs;
3442 	 * i.e., (AGi, ..., AGj) where i = k*n and j = k*(n+1) - 1 to AGn;
3443 	 * note: new AG size = old AG size * (2**x).
3444 	 */
3445 	if (l2agsize == oldl2agsize)
3446 		goto extend;
3447 	k = 1 << (l2agsize - oldl2agsize);
3448 	ag_rem = bmp->db_agfree[0];	/* save agfree[0] */
3449 	for (i = 0, n = 0; i < agno; n++) {
3450 		bmp->db_agfree[n] = 0;	/* init collection point */
3451 
3452 		/* coalesce contiguous k AGs; */
3453 		for (j = 0; j < k && i < agno; j++, i++) {
3454 			/* merge AGi to AGn */
3455 			bmp->db_agfree[n] += bmp->db_agfree[i];
3456 		}
3457 	}
3458 	bmp->db_agfree[0] += ag_rem;	/* restore agfree[0] */
3459 
3460 	for (; n < MAXAG; n++)
3461 		bmp->db_agfree[n] = 0;
3462 
3463 	/*
3464 	 * update highest active ag number
3465 	 */
3466 
3467 	bmp->db_maxag = bmp->db_maxag / k;
3468 
3469 	/*
3470 	 *	extend bmap
3471 	 *
3472 	 * update bit maps and corresponding level control pages;
3473 	 * global control page db_nfree, db_agfree[agno], db_maxfreebud;
3474 	 */
3475       extend:
3476 	/* get L2 page */
3477 	p = BMAPBLKNO + nbperpage;	/* L2 page */
3478 	l2mp = read_metapage(ipbmap, p, PSIZE, 0);
3479 	if (!l2mp) {
3480 		jfs_error(ipbmap->i_sb, "L2 page could not be read\n");
3481 		return -EIO;
3482 	}
3483 	l2dcp = (struct dmapctl *) l2mp->data;
3484 
3485 	/* compute start L1 */
3486 	k = blkno >> L2MAXL1SIZE;
3487 	l2leaf = l2dcp->stree + CTLLEAFIND + k;
3488 	p = BLKTOL1(blkno, sbi->l2nbperpage);	/* L1 page */
3489 
3490 	/*
3491 	 * extend each L1 in L2
3492 	 */
3493 	for (; k < LPERCTL; k++, p += nbperpage) {
3494 		/* get L1 page */
3495 		if (j0) {
3496 			/* read in L1 page: (blkno & (MAXL1SIZE - 1)) */
3497 			l1mp = read_metapage(ipbmap, p, PSIZE, 0);
3498 			if (l1mp == NULL)
3499 				goto errout;
3500 			l1dcp = (struct dmapctl *) l1mp->data;
3501 
3502 			/* compute start L0 */
3503 			j = (blkno & (MAXL1SIZE - 1)) >> L2MAXL0SIZE;
3504 			l1leaf = l1dcp->stree + CTLLEAFIND + j;
3505 			p = BLKTOL0(blkno, sbi->l2nbperpage);
3506 			j0 = false;
3507 		} else {
3508 			/* assign/init L1 page */
3509 			l1mp = get_metapage(ipbmap, p, PSIZE, 0);
3510 			if (l1mp == NULL)
3511 				goto errout;
3512 
3513 			l1dcp = (struct dmapctl *) l1mp->data;
3514 
3515 			/* compute start L0 */
3516 			j = 0;
3517 			l1leaf = l1dcp->stree + CTLLEAFIND;
3518 			p += nbperpage;	/* 1st L0 of L1.k */
3519 		}
3520 
3521 		/*
3522 		 * extend each L0 in L1
3523 		 */
3524 		for (; j < LPERCTL; j++) {
3525 			/* get L0 page */
3526 			if (i0) {
3527 				/* read in L0 page: (blkno & (MAXL0SIZE - 1)) */
3528 
3529 				l0mp = read_metapage(ipbmap, p, PSIZE, 0);
3530 				if (l0mp == NULL)
3531 					goto errout;
3532 				l0dcp = (struct dmapctl *) l0mp->data;
3533 
3534 				/* compute start dmap */
3535 				i = (blkno & (MAXL0SIZE - 1)) >>
3536 				    L2BPERDMAP;
3537 				l0leaf = l0dcp->stree + CTLLEAFIND + i;
3538 				p = BLKTODMAP(blkno,
3539 					      sbi->l2nbperpage);
3540 				i0 = false;
3541 			} else {
3542 				/* assign/init L0 page */
3543 				l0mp = get_metapage(ipbmap, p, PSIZE, 0);
3544 				if (l0mp == NULL)
3545 					goto errout;
3546 
3547 				l0dcp = (struct dmapctl *) l0mp->data;
3548 
3549 				/* compute start dmap */
3550 				i = 0;
3551 				l0leaf = l0dcp->stree + CTLLEAFIND;
3552 				p += nbperpage;	/* 1st dmap of L0.j */
3553 			}
3554 
3555 			/*
3556 			 * extend each dmap in L0
3557 			 */
3558 			for (; i < LPERCTL; i++) {
3559 				/*
3560 				 * reconstruct the dmap page, and
3561 				 * initialize corresponding parent L0 leaf
3562 				 */
3563 				if ((n = blkno & (BPERDMAP - 1))) {
3564 					/* read in dmap page: */
3565 					mp = read_metapage(ipbmap, p,
3566 							   PSIZE, 0);
3567 					if (mp == NULL)
3568 						goto errout;
3569 					n = min(nblocks, (s64)BPERDMAP - n);
3570 				} else {
3571 					/* assign/init dmap page */
3572 					mp = read_metapage(ipbmap, p,
3573 							   PSIZE, 0);
3574 					if (mp == NULL)
3575 						goto errout;
3576 
3577 					n = min_t(s64, nblocks, BPERDMAP);
3578 				}
3579 
3580 				dp = (struct dmap *) mp->data;
3581 				*l0leaf = dbInitDmap(dp, blkno, n);
3582 
3583 				bmp->db_nfree += n;
3584 				agno = le64_to_cpu(dp->start) >> l2agsize;
3585 				bmp->db_agfree[agno] += n;
3586 
3587 				write_metapage(mp);
3588 
3589 				l0leaf++;
3590 				p += nbperpage;
3591 
3592 				blkno += n;
3593 				nblocks -= n;
3594 				if (nblocks == 0)
3595 					break;
3596 			}	/* for each dmap in a L0 */
3597 
3598 			/*
3599 			 * build current L0 page from its leaves, and
3600 			 * initialize corresponding parent L1 leaf
3601 			 */
3602 			*l1leaf = dbInitDmapCtl(l0dcp, 0, ++i);
3603 			write_metapage(l0mp);
3604 			l0mp = NULL;
3605 
3606 			if (nblocks)
3607 				l1leaf++;	/* continue for next L0 */
3608 			else {
3609 				/* more than 1 L0 ? */
3610 				if (j > 0)
3611 					break;	/* build L1 page */
3612 				else {
3613 					/* summarize in global bmap page */
3614 					bmp->db_maxfreebud = *l1leaf;
3615 					release_metapage(l1mp);
3616 					release_metapage(l2mp);
3617 					goto finalize;
3618 				}
3619 			}
3620 		}		/* for each L0 in a L1 */
3621 
3622 		/*
3623 		 * build current L1 page from its leaves, and
3624 		 * initialize corresponding parent L2 leaf
3625 		 */
3626 		*l2leaf = dbInitDmapCtl(l1dcp, 1, ++j);
3627 		write_metapage(l1mp);
3628 		l1mp = NULL;
3629 
3630 		if (nblocks)
3631 			l2leaf++;	/* continue for next L1 */
3632 		else {
3633 			/* more than 1 L1 ? */
3634 			if (k > 0)
3635 				break;	/* build L2 page */
3636 			else {
3637 				/* summarize in global bmap page */
3638 				bmp->db_maxfreebud = *l2leaf;
3639 				release_metapage(l2mp);
3640 				goto finalize;
3641 			}
3642 		}
3643 	}			/* for each L1 in a L2 */
3644 
3645 	jfs_error(ipbmap->i_sb, "function has not returned as expected\n");
3646 errout:
3647 	if (l0mp)
3648 		release_metapage(l0mp);
3649 	if (l1mp)
3650 		release_metapage(l1mp);
3651 	release_metapage(l2mp);
3652 	return -EIO;
3653 
3654 	/*
3655 	 *	finalize bmap control page
3656 	 */
3657 finalize:
3658 
3659 	return 0;
3660 }
3661 
3662 
3663 /*
3664  *	dbFinalizeBmap()
3665  */
dbFinalizeBmap(struct inode * ipbmap)3666 void dbFinalizeBmap(struct inode *ipbmap)
3667 {
3668 	struct bmap *bmp = JFS_SBI(ipbmap->i_sb)->bmap;
3669 	int actags, inactags, l2nl;
3670 	s64 ag_rem, actfree, inactfree, avgfree;
3671 	int i, n;
3672 
3673 	/*
3674 	 *	finalize bmap control page
3675 	 */
3676 //finalize:
3677 	/*
3678 	 * compute db_agpref: preferred ag to allocate from
3679 	 * (the leftmost ag with average free space in it);
3680 	 */
3681 //agpref:
3682 	/* get the number of active ags and inacitve ags */
3683 	actags = bmp->db_maxag + 1;
3684 	inactags = bmp->db_numag - actags;
3685 	ag_rem = bmp->db_mapsize & (bmp->db_agsize - 1);	/* ??? */
3686 
3687 	/* determine how many blocks are in the inactive allocation
3688 	 * groups. in doing this, we must account for the fact that
3689 	 * the rightmost group might be a partial group (i.e. file
3690 	 * system size is not a multiple of the group size).
3691 	 */
3692 	inactfree = (inactags && ag_rem) ?
3693 	    ((inactags - 1) << bmp->db_agl2size) + ag_rem
3694 	    : inactags << bmp->db_agl2size;
3695 
3696 	/* determine how many free blocks are in the active
3697 	 * allocation groups plus the average number of free blocks
3698 	 * within the active ags.
3699 	 */
3700 	actfree = bmp->db_nfree - inactfree;
3701 	avgfree = (u32) actfree / (u32) actags;
3702 
3703 	/* if the preferred allocation group has not average free space.
3704 	 * re-establish the preferred group as the leftmost
3705 	 * group with average free space.
3706 	 */
3707 	if (bmp->db_agfree[bmp->db_agpref] < avgfree) {
3708 		for (bmp->db_agpref = 0; bmp->db_agpref < actags;
3709 		     bmp->db_agpref++) {
3710 			if (bmp->db_agfree[bmp->db_agpref] >= avgfree)
3711 				break;
3712 		}
3713 		if (bmp->db_agpref >= bmp->db_numag) {
3714 			jfs_error(ipbmap->i_sb,
3715 				  "cannot find ag with average freespace\n");
3716 		}
3717 	}
3718 
3719 	/*
3720 	 * compute db_aglevel, db_agheight, db_width, db_agstart:
3721 	 * an ag is covered in aglevel dmapctl summary tree,
3722 	 * at agheight level height (from leaf) with agwidth number of nodes
3723 	 * each, which starts at agstart index node of the smmary tree node
3724 	 * array;
3725 	 */
3726 	bmp->db_aglevel = BMAPSZTOLEV(bmp->db_agsize);
3727 	l2nl =
3728 	    bmp->db_agl2size - (L2BPERDMAP + bmp->db_aglevel * L2LPERCTL);
3729 	bmp->db_agheight = l2nl >> 1;
3730 	bmp->db_agwidth = 1 << (l2nl - (bmp->db_agheight << 1));
3731 	for (i = 5 - bmp->db_agheight, bmp->db_agstart = 0, n = 1; i > 0;
3732 	     i--) {
3733 		bmp->db_agstart += n;
3734 		n <<= 2;
3735 	}
3736 
3737 }
3738 
3739 
3740 /*
3741  * NAME:	dbInitDmap()/ujfs_idmap_page()
3742  *
3743  * FUNCTION:	initialize working/persistent bitmap of the dmap page
3744  *		for the specified number of blocks:
3745  *
3746  *		at entry, the bitmaps had been initialized as free (ZEROS);
3747  *		The number of blocks will only account for the actually
3748  *		existing blocks. Blocks which don't actually exist in
3749  *		the aggregate will be marked as allocated (ONES);
3750  *
3751  * PARAMETERS:
3752  *	dp	- pointer to page of map
3753  *	nblocks	- number of blocks this page
3754  *
3755  * RETURNS: NONE
3756  */
dbInitDmap(struct dmap * dp,s64 Blkno,int nblocks)3757 static int dbInitDmap(struct dmap * dp, s64 Blkno, int nblocks)
3758 {
3759 	int blkno, w, b, r, nw, nb, i;
3760 
3761 	/* starting block number within the dmap */
3762 	blkno = Blkno & (BPERDMAP - 1);
3763 
3764 	if (blkno == 0) {
3765 		dp->nblocks = dp->nfree = cpu_to_le32(nblocks);
3766 		dp->start = cpu_to_le64(Blkno);
3767 
3768 		if (nblocks == BPERDMAP) {
3769 			memset(&dp->wmap[0], 0, LPERDMAP * 4);
3770 			memset(&dp->pmap[0], 0, LPERDMAP * 4);
3771 			goto initTree;
3772 		}
3773 	} else {
3774 		le32_add_cpu(&dp->nblocks, nblocks);
3775 		le32_add_cpu(&dp->nfree, nblocks);
3776 	}
3777 
3778 	/* word number containing start block number */
3779 	w = blkno >> L2DBWORD;
3780 
3781 	/*
3782 	 * free the bits corresponding to the block range (ZEROS):
3783 	 * note: not all bits of the first and last words may be contained
3784 	 * within the block range.
3785 	 */
3786 	for (r = nblocks; r > 0; r -= nb, blkno += nb) {
3787 		/* number of bits preceding range to be freed in the word */
3788 		b = blkno & (DBWORD - 1);
3789 		/* number of bits to free in the word */
3790 		nb = min(r, DBWORD - b);
3791 
3792 		/* is partial word to be freed ? */
3793 		if (nb < DBWORD) {
3794 			/* free (set to 0) from the bitmap word */
3795 			dp->wmap[w] &= cpu_to_le32(~(ONES << (DBWORD - nb)
3796 						     >> b));
3797 			dp->pmap[w] &= cpu_to_le32(~(ONES << (DBWORD - nb)
3798 						     >> b));
3799 
3800 			/* skip the word freed */
3801 			w++;
3802 		} else {
3803 			/* free (set to 0) contiguous bitmap words */
3804 			nw = r >> L2DBWORD;
3805 			memset(&dp->wmap[w], 0, nw * 4);
3806 			memset(&dp->pmap[w], 0, nw * 4);
3807 
3808 			/* skip the words freed */
3809 			nb = nw << L2DBWORD;
3810 			w += nw;
3811 		}
3812 	}
3813 
3814 	/*
3815 	 * mark bits following the range to be freed (non-existing
3816 	 * blocks) as allocated (ONES)
3817 	 */
3818 
3819 	if (blkno == BPERDMAP)
3820 		goto initTree;
3821 
3822 	/* the first word beyond the end of existing blocks */
3823 	w = blkno >> L2DBWORD;
3824 
3825 	/* does nblocks fall on a 32-bit boundary ? */
3826 	b = blkno & (DBWORD - 1);
3827 	if (b) {
3828 		/* mark a partial word allocated */
3829 		dp->wmap[w] = dp->pmap[w] = cpu_to_le32(ONES >> b);
3830 		w++;
3831 	}
3832 
3833 	/* set the rest of the words in the page to allocated (ONES) */
3834 	for (i = w; i < LPERDMAP; i++)
3835 		dp->pmap[i] = dp->wmap[i] = cpu_to_le32(ONES);
3836 
3837 	/*
3838 	 * init tree
3839 	 */
3840       initTree:
3841 	return (dbInitDmapTree(dp));
3842 }
3843 
3844 
3845 /*
3846  * NAME:	dbInitDmapTree()/ujfs_complete_dmap()
3847  *
3848  * FUNCTION:	initialize summary tree of the specified dmap:
3849  *
3850  *		at entry, bitmap of the dmap has been initialized;
3851  *
3852  * PARAMETERS:
3853  *	dp	- dmap to complete
3854  *	blkno	- starting block number for this dmap
3855  *	treemax	- will be filled in with max free for this dmap
3856  *
3857  * RETURNS:	max free string at the root of the tree
3858  */
dbInitDmapTree(struct dmap * dp)3859 static int dbInitDmapTree(struct dmap * dp)
3860 {
3861 	struct dmaptree *tp;
3862 	s8 *cp;
3863 	int i;
3864 
3865 	/* init fixed info of tree */
3866 	tp = &dp->tree;
3867 	tp->nleafs = cpu_to_le32(LPERDMAP);
3868 	tp->l2nleafs = cpu_to_le32(L2LPERDMAP);
3869 	tp->leafidx = cpu_to_le32(LEAFIND);
3870 	tp->height = cpu_to_le32(4);
3871 	tp->budmin = BUDMIN;
3872 
3873 	/* init each leaf from corresponding wmap word:
3874 	 * note: leaf is set to NOFREE(-1) if all blocks of corresponding
3875 	 * bitmap word are allocated.
3876 	 */
3877 	cp = tp->stree + le32_to_cpu(tp->leafidx);
3878 	for (i = 0; i < LPERDMAP; i++)
3879 		*cp++ = dbMaxBud((u8 *) & dp->wmap[i]);
3880 
3881 	/* build the dmap's binary buddy summary tree */
3882 	return (dbInitTree(tp));
3883 }
3884 
3885 
3886 /*
3887  * NAME:	dbInitTree()/ujfs_adjtree()
3888  *
3889  * FUNCTION:	initialize binary buddy summary tree of a dmap or dmapctl.
3890  *
3891  *		at entry, the leaves of the tree has been initialized
3892  *		from corresponding bitmap word or root of summary tree
3893  *		of the child control page;
3894  *		configure binary buddy system at the leaf level, then
3895  *		bubble up the values of the leaf nodes up the tree.
3896  *
3897  * PARAMETERS:
3898  *	cp	- Pointer to the root of the tree
3899  *	l2leaves- Number of leaf nodes as a power of 2
3900  *	l2min	- Number of blocks that can be covered by a leaf
3901  *		  as a power of 2
3902  *
3903  * RETURNS: max free string at the root of the tree
3904  */
dbInitTree(struct dmaptree * dtp)3905 static int dbInitTree(struct dmaptree * dtp)
3906 {
3907 	int l2max, l2free, bsize, nextb, i;
3908 	int child, parent, nparent;
3909 	s8 *tp, *cp, *cp1;
3910 
3911 	tp = dtp->stree;
3912 
3913 	/* Determine the maximum free string possible for the leaves */
3914 	l2max = le32_to_cpu(dtp->l2nleafs) + dtp->budmin;
3915 
3916 	/*
3917 	 * configure the leaf levevl into binary buddy system
3918 	 *
3919 	 * Try to combine buddies starting with a buddy size of 1
3920 	 * (i.e. two leaves). At a buddy size of 1 two buddy leaves
3921 	 * can be combined if both buddies have a maximum free of l2min;
3922 	 * the combination will result in the left-most buddy leaf having
3923 	 * a maximum free of l2min+1.
3924 	 * After processing all buddies for a given size, process buddies
3925 	 * at the next higher buddy size (i.e. current size * 2) and
3926 	 * the next maximum free (current free + 1).
3927 	 * This continues until the maximum possible buddy combination
3928 	 * yields maximum free.
3929 	 */
3930 	for (l2free = dtp->budmin, bsize = 1; l2free < l2max;
3931 	     l2free++, bsize = nextb) {
3932 		/* get next buddy size == current buddy pair size */
3933 		nextb = bsize << 1;
3934 
3935 		/* scan each adjacent buddy pair at current buddy size */
3936 		for (i = 0, cp = tp + le32_to_cpu(dtp->leafidx);
3937 		     i < le32_to_cpu(dtp->nleafs);
3938 		     i += nextb, cp += nextb) {
3939 			/* coalesce if both adjacent buddies are max free */
3940 			if (*cp == l2free && *(cp + bsize) == l2free) {
3941 				*cp = l2free + 1;	/* left take right */
3942 				*(cp + bsize) = -1;	/* right give left */
3943 			}
3944 		}
3945 	}
3946 
3947 	/*
3948 	 * bubble summary information of leaves up the tree.
3949 	 *
3950 	 * Starting at the leaf node level, the four nodes described by
3951 	 * the higher level parent node are compared for a maximum free and
3952 	 * this maximum becomes the value of the parent node.
3953 	 * when all lower level nodes are processed in this fashion then
3954 	 * move up to the next level (parent becomes a lower level node) and
3955 	 * continue the process for that level.
3956 	 */
3957 	for (child = le32_to_cpu(dtp->leafidx),
3958 	     nparent = le32_to_cpu(dtp->nleafs) >> 2;
3959 	     nparent > 0; nparent >>= 2, child = parent) {
3960 		/* get index of 1st node of parent level */
3961 		parent = (child - 1) >> 2;
3962 
3963 		/* set the value of the parent node as the maximum
3964 		 * of the four nodes of the current level.
3965 		 */
3966 		for (i = 0, cp = tp + child, cp1 = tp + parent;
3967 		     i < nparent; i++, cp += 4, cp1++)
3968 			*cp1 = TREEMAX(cp);
3969 	}
3970 
3971 	return (*tp);
3972 }
3973 
3974 
3975 /*
3976  *	dbInitDmapCtl()
3977  *
3978  * function: initialize dmapctl page
3979  */
dbInitDmapCtl(struct dmapctl * dcp,int level,int i)3980 static int dbInitDmapCtl(struct dmapctl * dcp, int level, int i)
3981 {				/* start leaf index not covered by range */
3982 	s8 *cp;
3983 
3984 	dcp->nleafs = cpu_to_le32(LPERCTL);
3985 	dcp->l2nleafs = cpu_to_le32(L2LPERCTL);
3986 	dcp->leafidx = cpu_to_le32(CTLLEAFIND);
3987 	dcp->height = cpu_to_le32(5);
3988 	dcp->budmin = L2BPERDMAP + L2LPERCTL * level;
3989 
3990 	/*
3991 	 * initialize the leaves of current level that were not covered
3992 	 * by the specified input block range (i.e. the leaves have no
3993 	 * low level dmapctl or dmap).
3994 	 */
3995 	cp = &dcp->stree[CTLLEAFIND + i];
3996 	for (; i < LPERCTL; i++)
3997 		*cp++ = NOFREE;
3998 
3999 	/* build the dmap's binary buddy summary tree */
4000 	return (dbInitTree((struct dmaptree *) dcp));
4001 }
4002 
4003 
4004 /*
4005  * NAME:	dbGetL2AGSize()/ujfs_getagl2size()
4006  *
4007  * FUNCTION:	Determine log2(allocation group size) from aggregate size
4008  *
4009  * PARAMETERS:
4010  *	nblocks	- Number of blocks in aggregate
4011  *
4012  * RETURNS: log2(allocation group size) in aggregate blocks
4013  */
dbGetL2AGSize(s64 nblocks)4014 static int dbGetL2AGSize(s64 nblocks)
4015 {
4016 	s64 sz;
4017 	s64 m;
4018 	int l2sz;
4019 
4020 	if (nblocks < BPERDMAP * MAXAG)
4021 		return (L2BPERDMAP);
4022 
4023 	/* round up aggregate size to power of 2 */
4024 	m = ((u64) 1 << (64 - 1));
4025 	for (l2sz = 64; l2sz >= 0; l2sz--, m >>= 1) {
4026 		if (m & nblocks)
4027 			break;
4028 	}
4029 
4030 	sz = (s64) 1 << l2sz;
4031 	if (sz < nblocks)
4032 		l2sz += 1;
4033 
4034 	/* agsize = roundupSize/max_number_of_ag */
4035 	return (l2sz - L2MAXAG);
4036 }
4037 
4038 
4039 /*
4040  * NAME:	dbMapFileSizeToMapSize()
4041  *
4042  * FUNCTION:	compute number of blocks the block allocation map file
4043  *		can cover from the map file size;
4044  *
4045  * RETURNS:	Number of blocks which can be covered by this block map file;
4046  */
4047 
4048 /*
4049  * maximum number of map pages at each level including control pages
4050  */
4051 #define MAXL0PAGES	(1 + LPERCTL)
4052 #define MAXL1PAGES	(1 + LPERCTL * MAXL0PAGES)
4053 
4054 /*
4055  * convert number of map pages to the zero origin top dmapctl level
4056  */
4057 #define BMAPPGTOLEV(npages)	\
4058 	(((npages) <= 3 + MAXL0PAGES) ? 0 : \
4059 	 ((npages) <= 2 + MAXL1PAGES) ? 1 : 2)
4060 
dbMapFileSizeToMapSize(struct inode * ipbmap)4061 s64 dbMapFileSizeToMapSize(struct inode * ipbmap)
4062 {
4063 	struct super_block *sb = ipbmap->i_sb;
4064 	s64 nblocks;
4065 	s64 npages, ndmaps;
4066 	int level, i;
4067 	int complete, factor;
4068 
4069 	nblocks = ipbmap->i_size >> JFS_SBI(sb)->l2bsize;
4070 	npages = nblocks >> JFS_SBI(sb)->l2nbperpage;
4071 	level = BMAPPGTOLEV(npages);
4072 
4073 	/* At each level, accumulate the number of dmap pages covered by
4074 	 * the number of full child levels below it;
4075 	 * repeat for the last incomplete child level.
4076 	 */
4077 	ndmaps = 0;
4078 	npages--;		/* skip the first global control page */
4079 	/* skip higher level control pages above top level covered by map */
4080 	npages -= (2 - level);
4081 	npages--;		/* skip top level's control page */
4082 	for (i = level; i >= 0; i--) {
4083 		factor =
4084 		    (i == 2) ? MAXL1PAGES : ((i == 1) ? MAXL0PAGES : 1);
4085 		complete = (u32) npages / factor;
4086 		ndmaps += complete * ((i == 2) ? LPERCTL * LPERCTL :
4087 				      ((i == 1) ? LPERCTL : 1));
4088 
4089 		/* pages in last/incomplete child */
4090 		npages = (u32) npages % factor;
4091 		/* skip incomplete child's level control page */
4092 		npages--;
4093 	}
4094 
4095 	/* convert the number of dmaps into the number of blocks
4096 	 * which can be covered by the dmaps;
4097 	 */
4098 	nblocks = ndmaps << L2BPERDMAP;
4099 
4100 	return (nblocks);
4101 }
4102