]> git.karo-electronics.de Git - karo-tx-linux.git/blob - fs/ntfs/lcnalloc.c
8e60c47fafacd1c5ba96e5e262857fa53c5f35cf
[karo-tx-linux.git] / fs / ntfs / lcnalloc.c
1 /*
2  * lcnalloc.c - Cluster (de)allocation code.  Part of the Linux-NTFS project.
3  *
4  * Copyright (c) 2004-2005 Anton Altaparmakov
5  *
6  * This program/include file is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as published
8  * by the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program/include file is distributed in the hope that it will be
12  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program (in the main directory of the Linux-NTFS
18  * distribution in the file COPYING); if not, write to the Free Software
19  * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #ifdef NTFS_RW
23
24 #include <linux/pagemap.h>
25
26 #include "lcnalloc.h"
27 #include "debug.h"
28 #include "bitmap.h"
29 #include "inode.h"
30 #include "volume.h"
31 #include "attrib.h"
32 #include "malloc.h"
33 #include "aops.h"
34 #include "ntfs.h"
35
36 /**
37  * ntfs_cluster_free_from_rl_nolock - free clusters from runlist
38  * @vol:        mounted ntfs volume on which to free the clusters
39  * @rl:         runlist describing the clusters to free
40  *
41  * Free all the clusters described by the runlist @rl on the volume @vol.  In
42  * the case of an error being returned, at least some of the clusters were not
43  * freed.
44  *
45  * Return 0 on success and -errno on error.
46  *
47  * Locking: - The volume lcn bitmap must be locked for writing on entry and is
48  *            left locked on return.
49  */
50 int ntfs_cluster_free_from_rl_nolock(ntfs_volume *vol,
51                 const runlist_element *rl)
52 {
53         struct inode *lcnbmp_vi = vol->lcnbmp_ino;
54         int ret = 0;
55
56         ntfs_debug("Entering.");
57         if (!rl)
58                 return 0;
59         for (; rl->length; rl++) {
60                 int err;
61
62                 if (rl->lcn < 0)
63                         continue;
64                 err = ntfs_bitmap_clear_run(lcnbmp_vi, rl->lcn, rl->length);
65                 if (unlikely(err && (!ret || ret == -ENOMEM) && ret != err))
66                         ret = err;
67         }
68         ntfs_debug("Done.");
69         return ret;
70 }
71
72 /**
73  * ntfs_cluster_alloc - allocate clusters on an ntfs volume
74  * @vol:        mounted ntfs volume on which to allocate the clusters
75  * @start_vcn:  vcn to use for the first allocated cluster
76  * @count:      number of clusters to allocate
77  * @start_lcn:  starting lcn at which to allocate the clusters (or -1 if none)
78  * @zone:       zone from which to allocate the clusters
79  *
80  * Allocate @count clusters preferably starting at cluster @start_lcn or at the
81  * current allocator position if @start_lcn is -1, on the mounted ntfs volume
82  * @vol. @zone is either DATA_ZONE for allocation of normal clusters or
83  * MFT_ZONE for allocation of clusters for the master file table, i.e. the
84  * $MFT/$DATA attribute.
85  *
86  * @start_vcn specifies the vcn of the first allocated cluster.  This makes
87  * merging the resulting runlist with the old runlist easier.
88  *
89  * You need to check the return value with IS_ERR().  If this is false, the
90  * function was successful and the return value is a runlist describing the
91  * allocated cluster(s).  If IS_ERR() is true, the function failed and
92  * PTR_ERR() gives you the error code.
93  *
94  * Notes on the allocation algorithm
95  * =================================
96  *
97  * There are two data zones.  First is the area between the end of the mft zone
98  * and the end of the volume, and second is the area between the start of the
99  * volume and the start of the mft zone.  On unmodified/standard NTFS 1.x
100  * volumes, the second data zone does not exist due to the mft zone being
101  * expanded to cover the start of the volume in order to reserve space for the
102  * mft bitmap attribute.
103  *
104  * This is not the prettiest function but the complexity stems from the need of
105  * implementing the mft vs data zoned approach and from the fact that we have
106  * access to the lcn bitmap in portions of up to 8192 bytes at a time, so we
107  * need to cope with crossing over boundaries of two buffers.  Further, the
108  * fact that the allocator allows for caller supplied hints as to the location
109  * of where allocation should begin and the fact that the allocator keeps track
110  * of where in the data zones the next natural allocation should occur,
111  * contribute to the complexity of the function.  But it should all be
112  * worthwhile, because this allocator should: 1) be a full implementation of
113  * the MFT zone approach used by Windows NT, 2) cause reduction in
114  * fragmentation, and 3) be speedy in allocations (the code is not optimized
115  * for speed, but the algorithm is, so further speed improvements are probably
116  * possible).
117  *
118  * FIXME: We should be monitoring cluster allocation and increment the MFT zone
119  * size dynamically but this is something for the future.  We will just cause
120  * heavier fragmentation by not doing it and I am not even sure Windows would
121  * grow the MFT zone dynamically, so it might even be correct not to do this.
122  * The overhead in doing dynamic MFT zone expansion would be very large and
123  * unlikely worth the effort. (AIA)
124  *
125  * TODO: I have added in double the required zone position pointer wrap around
126  * logic which can be optimized to having only one of the two logic sets.
127  * However, having the double logic will work fine, but if we have only one of
128  * the sets and we get it wrong somewhere, then we get into trouble, so
129  * removing the duplicate logic requires _very_ careful consideration of _all_
130  * possible code paths.  So at least for now, I am leaving the double logic -
131  * better safe than sorry... (AIA)
132  *
133  * Locking: - The volume lcn bitmap must be unlocked on entry and is unlocked
134  *            on return.
135  *          - This function takes the volume lcn bitmap lock for writing and
136  *            modifies the bitmap contents.
137  */
138 runlist_element *ntfs_cluster_alloc(ntfs_volume *vol, const VCN start_vcn,
139                 const s64 count, const LCN start_lcn,
140                 const NTFS_CLUSTER_ALLOCATION_ZONES zone)
141 {
142         LCN zone_start, zone_end, bmp_pos, bmp_initial_pos, last_read_pos, lcn;
143         LCN prev_lcn = 0, prev_run_len = 0, mft_zone_size;
144         s64 clusters;
145         loff_t i_size;
146         struct inode *lcnbmp_vi;
147         runlist_element *rl = NULL;
148         struct address_space *mapping;
149         struct page *page = NULL;
150         u8 *buf, *byte;
151         int err = 0, rlpos, rlsize, buf_size;
152         u8 pass, done_zones, search_zone, need_writeback = 0, bit;
153
154         ntfs_debug("Entering for start_vcn 0x%llx, count 0x%llx, start_lcn "
155                         "0x%llx, zone %s_ZONE.", (unsigned long long)start_vcn,
156                         (unsigned long long)count,
157                         (unsigned long long)start_lcn,
158                         zone == MFT_ZONE ? "MFT" : "DATA");
159         BUG_ON(!vol);
160         lcnbmp_vi = vol->lcnbmp_ino;
161         BUG_ON(!lcnbmp_vi);
162         BUG_ON(start_vcn < 0);
163         BUG_ON(count < 0);
164         BUG_ON(start_lcn < -1);
165         BUG_ON(zone < FIRST_ZONE);
166         BUG_ON(zone > LAST_ZONE);
167
168         /* Return NULL if @count is zero. */
169         if (!count)
170                 return NULL;
171         /* Take the lcnbmp lock for writing. */
172         down_write(&vol->lcnbmp_lock);
173         /*
174          * If no specific @start_lcn was requested, use the current data zone
175          * position, otherwise use the requested @start_lcn but make sure it
176          * lies outside the mft zone.  Also set done_zones to 0 (no zones done)
177          * and pass depending on whether we are starting inside a zone (1) or
178          * at the beginning of a zone (2).  If requesting from the MFT_ZONE,
179          * we either start at the current position within the mft zone or at
180          * the specified position.  If the latter is out of bounds then we start
181          * at the beginning of the MFT_ZONE.
182          */
183         done_zones = 0;
184         pass = 1;
185         /*
186          * zone_start and zone_end are the current search range.  search_zone
187          * is 1 for mft zone, 2 for data zone 1 (end of mft zone till end of
188          * volume) and 4 for data zone 2 (start of volume till start of mft
189          * zone).
190          */
191         zone_start = start_lcn;
192         if (zone_start < 0) {
193                 if (zone == DATA_ZONE)
194                         zone_start = vol->data1_zone_pos;
195                 else
196                         zone_start = vol->mft_zone_pos;
197                 if (!zone_start) {
198                         /*
199                          * Zone starts at beginning of volume which means a
200                          * single pass is sufficient.
201                          */
202                         pass = 2;
203                 }
204         } else if (zone == DATA_ZONE && zone_start >= vol->mft_zone_start &&
205                         zone_start < vol->mft_zone_end) {
206                 zone_start = vol->mft_zone_end;
207                 /*
208                  * Starting at beginning of data1_zone which means a single
209                  * pass in this zone is sufficient.
210                  */
211                 pass = 2;
212         } else if (zone == MFT_ZONE && (zone_start < vol->mft_zone_start ||
213                         zone_start >= vol->mft_zone_end)) {
214                 zone_start = vol->mft_lcn;
215                 if (!vol->mft_zone_end)
216                         zone_start = 0;
217                 /*
218                  * Starting at beginning of volume which means a single pass
219                  * is sufficient.
220                  */
221                 pass = 2;
222         }
223         if (zone == MFT_ZONE) {
224                 zone_end = vol->mft_zone_end;
225                 search_zone = 1;
226         } else /* if (zone == DATA_ZONE) */ {
227                 /* Skip searching the mft zone. */
228                 done_zones |= 1;
229                 if (zone_start >= vol->mft_zone_end) {
230                         zone_end = vol->nr_clusters;
231                         search_zone = 2;
232                 } else {
233                         zone_end = vol->mft_zone_start;
234                         search_zone = 4;
235                 }
236         }
237         /*
238          * bmp_pos is the current bit position inside the bitmap.  We use
239          * bmp_initial_pos to determine whether or not to do a zone switch.
240          */
241         bmp_pos = bmp_initial_pos = zone_start;
242
243         /* Loop until all clusters are allocated, i.e. clusters == 0. */
244         clusters = count;
245         rlpos = rlsize = 0;
246         mapping = lcnbmp_vi->i_mapping;
247         i_size = i_size_read(lcnbmp_vi);
248         while (1) {
249                 ntfs_debug("Start of outer while loop: done_zones 0x%x, "
250                                 "search_zone %i, pass %i, zone_start 0x%llx, "
251                                 "zone_end 0x%llx, bmp_initial_pos 0x%llx, "
252                                 "bmp_pos 0x%llx, rlpos %i, rlsize %i.",
253                                 done_zones, search_zone, pass,
254                                 (unsigned long long)zone_start,
255                                 (unsigned long long)zone_end,
256                                 (unsigned long long)bmp_initial_pos,
257                                 (unsigned long long)bmp_pos, rlpos, rlsize);
258                 /* Loop until we run out of free clusters. */
259                 last_read_pos = bmp_pos >> 3;
260                 ntfs_debug("last_read_pos 0x%llx.",
261                                 (unsigned long long)last_read_pos);
262                 if (last_read_pos > i_size) {
263                         ntfs_debug("End of attribute reached.  "
264                                         "Skipping to zone_pass_done.");
265                         goto zone_pass_done;
266                 }
267                 if (likely(page)) {
268                         if (need_writeback) {
269                                 ntfs_debug("Marking page dirty.");
270                                 flush_dcache_page(page);
271                                 set_page_dirty(page);
272                                 need_writeback = 0;
273                         }
274                         ntfs_unmap_page(page);
275                 }
276                 page = ntfs_map_page(mapping, last_read_pos >>
277                                 PAGE_CACHE_SHIFT);
278                 if (IS_ERR(page)) {
279                         err = PTR_ERR(page);
280                         ntfs_error(vol->sb, "Failed to map page.");
281                         goto out;
282                 }
283                 buf_size = last_read_pos & ~PAGE_CACHE_MASK;
284                 buf = page_address(page) + buf_size;
285                 buf_size = PAGE_CACHE_SIZE - buf_size;
286                 if (unlikely(last_read_pos + buf_size > i_size))
287                         buf_size = i_size - last_read_pos;
288                 buf_size <<= 3;
289                 lcn = bmp_pos & 7;
290                 bmp_pos &= ~(LCN)7;
291                 ntfs_debug("Before inner while loop: buf_size %i, lcn 0x%llx, "
292                                 "bmp_pos 0x%llx, need_writeback %i.", buf_size,
293                                 (unsigned long long)lcn,
294                                 (unsigned long long)bmp_pos, need_writeback);
295                 while (lcn < buf_size && lcn + bmp_pos < zone_end) {
296                         byte = buf + (lcn >> 3);
297                         ntfs_debug("In inner while loop: buf_size %i, "
298                                         "lcn 0x%llx, bmp_pos 0x%llx, "
299                                         "need_writeback %i, byte ofs 0x%x, "
300                                         "*byte 0x%x.", buf_size,
301                                         (unsigned long long)lcn,
302                                         (unsigned long long)bmp_pos,
303                                         need_writeback,
304                                         (unsigned int)(lcn >> 3),
305                                         (unsigned int)*byte);
306                         /* Skip full bytes. */
307                         if (*byte == 0xff) {
308                                 lcn = (lcn + 8) & ~(LCN)7;
309                                 ntfs_debug("Continuing while loop 1.");
310                                 continue;
311                         }
312                         bit = 1 << (lcn & 7);
313                         ntfs_debug("bit %i.", bit);
314                         /* If the bit is already set, go onto the next one. */
315                         if (*byte & bit) {
316                                 lcn++;
317                                 ntfs_debug("Continuing while loop 2.");
318                                 continue;
319                         }
320                         /*
321                          * Allocate more memory if needed, including space for
322                          * the terminator element.
323                          * ntfs_malloc_nofs() operates on whole pages only.
324                          */
325                         if ((rlpos + 2) * sizeof(*rl) > rlsize) {
326                                 runlist_element *rl2;
327
328                                 ntfs_debug("Reallocating memory.");
329                                 if (!rl)
330                                         ntfs_debug("First free bit is at LCN "
331                                                         "0x%llx.",
332                                                         (unsigned long long)
333                                                         (lcn + bmp_pos));
334                                 rl2 = ntfs_malloc_nofs(rlsize + (int)PAGE_SIZE);
335                                 if (unlikely(!rl2)) {
336                                         err = -ENOMEM;
337                                         ntfs_error(vol->sb, "Failed to "
338                                                         "allocate memory.");
339                                         goto out;
340                                 }
341                                 memcpy(rl2, rl, rlsize);
342                                 ntfs_free(rl);
343                                 rl = rl2;
344                                 rlsize += PAGE_SIZE;
345                                 ntfs_debug("Reallocated memory, rlsize 0x%x.",
346                                                 rlsize);
347                         }
348                         /* Allocate the bitmap bit. */
349                         *byte |= bit;
350                         /* We need to write this bitmap page to disk. */
351                         need_writeback = 1;
352                         ntfs_debug("*byte 0x%x, need_writeback is set.",
353                                         (unsigned int)*byte);
354                         /*
355                          * Coalesce with previous run if adjacent LCNs.
356                          * Otherwise, append a new run.
357                          */
358                         ntfs_debug("Adding run (lcn 0x%llx, len 0x%llx), "
359                                         "prev_lcn 0x%llx, lcn 0x%llx, "
360                                         "bmp_pos 0x%llx, prev_run_len 0x%llx, "
361                                         "rlpos %i.",
362                                         (unsigned long long)(lcn + bmp_pos),
363                                         1ULL, (unsigned long long)prev_lcn,
364                                         (unsigned long long)lcn,
365                                         (unsigned long long)bmp_pos,
366                                         (unsigned long long)prev_run_len,
367                                         rlpos);
368                         if (prev_lcn == lcn + bmp_pos - prev_run_len && rlpos) {
369                                 ntfs_debug("Coalescing to run (lcn 0x%llx, "
370                                                 "len 0x%llx).",
371                                                 (unsigned long long)
372                                                 rl[rlpos - 1].lcn,
373                                                 (unsigned long long)
374                                                 rl[rlpos - 1].length);
375                                 rl[rlpos - 1].length = ++prev_run_len;
376                                 ntfs_debug("Run now (lcn 0x%llx, len 0x%llx), "
377                                                 "prev_run_len 0x%llx.",
378                                                 (unsigned long long)
379                                                 rl[rlpos - 1].lcn,
380                                                 (unsigned long long)
381                                                 rl[rlpos - 1].length,
382                                                 (unsigned long long)
383                                                 prev_run_len);
384                         } else {
385                                 if (likely(rlpos)) {
386                                         ntfs_debug("Adding new run, (previous "
387                                                         "run lcn 0x%llx, "
388                                                         "len 0x%llx).",
389                                                         (unsigned long long)
390                                                         rl[rlpos - 1].lcn,
391                                                         (unsigned long long)
392                                                         rl[rlpos - 1].length);
393                                         rl[rlpos].vcn = rl[rlpos - 1].vcn +
394                                                         prev_run_len;
395                                 } else {
396                                         ntfs_debug("Adding new run, is first "
397                                                         "run.");
398                                         rl[rlpos].vcn = start_vcn;
399                                 }
400                                 rl[rlpos].lcn = prev_lcn = lcn + bmp_pos;
401                                 rl[rlpos].length = prev_run_len = 1;
402                                 rlpos++;
403                         }
404                         /* Done? */
405                         if (!--clusters) {
406                                 LCN tc;
407                                 /*
408                                  * Update the current zone position.  Positions
409                                  * of already scanned zones have been updated
410                                  * during the respective zone switches.
411                                  */
412                                 tc = lcn + bmp_pos + 1;
413                                 ntfs_debug("Done. Updating current zone "
414                                                 "position, tc 0x%llx, "
415                                                 "search_zone %i.",
416                                                 (unsigned long long)tc,
417                                                 search_zone);
418                                 switch (search_zone) {
419                                 case 1:
420                                         ntfs_debug("Before checks, "
421                                                         "vol->mft_zone_pos "
422                                                         "0x%llx.",
423                                                         (unsigned long long)
424                                                         vol->mft_zone_pos);
425                                         if (tc >= vol->mft_zone_end) {
426                                                 vol->mft_zone_pos =
427                                                                 vol->mft_lcn;
428                                                 if (!vol->mft_zone_end)
429                                                         vol->mft_zone_pos = 0;
430                                         } else if ((bmp_initial_pos >=
431                                                         vol->mft_zone_pos ||
432                                                         tc > vol->mft_zone_pos)
433                                                         && tc >= vol->mft_lcn)
434                                                 vol->mft_zone_pos = tc;
435                                         ntfs_debug("After checks, "
436                                                         "vol->mft_zone_pos "
437                                                         "0x%llx.",
438                                                         (unsigned long long)
439                                                         vol->mft_zone_pos);
440                                         break;
441                                 case 2:
442                                         ntfs_debug("Before checks, "
443                                                         "vol->data1_zone_pos "
444                                                         "0x%llx.",
445                                                         (unsigned long long)
446                                                         vol->data1_zone_pos);
447                                         if (tc >= vol->nr_clusters)
448                                                 vol->data1_zone_pos =
449                                                              vol->mft_zone_end;
450                                         else if ((bmp_initial_pos >=
451                                                     vol->data1_zone_pos ||
452                                                     tc > vol->data1_zone_pos)
453                                                     && tc >= vol->mft_zone_end)
454                                                 vol->data1_zone_pos = tc;
455                                         ntfs_debug("After checks, "
456                                                         "vol->data1_zone_pos "
457                                                         "0x%llx.",
458                                                         (unsigned long long)
459                                                         vol->data1_zone_pos);
460                                         break;
461                                 case 4:
462                                         ntfs_debug("Before checks, "
463                                                         "vol->data2_zone_pos "
464                                                         "0x%llx.",
465                                                         (unsigned long long)
466                                                         vol->data2_zone_pos);
467                                         if (tc >= vol->mft_zone_start)
468                                                 vol->data2_zone_pos = 0;
469                                         else if (bmp_initial_pos >=
470                                                       vol->data2_zone_pos ||
471                                                       tc > vol->data2_zone_pos)
472                                                 vol->data2_zone_pos = tc;
473                                         ntfs_debug("After checks, "
474                                                         "vol->data2_zone_pos "
475                                                         "0x%llx.",
476                                                         (unsigned long long)
477                                                         vol->data2_zone_pos);
478                                         break;
479                                 default:
480                                         BUG();
481                                 }
482                                 ntfs_debug("Finished.  Going to out.");
483                                 goto out;
484                         }
485                         lcn++;
486                 }
487                 bmp_pos += buf_size;
488                 ntfs_debug("After inner while loop: buf_size 0x%x, lcn "
489                                 "0x%llx, bmp_pos 0x%llx, need_writeback %i.",
490                                 buf_size, (unsigned long long)lcn,
491                                 (unsigned long long)bmp_pos, need_writeback);
492                 if (bmp_pos < zone_end) {
493                         ntfs_debug("Continuing outer while loop, "
494                                         "bmp_pos 0x%llx, zone_end 0x%llx.",
495                                         (unsigned long long)bmp_pos,
496                                         (unsigned long long)zone_end);
497                         continue;
498                 }
499 zone_pass_done: /* Finished with the current zone pass. */
500                 ntfs_debug("At zone_pass_done, pass %i.", pass);
501                 if (pass == 1) {
502                         /*
503                          * Now do pass 2, scanning the first part of the zone
504                          * we omitted in pass 1.
505                          */
506                         pass = 2;
507                         zone_end = zone_start;
508                         switch (search_zone) {
509                         case 1: /* mft_zone */
510                                 zone_start = vol->mft_zone_start;
511                                 break;
512                         case 2: /* data1_zone */
513                                 zone_start = vol->mft_zone_end;
514                                 break;
515                         case 4: /* data2_zone */
516                                 zone_start = 0;
517                                 break;
518                         default:
519                                 BUG();
520                         }
521                         /* Sanity check. */
522                         if (zone_end < zone_start)
523                                 zone_end = zone_start;
524                         bmp_pos = zone_start;
525                         ntfs_debug("Continuing outer while loop, pass 2, "
526                                         "zone_start 0x%llx, zone_end 0x%llx, "
527                                         "bmp_pos 0x%llx.",
528                                         (unsigned long long)zone_start,
529                                         (unsigned long long)zone_end,
530                                         (unsigned long long)bmp_pos);
531                         continue;
532                 } /* pass == 2 */
533 done_zones_check:
534                 ntfs_debug("At done_zones_check, search_zone %i, done_zones "
535                                 "before 0x%x, done_zones after 0x%x.",
536                                 search_zone, done_zones,
537                                 done_zones | search_zone);
538                 done_zones |= search_zone;
539                 if (done_zones < 7) {
540                         ntfs_debug("Switching zone.");
541                         /* Now switch to the next zone we haven't done yet. */
542                         pass = 1;
543                         switch (search_zone) {
544                         case 1:
545                                 ntfs_debug("Switching from mft zone to data1 "
546                                                 "zone.");
547                                 /* Update mft zone position. */
548                                 if (rlpos) {
549                                         LCN tc;
550
551                                         ntfs_debug("Before checks, "
552                                                         "vol->mft_zone_pos "
553                                                         "0x%llx.",
554                                                         (unsigned long long)
555                                                         vol->mft_zone_pos);
556                                         tc = rl[rlpos - 1].lcn +
557                                                         rl[rlpos - 1].length;
558                                         if (tc >= vol->mft_zone_end) {
559                                                 vol->mft_zone_pos =
560                                                                 vol->mft_lcn;
561                                                 if (!vol->mft_zone_end)
562                                                         vol->mft_zone_pos = 0;
563                                         } else if ((bmp_initial_pos >=
564                                                         vol->mft_zone_pos ||
565                                                         tc > vol->mft_zone_pos)
566                                                         && tc >= vol->mft_lcn)
567                                                 vol->mft_zone_pos = tc;
568                                         ntfs_debug("After checks, "
569                                                         "vol->mft_zone_pos "
570                                                         "0x%llx.",
571                                                         (unsigned long long)
572                                                         vol->mft_zone_pos);
573                                 }
574                                 /* Switch from mft zone to data1 zone. */
575 switch_to_data1_zone:           search_zone = 2;
576                                 zone_start = bmp_initial_pos =
577                                                 vol->data1_zone_pos;
578                                 zone_end = vol->nr_clusters;
579                                 if (zone_start == vol->mft_zone_end)
580                                         pass = 2;
581                                 if (zone_start >= zone_end) {
582                                         vol->data1_zone_pos = zone_start =
583                                                         vol->mft_zone_end;
584                                         pass = 2;
585                                 }
586                                 break;
587                         case 2:
588                                 ntfs_debug("Switching from data1 zone to "
589                                                 "data2 zone.");
590                                 /* Update data1 zone position. */
591                                 if (rlpos) {
592                                         LCN tc;
593
594                                         ntfs_debug("Before checks, "
595                                                         "vol->data1_zone_pos "
596                                                         "0x%llx.",
597                                                         (unsigned long long)
598                                                         vol->data1_zone_pos);
599                                         tc = rl[rlpos - 1].lcn +
600                                                         rl[rlpos - 1].length;
601                                         if (tc >= vol->nr_clusters)
602                                                 vol->data1_zone_pos =
603                                                              vol->mft_zone_end;
604                                         else if ((bmp_initial_pos >=
605                                                     vol->data1_zone_pos ||
606                                                     tc > vol->data1_zone_pos)
607                                                     && tc >= vol->mft_zone_end)
608                                                 vol->data1_zone_pos = tc;
609                                         ntfs_debug("After checks, "
610                                                         "vol->data1_zone_pos "
611                                                         "0x%llx.",
612                                                         (unsigned long long)
613                                                         vol->data1_zone_pos);
614                                 }
615                                 /* Switch from data1 zone to data2 zone. */
616                                 search_zone = 4;
617                                 zone_start = bmp_initial_pos =
618                                                 vol->data2_zone_pos;
619                                 zone_end = vol->mft_zone_start;
620                                 if (!zone_start)
621                                         pass = 2;
622                                 if (zone_start >= zone_end) {
623                                         vol->data2_zone_pos = zone_start =
624                                                         bmp_initial_pos = 0;
625                                         pass = 2;
626                                 }
627                                 break;
628                         case 4:
629                                 ntfs_debug("Switching from data2 zone to "
630                                                 "data1 zone.");
631                                 /* Update data2 zone position. */
632                                 if (rlpos) {
633                                         LCN tc;
634
635                                         ntfs_debug("Before checks, "
636                                                         "vol->data2_zone_pos "
637                                                         "0x%llx.",
638                                                         (unsigned long long)
639                                                         vol->data2_zone_pos);
640                                         tc = rl[rlpos - 1].lcn +
641                                                         rl[rlpos - 1].length;
642                                         if (tc >= vol->mft_zone_start)
643                                                 vol->data2_zone_pos = 0;
644                                         else if (bmp_initial_pos >=
645                                                       vol->data2_zone_pos ||
646                                                       tc > vol->data2_zone_pos)
647                                                 vol->data2_zone_pos = tc;
648                                         ntfs_debug("After checks, "
649                                                         "vol->data2_zone_pos "
650                                                         "0x%llx.",
651                                                         (unsigned long long)
652                                                         vol->data2_zone_pos);
653                                 }
654                                 /* Switch from data2 zone to data1 zone. */
655                                 goto switch_to_data1_zone;
656                         default:
657                                 BUG();
658                         }
659                         ntfs_debug("After zone switch, search_zone %i, "
660                                         "pass %i, bmp_initial_pos 0x%llx, "
661                                         "zone_start 0x%llx, zone_end 0x%llx.",
662                                         search_zone, pass,
663                                         (unsigned long long)bmp_initial_pos,
664                                         (unsigned long long)zone_start,
665                                         (unsigned long long)zone_end);
666                         bmp_pos = zone_start;
667                         if (zone_start == zone_end) {
668                                 ntfs_debug("Empty zone, going to "
669                                                 "done_zones_check.");
670                                 /* Empty zone. Don't bother searching it. */
671                                 goto done_zones_check;
672                         }
673                         ntfs_debug("Continuing outer while loop.");
674                         continue;
675                 } /* done_zones == 7 */
676                 ntfs_debug("All zones are finished.");
677                 /*
678                  * All zones are finished!  If DATA_ZONE, shrink mft zone.  If
679                  * MFT_ZONE, we have really run out of space.
680                  */
681                 mft_zone_size = vol->mft_zone_end - vol->mft_zone_start;
682                 ntfs_debug("vol->mft_zone_start 0x%llx, vol->mft_zone_end "
683                                 "0x%llx, mft_zone_size 0x%llx.",
684                                 (unsigned long long)vol->mft_zone_start,
685                                 (unsigned long long)vol->mft_zone_end,
686                                 (unsigned long long)mft_zone_size);
687                 if (zone == MFT_ZONE || mft_zone_size <= 0) {
688                         ntfs_debug("No free clusters left, going to out.");
689                         /* Really no more space left on device. */
690                         err = -ENOSPC;
691                         goto out;
692                 } /* zone == DATA_ZONE && mft_zone_size > 0 */
693                 ntfs_debug("Shrinking mft zone.");
694                 zone_end = vol->mft_zone_end;
695                 mft_zone_size >>= 1;
696                 if (mft_zone_size > 0)
697                         vol->mft_zone_end = vol->mft_zone_start + mft_zone_size;
698                 else /* mft zone and data2 zone no longer exist. */
699                         vol->data2_zone_pos = vol->mft_zone_start =
700                                         vol->mft_zone_end = 0;
701                 if (vol->mft_zone_pos >= vol->mft_zone_end) {
702                         vol->mft_zone_pos = vol->mft_lcn;
703                         if (!vol->mft_zone_end)
704                                 vol->mft_zone_pos = 0;
705                 }
706                 bmp_pos = zone_start = bmp_initial_pos =
707                                 vol->data1_zone_pos = vol->mft_zone_end;
708                 search_zone = 2;
709                 pass = 2;
710                 done_zones &= ~2;
711                 ntfs_debug("After shrinking mft zone, mft_zone_size 0x%llx, "
712                                 "vol->mft_zone_start 0x%llx, "
713                                 "vol->mft_zone_end 0x%llx, "
714                                 "vol->mft_zone_pos 0x%llx, search_zone 2, "
715                                 "pass 2, dones_zones 0x%x, zone_start 0x%llx, "
716                                 "zone_end 0x%llx, vol->data1_zone_pos 0x%llx, "
717                                 "continuing outer while loop.",
718                                 (unsigned long long)mft_zone_size,
719                                 (unsigned long long)vol->mft_zone_start,
720                                 (unsigned long long)vol->mft_zone_end,
721                                 (unsigned long long)vol->mft_zone_pos,
722                                 done_zones, (unsigned long long)zone_start,
723                                 (unsigned long long)zone_end,
724                                 (unsigned long long)vol->data1_zone_pos);
725         }
726         ntfs_debug("After outer while loop.");
727 out:
728         ntfs_debug("At out.");
729         /* Add runlist terminator element. */
730         if (likely(rl)) {
731                 rl[rlpos].vcn = rl[rlpos - 1].vcn + rl[rlpos - 1].length;
732                 rl[rlpos].lcn = LCN_RL_NOT_MAPPED;
733                 rl[rlpos].length = 0;
734         }
735         if (likely(page && !IS_ERR(page))) {
736                 if (need_writeback) {
737                         ntfs_debug("Marking page dirty.");
738                         flush_dcache_page(page);
739                         set_page_dirty(page);
740                         need_writeback = 0;
741                 }
742                 ntfs_unmap_page(page);
743         }
744         if (likely(!err)) {
745                 up_write(&vol->lcnbmp_lock);
746                 ntfs_debug("Done.");
747                 return rl;
748         }
749         ntfs_error(vol->sb, "Failed to allocate clusters, aborting "
750                         "(error %i).", err);
751         if (rl) {
752                 int err2;
753
754                 if (err == -ENOSPC)
755                         ntfs_debug("Not enough space to complete allocation, "
756                                         "err -ENOSPC, first free lcn 0x%llx, "
757                                         "could allocate up to 0x%llx "
758                                         "clusters.",
759                                         (unsigned long long)rl[0].lcn,
760                                         (unsigned long long)(count - clusters));
761                 /* Deallocate all allocated clusters. */
762                 ntfs_debug("Attempting rollback...");
763                 err2 = ntfs_cluster_free_from_rl_nolock(vol, rl);
764                 if (err2) {
765                         ntfs_error(vol->sb, "Failed to rollback (error %i).  "
766                                         "Leaving inconsistent metadata!  "
767                                         "Unmount and run chkdsk.", err2);
768                         NVolSetErrors(vol);
769                 }
770                 /* Free the runlist. */
771                 ntfs_free(rl);
772         } else if (err == -ENOSPC)
773                 ntfs_debug("No space left at all, err = -ENOSPC, first free "
774                                 "lcn = 0x%llx.",
775                                 (long long)vol->data1_zone_pos);
776         up_write(&vol->lcnbmp_lock);
777         return ERR_PTR(err);
778 }
779
780 /**
781  * __ntfs_cluster_free - free clusters on an ntfs volume
782  * @ni:         ntfs inode whose runlist describes the clusters to free
783  * @start_vcn:  vcn in the runlist of @ni at which to start freeing clusters
784  * @count:      number of clusters to free or -1 for all clusters
785  * @is_rollback:        true if this is a rollback operation
786  *
787  * Free @count clusters starting at the cluster @start_vcn in the runlist
788  * described by the vfs inode @ni.
789  *
790  * If @count is -1, all clusters from @start_vcn to the end of the runlist are
791  * deallocated.  Thus, to completely free all clusters in a runlist, use
792  * @start_vcn = 0 and @count = -1.
793  *
794  * @is_rollback should always be FALSE, it is for internal use to rollback
795  * errors.  You probably want to use ntfs_cluster_free() instead.
796  *
797  * Note, ntfs_cluster_free() does not modify the runlist at all, so the caller
798  * has to deal with it later.
799  *
800  * Return the number of deallocated clusters (not counting sparse ones) on
801  * success and -errno on error.
802  *
803  * Locking: - The runlist described by @ni must be locked for writing on entry
804  *            and is locked on return.  Note the runlist may be modified when
805  *            needed runlist fragments need to be mapped.
806  *          - The volume lcn bitmap must be unlocked on entry and is unlocked
807  *            on return.
808  *          - This function takes the volume lcn bitmap lock for writing and
809  *            modifies the bitmap contents.
810  */
811 s64 __ntfs_cluster_free(ntfs_inode *ni, const VCN start_vcn, s64 count,
812                 const BOOL is_rollback)
813 {
814         s64 delta, to_free, total_freed, real_freed;
815         ntfs_volume *vol;
816         struct inode *lcnbmp_vi;
817         runlist_element *rl;
818         int err;
819
820         BUG_ON(!ni);
821         ntfs_debug("Entering for i_ino 0x%lx, start_vcn 0x%llx, count "
822                         "0x%llx.%s", ni->mft_no, (unsigned long long)start_vcn,
823                         (unsigned long long)count,
824                         is_rollback ? " (rollback)" : "");
825         vol = ni->vol;
826         lcnbmp_vi = vol->lcnbmp_ino;
827         BUG_ON(!lcnbmp_vi);
828         BUG_ON(start_vcn < 0);
829         BUG_ON(count < -1);
830         /*
831          * Lock the lcn bitmap for writing but only if not rolling back.  We
832          * must hold the lock all the way including through rollback otherwise
833          * rollback is not possible because once we have cleared a bit and
834          * dropped the lock, anyone could have set the bit again, thus
835          * allocating the cluster for another use.
836          */
837         if (likely(!is_rollback))
838                 down_write(&vol->lcnbmp_lock);
839
840         total_freed = real_freed = 0;
841
842         rl = ntfs_attr_find_vcn_nolock(ni, start_vcn, NULL);
843         if (IS_ERR(rl)) {
844                 if (!is_rollback)
845                         ntfs_error(vol->sb, "Failed to find first runlist "
846                                         "element (error %li), aborting.",
847                                         PTR_ERR(rl));
848                 err = PTR_ERR(rl);
849                 goto err_out;
850         }
851         if (unlikely(rl->lcn < LCN_HOLE)) {
852                 if (!is_rollback)
853                         ntfs_error(vol->sb, "First runlist element has "
854                                         "invalid lcn, aborting.");
855                 err = -EIO;
856                 goto err_out;
857         }
858         /* Find the starting cluster inside the run that needs freeing. */
859         delta = start_vcn - rl->vcn;
860
861         /* The number of clusters in this run that need freeing. */
862         to_free = rl->length - delta;
863         if (count >= 0 && to_free > count)
864                 to_free = count;
865
866         if (likely(rl->lcn >= 0)) {
867                 /* Do the actual freeing of the clusters in this run. */
868                 err = ntfs_bitmap_set_bits_in_run(lcnbmp_vi, rl->lcn + delta,
869                                 to_free, likely(!is_rollback) ? 0 : 1);
870                 if (unlikely(err)) {
871                         if (!is_rollback)
872                                 ntfs_error(vol->sb, "Failed to clear first run "
873                                                 "(error %i), aborting.", err);
874                         goto err_out;
875                 }
876                 /* We have freed @to_free real clusters. */
877                 real_freed = to_free;
878         };
879         /* Go to the next run and adjust the number of clusters left to free. */
880         ++rl;
881         if (count >= 0)
882                 count -= to_free;
883
884         /* Keep track of the total "freed" clusters, including sparse ones. */
885         total_freed = to_free;
886         /*
887          * Loop over the remaining runs, using @count as a capping value, and
888          * free them.
889          */
890         for (; rl->length && count != 0; ++rl) {
891                 if (unlikely(rl->lcn < LCN_HOLE)) {
892                         VCN vcn;
893
894                         /* Attempt to map runlist. */
895                         vcn = rl->vcn;
896                         rl = ntfs_attr_find_vcn_nolock(ni, vcn, NULL);
897                         if (IS_ERR(rl)) {
898                                 err = PTR_ERR(rl);
899                                 if (!is_rollback)
900                                         ntfs_error(vol->sb, "Failed to map "
901                                                         "runlist fragment or "
902                                                         "failed to find "
903                                                         "subsequent runlist "
904                                                         "element.");
905                                 goto err_out;
906                         }
907                         if (unlikely(rl->lcn < LCN_HOLE)) {
908                                 if (!is_rollback)
909                                         ntfs_error(vol->sb, "Runlist element "
910                                                         "has invalid lcn "
911                                                         "(0x%llx).",
912                                                         (unsigned long long)
913                                                         rl->lcn);
914                                 err = -EIO;
915                                 goto err_out;
916                         }
917                 }
918                 /* The number of clusters in this run that need freeing. */
919                 to_free = rl->length;
920                 if (count >= 0 && to_free > count)
921                         to_free = count;
922
923                 if (likely(rl->lcn >= 0)) {
924                         /* Do the actual freeing of the clusters in the run. */
925                         err = ntfs_bitmap_set_bits_in_run(lcnbmp_vi, rl->lcn,
926                                         to_free, likely(!is_rollback) ? 0 : 1);
927                         if (unlikely(err)) {
928                                 if (!is_rollback)
929                                         ntfs_error(vol->sb, "Failed to clear "
930                                                         "subsequent run.");
931                                 goto err_out;
932                         }
933                         /* We have freed @to_free real clusters. */
934                         real_freed += to_free;
935                 }
936                 /* Adjust the number of clusters left to free. */
937                 if (count >= 0)
938                         count -= to_free;
939         
940                 /* Update the total done clusters. */
941                 total_freed += to_free;
942         }
943         if (likely(!is_rollback))
944                 up_write(&vol->lcnbmp_lock);
945
946         BUG_ON(count > 0);
947
948         /* We are done.  Return the number of actually freed clusters. */
949         ntfs_debug("Done.");
950         return real_freed;
951 err_out:
952         if (is_rollback)
953                 return err;
954         /* If no real clusters were freed, no need to rollback. */
955         if (!real_freed) {
956                 up_write(&vol->lcnbmp_lock);
957                 return err;
958         }
959         /*
960          * Attempt to rollback and if that succeeds just return the error code.
961          * If rollback fails, set the volume errors flag, emit an error
962          * message, and return the error code.
963          */
964         delta = __ntfs_cluster_free(ni, start_vcn, total_freed, TRUE);
965         if (delta < 0) {
966                 ntfs_error(vol->sb, "Failed to rollback (error %i).  Leaving "
967                                 "inconsistent metadata!  Unmount and run "
968                                 "chkdsk.", (int)delta);
969                 NVolSetErrors(vol);
970         }
971         up_write(&vol->lcnbmp_lock);
972         ntfs_error(vol->sb, "Aborting (error %i).", err);
973         return err;
974 }
975
976 #endif /* NTFS_RW */