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