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