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 */
50int 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
72runlist_element *ntfs_cluster_alloc(ntfs_volume *vol, const VCN start_vcn,
73		const s64 count, const LCN start_lcn,
74		const NTFS_CLUSTER_ALLOCATION_ZONES zone,
75		const bool is_extension)
76{
77	LCN zone_start, zone_end, bmp_pos, bmp_initial_pos, last_read_pos, lcn;
78	LCN prev_lcn = 0, prev_run_len = 0, mft_zone_size;
79	s64 clusters;
80	loff_t i_size;
81	struct inode *lcnbmp_vi;
82	runlist_element *rl = NULL;
83	struct address_space *mapping;
84	struct page *page = NULL;
85	u8 *buf, *byte;
86	int err = 0, rlpos, rlsize, buf_size;
87	u8 pass, done_zones, search_zone, need_writeback = 0, bit;
88
89	ntfs_debug("Entering for start_vcn 0x%llx, count 0x%llx, start_lcn "
90			"0x%llx, zone %s_ZONE.", (unsigned long long)start_vcn,
91			(unsigned long long)count,
92			(unsigned long long)start_lcn,
93			zone == MFT_ZONE ? "MFT" : "DATA");
94	BUG_ON(!vol);
95	lcnbmp_vi = vol->lcnbmp_ino;
96	BUG_ON(!lcnbmp_vi);
97	BUG_ON(start_vcn < 0);
98	BUG_ON(count < 0);
99	BUG_ON(start_lcn < -1);
100	BUG_ON(zone < FIRST_ZONE);
101	BUG_ON(zone > LAST_ZONE);
102
103	/* Return NULL if @count is zero. */
104	if (!count)
105		return NULL;
106	/* Take the lcnbmp lock for writing. */
107	down_write(&vol->lcnbmp_lock);
108	/*
109	 * If no specific @start_lcn was requested, use the current data zone
110	 * position, otherwise use the requested @start_lcn but make sure it
111	 * lies outside the mft zone.  Also set done_zones to 0 (no zones done)
112	 * and pass depending on whether we are starting inside a zone (1) or
113	 * at the beginning of a zone (2).  If requesting from the MFT_ZONE,
114	 * we either start at the current position within the mft zone or at
115	 * the specified position.  If the latter is out of bounds then we start
116	 * at the beginning of the MFT_ZONE.
117	 */
118	done_zones = 0;
119	pass = 1;
120	/*
121	 * zone_start and zone_end are the current search range.  search_zone
122	 * is 1 for mft zone, 2 for data zone 1 (end of mft zone till end of
123	 * volume) and 4 for data zone 2 (start of volume till start of mft
124	 * zone).
125	 */
126	zone_start = start_lcn;
127	if (zone_start < 0) {
128		if (zone == DATA_ZONE)
129			zone_start = vol->data1_zone_pos;
130		else
131			zone_start = vol->mft_zone_pos;
132		if (!zone_start) {
133			/*
134			 * Zone starts at beginning of volume which means a
135			 * single pass is sufficient.
136			 */
137			pass = 2;
138		}
139	} else if (zone == DATA_ZONE && zone_start >= vol->mft_zone_start &&
140			zone_start < vol->mft_zone_end) {
141		zone_start = vol->mft_zone_end;
142		/*
143		 * Starting at beginning of data1_zone which means a single
144		 * pass in this zone is sufficient.
145		 */
146		pass = 2;
147	} else if (zone == MFT_ZONE && (zone_start < vol->mft_zone_start ||
148			zone_start >= vol->mft_zone_end)) {
149		zone_start = vol->mft_lcn;
150		if (!vol->mft_zone_end)
151			zone_start = 0;
152		/*
153		 * Starting at beginning of volume which means a single pass
154		 * is sufficient.
155		 */
156		pass = 2;
157	}
158	if (zone == MFT_ZONE) {
159		zone_end = vol->mft_zone_end;
160		search_zone = 1;
161	} else /* if (zone == DATA_ZONE) */ {
162		/* Skip searching the mft zone. */
163		done_zones |= 1;
164		if (zone_start >= vol->mft_zone_end) {
165			zone_end = vol->nr_clusters;
166			search_zone = 2;
167		} else {
168			zone_end = vol->mft_zone_start;
169			search_zone = 4;
170		}
171	}
172	/*
173	 * bmp_pos is the current bit position inside the bitmap.  We use
174	 * bmp_initial_pos to determine whether or not to do a zone switch.
175	 */
176	bmp_pos = bmp_initial_pos = zone_start;
177
178	/* Loop until all clusters are allocated, i.e. clusters == 0. */
179	clusters = count;
180	rlpos = rlsize = 0;
181	mapping = lcnbmp_vi->i_mapping;
182	i_size = i_size_read(lcnbmp_vi);
183	while (1) {
184		ntfs_debug("Start of outer while loop: done_zones 0x%x, "
185				"search_zone %i, pass %i, zone_start 0x%llx, "
186				"zone_end 0x%llx, bmp_initial_pos 0x%llx, "
187				"bmp_pos 0x%llx, rlpos %i, rlsize %i.",
188				done_zones, search_zone, pass,
189				(unsigned long long)zone_start,
190				(unsigned long long)zone_end,
191				(unsigned long long)bmp_initial_pos,
192				(unsigned long long)bmp_pos, rlpos, rlsize);
193		/* Loop until we run out of free clusters. */
194		last_read_pos = bmp_pos >> 3;
195		ntfs_debug("last_read_pos 0x%llx.",
196				(unsigned long long)last_read_pos);
197		if (last_read_pos > i_size) {
198			ntfs_debug("End of attribute reached.  "
199					"Skipping to zone_pass_done.");
200			goto zone_pass_done;
201		}
202		if (likely(page)) {
203			if (need_writeback) {
204				ntfs_debug("Marking page dirty.");
205				flush_dcache_page(page);
206				set_page_dirty(page);
207				need_writeback = 0;
208			}
209			ntfs_unmap_page(page);
210		}
211		page = ntfs_map_page(mapping, last_read_pos >>
212				PAGE_CACHE_SHIFT);
213		if (IS_ERR(page)) {
214			err = PTR_ERR(page);
215			ntfs_error(vol->sb, "Failed to map page.");
216			goto out;
217		}
218		buf_size = last_read_pos & ~PAGE_CACHE_MASK;
219		buf = page_address(page) + buf_size;
220		buf_size = PAGE_CACHE_SIZE - buf_size;
221		if (unlikely(last_read_pos + buf_size > i_size))
222			buf_size = i_size - last_read_pos;
223		buf_size <<= 3;
224		lcn = bmp_pos & 7;
225		bmp_pos &= ~(LCN)7;
226		ntfs_debug("Before inner while loop: buf_size %i, lcn 0x%llx, "
227				"bmp_pos 0x%llx, need_writeback %i.", buf_size,
228				(unsigned long long)lcn,
229				(unsigned long long)bmp_pos, need_writeback);
230		while (lcn < buf_size && lcn + bmp_pos < zone_end) {
231			byte = buf + (lcn >> 3);
232			ntfs_debug("In inner while loop: buf_size %i, "
233					"lcn 0x%llx, bmp_pos 0x%llx, "
234					"need_writeback %i, byte ofs 0x%x, "
235					"*byte 0x%x.", buf_size,
236					(unsigned long long)lcn,
237					(unsigned long long)bmp_pos,
238					need_writeback,
239					(unsigned int)(lcn >> 3),
240					(unsigned int)*byte);
241			/* Skip full bytes. */
242			if (*byte == 0xff) {
243				lcn = (lcn + 8) & ~(LCN)7;
244				ntfs_debug("Continuing while loop 1.");
245				continue;
246			}
247			bit = 1 << (lcn & 7);
248			ntfs_debug("bit 0x%x.", bit);
249			/* If the bit is already set, go onto the next one. */
250			if (*byte & bit) {
251				lcn++;
252				ntfs_debug("Continuing while loop 2.");
253				continue;
254			}
255			/*
256			 * Allocate more memory if needed, including space for
257			 * the terminator element.
258			 * ntfs_malloc_nofs() operates on whole pages only.
259			 */
260			if ((rlpos + 2) * sizeof(*rl) > rlsize) {
261				runlist_element *rl2;
262
263				ntfs_debug("Reallocating memory.");
264				if (!rl)
265					ntfs_debug("First free bit is at LCN "
266							"0x%llx.",
267							(unsigned long long)
268							(lcn + bmp_pos));
269				rl2 = ntfs_malloc_nofs(rlsize + (int)PAGE_SIZE);
270				if (unlikely(!rl2)) {
271					err = -ENOMEM;
272					ntfs_error(vol->sb, "Failed to "
273							"allocate memory.");
274					goto out;
275				}
276				memcpy(rl2, rl, rlsize);
277				ntfs_free(rl);
278				rl = rl2;
279				rlsize += PAGE_SIZE;
280				ntfs_debug("Reallocated memory, rlsize 0x%x.",
281						rlsize);
282			}
283			/* Allocate the bitmap bit. */
284			*byte |= bit;
285			/* We need to write this bitmap page to disk. */
286			need_writeback = 1;
287			ntfs_debug("*byte 0x%x, need_writeback is set.",
288					(unsigned int)*byte);
289			/*
290			 * Coalesce with previous run if adjacent LCNs.
291			 * Otherwise, append a new run.
292			 */
293			ntfs_debug("Adding run (lcn 0x%llx, len 0x%llx), "
294					"prev_lcn 0x%llx, lcn 0x%llx, "
295					"bmp_pos 0x%llx, prev_run_len 0x%llx, "
296					"rlpos %i.",
297					(unsigned long long)(lcn + bmp_pos),
298					1ULL, (unsigned long long)prev_lcn,
299					(unsigned long long)lcn,
300					(unsigned long long)bmp_pos,
301					(unsigned long long)prev_run_len,
302					rlpos);
303			if (prev_lcn == lcn + bmp_pos - prev_run_len && rlpos) {
304				ntfs_debug("Coalescing to run (lcn 0x%llx, "
305						"len 0x%llx).",
306						(unsigned long long)
307						rl[rlpos - 1].lcn,
308						(unsigned long long)
309						rl[rlpos - 1].length);
310				rl[rlpos - 1].length = ++prev_run_len;
311				ntfs_debug("Run now (lcn 0x%llx, len 0x%llx), "
312						"prev_run_len 0x%llx.",
313						(unsigned long long)
314						rl[rlpos - 1].lcn,
315						(unsigned long long)
316						rl[rlpos - 1].length,
317						(unsigned long long)
318						prev_run_len);
319			} else {
320				if (likely(rlpos)) {
321					ntfs_debug("Adding new run, (previous "
322							"run lcn 0x%llx, "
323							"len 0x%llx).",
324							(unsigned long long)
325							rl[rlpos - 1].lcn,
326							(unsigned long long)
327							rl[rlpos - 1].length);
328					rl[rlpos].vcn = rl[rlpos - 1].vcn +
329							prev_run_len;
330				} else {
331					ntfs_debug("Adding new run, is first "
332							"run.");
333					rl[rlpos].vcn = start_vcn;
334				}
335				rl[rlpos].lcn = prev_lcn = lcn + bmp_pos;
336				rl[rlpos].length = prev_run_len = 1;
337				rlpos++;
338			}
339			/* Done? */
340			if (!--clusters) {
341				LCN tc;
342				/*
343				 * Update the current zone position.  Positions
344				 * of already scanned zones have been updated
345				 * during the respective zone switches.
346				 */
347				tc = lcn + bmp_pos + 1;
348				ntfs_debug("Done. Updating current zone "
349						"position, tc 0x%llx, "
350						"search_zone %i.",
351						(unsigned long long)tc,
352						search_zone);
353				switch (search_zone) {
354				case 1:
355					ntfs_debug("Before checks, "
356							"vol->mft_zone_pos "
357							"0x%llx.",
358							(unsigned long long)
359							vol->mft_zone_pos);
360					if (tc >= vol->mft_zone_end) {
361						vol->mft_zone_pos =
362								vol->mft_lcn;
363						if (!vol->mft_zone_end)
364							vol->mft_zone_pos = 0;
365					} else if ((bmp_initial_pos >=
366							vol->mft_zone_pos ||
367							tc > vol->mft_zone_pos)
368							&& tc >= vol->mft_lcn)
369						vol->mft_zone_pos = tc;
370					ntfs_debug("After checks, "
371							"vol->mft_zone_pos "
372							"0x%llx.",
373							(unsigned long long)
374							vol->mft_zone_pos);
375					break;
376				case 2:
377					ntfs_debug("Before checks, "
378							"vol->data1_zone_pos "
379							"0x%llx.",
380							(unsigned long long)
381							vol->data1_zone_pos);
382					if (tc >= vol->nr_clusters)
383						vol->data1_zone_pos =
384							     vol->mft_zone_end;
385					else if ((bmp_initial_pos >=
386						    vol->data1_zone_pos ||
387						    tc > vol->data1_zone_pos)
388						    && tc >= vol->mft_zone_end)
389						vol->data1_zone_pos = tc;
390					ntfs_debug("After checks, "
391							"vol->data1_zone_pos "
392							"0x%llx.",
393							(unsigned long long)
394							vol->data1_zone_pos);
395					break;
396				case 4:
397					ntfs_debug("Before checks, "
398							"vol->data2_zone_pos "
399							"0x%llx.",
400							(unsigned long long)
401							vol->data2_zone_pos);
402					if (tc >= vol->mft_zone_start)
403						vol->data2_zone_pos = 0;
404					else if (bmp_initial_pos >=
405						      vol->data2_zone_pos ||
406						      tc > vol->data2_zone_pos)
407						vol->data2_zone_pos = tc;
408					ntfs_debug("After checks, "
409							"vol->data2_zone_pos "
410							"0x%llx.",
411							(unsigned long long)
412							vol->data2_zone_pos);
413					break;
414				default:
415					BUG();
416				}
417				ntfs_debug("Finished.  Going to out.");
418				goto out;
419			}
420			lcn++;
421		}
422		bmp_pos += buf_size;
423		ntfs_debug("After inner while loop: buf_size 0x%x, lcn "
424				"0x%llx, bmp_pos 0x%llx, need_writeback %i.",
425				buf_size, (unsigned long long)lcn,
426				(unsigned long long)bmp_pos, need_writeback);
427		if (bmp_pos < zone_end) {
428			ntfs_debug("Continuing outer while loop, "
429					"bmp_pos 0x%llx, zone_end 0x%llx.",
430					(unsigned long long)bmp_pos,
431					(unsigned long long)zone_end);
432			continue;
433		}
434zone_pass_done:	/* Finished with the current zone pass. */
435		ntfs_debug("At zone_pass_done, pass %i.", pass);
436		if (pass == 1) {
437			/*
438			 * Now do pass 2, scanning the first part of the zone
439			 * we omitted in pass 1.
440			 */
441			pass = 2;
442			zone_end = zone_start;
443			switch (search_zone) {
444			case 1: /* mft_zone */
445				zone_start = vol->mft_zone_start;
446				break;
447			case 2: /* data1_zone */
448				zone_start = vol->mft_zone_end;
449				break;
450			case 4: /* data2_zone */
451				zone_start = 0;
452				break;
453			default:
454				BUG();
455			}
456			/* Sanity check. */
457			if (zone_end < zone_start)
458				zone_end = zone_start;
459			bmp_pos = zone_start;
460			ntfs_debug("Continuing outer while loop, pass 2, "
461					"zone_start 0x%llx, zone_end 0x%llx, "
462					"bmp_pos 0x%llx.",
463					(unsigned long long)zone_start,
464					(unsigned long long)zone_end,
465					(unsigned long long)bmp_pos);
466			continue;
467		} /* pass == 2 */
468done_zones_check:
469		ntfs_debug("At done_zones_check, search_zone %i, done_zones "
470				"before 0x%x, done_zones after 0x%x.",
471				search_zone, done_zones,
472				done_zones | search_zone);
473		done_zones |= search_zone;
474		if (done_zones < 7) {
475			ntfs_debug("Switching zone.");
476			/* Now switch to the next zone we haven't done yet. */
477			pass = 1;
478			switch (search_zone) {
479			case 1:
480				ntfs_debug("Switching from mft zone to data1 "
481						"zone.");
482				/* Update mft zone position. */
483				if (rlpos) {
484					LCN tc;
485
486					ntfs_debug("Before checks, "
487							"vol->mft_zone_pos "
488							"0x%llx.",
489							(unsigned long long)
490							vol->mft_zone_pos);
491					tc = rl[rlpos - 1].lcn +
492							rl[rlpos - 1].length;
493					if (tc >= vol->mft_zone_end) {
494						vol->mft_zone_pos =
495								vol->mft_lcn;
496						if (!vol->mft_zone_end)
497							vol->mft_zone_pos = 0;
498					} else if ((bmp_initial_pos >=
499							vol->mft_zone_pos ||
500							tc > vol->mft_zone_pos)
501							&& tc >= vol->mft_lcn)
502						vol->mft_zone_pos = tc;
503					ntfs_debug("After checks, "
504							"vol->mft_zone_pos "
505							"0x%llx.",
506							(unsigned long long)
507							vol->mft_zone_pos);
508				}
509				/* Switch from mft zone to data1 zone. */
510switch_to_data1_zone:		search_zone = 2;
511				zone_start = bmp_initial_pos =
512						vol->data1_zone_pos;
513				zone_end = vol->nr_clusters;
514				if (zone_start == vol->mft_zone_end)
515					pass = 2;
516				if (zone_start >= zone_end) {
517					vol->data1_zone_pos = zone_start =
518							vol->mft_zone_end;
519					pass = 2;
520				}
521				break;
522			case 2:
523				ntfs_debug("Switching from data1 zone to "
524						"data2 zone.");
525				/* Update data1 zone position. */
526				if (rlpos) {
527					LCN tc;
528
529					ntfs_debug("Before checks, "
530							"vol->data1_zone_pos "
531							"0x%llx.",
532							(unsigned long long)
533							vol->data1_zone_pos);
534					tc = rl[rlpos - 1].lcn +
535							rl[rlpos - 1].length;
536					if (tc >= vol->nr_clusters)
537						vol->data1_zone_pos =
538							     vol->mft_zone_end;
539					else if ((bmp_initial_pos >=
540						    vol->data1_zone_pos ||
541						    tc > vol->data1_zone_pos)
542						    && tc >= vol->mft_zone_end)
543						vol->data1_zone_pos = tc;
544					ntfs_debug("After checks, "
545							"vol->data1_zone_pos "
546							"0x%llx.",
547							(unsigned long long)
548							vol->data1_zone_pos);
549				}
550				/* Switch from data1 zone to data2 zone. */
551				search_zone = 4;
552				zone_start = bmp_initial_pos =
553						vol->data2_zone_pos;
554				zone_end = vol->mft_zone_start;
555				if (!zone_start)
556					pass = 2;
557				if (zone_start >= zone_end) {
558					vol->data2_zone_pos = zone_start =
559							bmp_initial_pos = 0;
560					pass = 2;
561				}
562				break;
563			case 4:
564				ntfs_debug("Switching from data2 zone to "
565						"data1 zone.");
566				/* Update data2 zone position. */
567				if (rlpos) {
568					LCN tc;
569
570					ntfs_debug("Before checks, "
571							"vol->data2_zone_pos "
572							"0x%llx.",
573							(unsigned long long)
574							vol->data2_zone_pos);
575					tc = rl[rlpos - 1].lcn +
576							rl[rlpos - 1].length;
577					if (tc >= vol->mft_zone_start)
578						vol->data2_zone_pos = 0;
579					else if (bmp_initial_pos >=
580						      vol->data2_zone_pos ||
581						      tc > vol->data2_zone_pos)
582						vol->data2_zone_pos = tc;
583					ntfs_debug("After checks, "
584							"vol->data2_zone_pos "
585							"0x%llx.",
586							(unsigned long long)
587							vol->data2_zone_pos);
588				}
589				/* Switch from data2 zone to data1 zone. */
590				goto switch_to_data1_zone;
591			default:
592				BUG();
593			}
594			ntfs_debug("After zone switch, search_zone %i, "
595					"pass %i, bmp_initial_pos 0x%llx, "
596					"zone_start 0x%llx, zone_end 0x%llx.",
597					search_zone, pass,
598					(unsigned long long)bmp_initial_pos,
599					(unsigned long long)zone_start,
600					(unsigned long long)zone_end);
601			bmp_pos = zone_start;
602			if (zone_start == zone_end) {
603				ntfs_debug("Empty zone, going to "
604						"done_zones_check.");
605				/* Empty zone. Don't bother searching it. */
606				goto done_zones_check;
607			}
608			ntfs_debug("Continuing outer while loop.");
609			continue;
610		} /* done_zones == 7 */
611		ntfs_debug("All zones are finished.");
612		/*
613		 * All zones are finished!  If DATA_ZONE, shrink mft zone.  If
614		 * MFT_ZONE, we have really run out of space.
615		 */
616		mft_zone_size = vol->mft_zone_end - vol->mft_zone_start;
617		ntfs_debug("vol->mft_zone_start 0x%llx, vol->mft_zone_end "
618				"0x%llx, mft_zone_size 0x%llx.",
619				(unsigned long long)vol->mft_zone_start,
620				(unsigned long long)vol->mft_zone_end,
621				(unsigned long long)mft_zone_size);
622		if (zone == MFT_ZONE || mft_zone_size <= 0) {
623			ntfs_debug("No free clusters left, going to out.");
624			/* Really no more space left on device. */
625			err = -ENOSPC;
626			goto out;
627		} /* zone == DATA_ZONE && mft_zone_size > 0 */
628		ntfs_debug("Shrinking mft zone.");
629		zone_end = vol->mft_zone_end;
630		mft_zone_size >>= 1;
631		if (mft_zone_size > 0)
632			vol->mft_zone_end = vol->mft_zone_start + mft_zone_size;
633		else /* mft zone and data2 zone no longer exist. */
634			vol->data2_zone_pos = vol->mft_zone_start =
635					vol->mft_zone_end = 0;
636		if (vol->mft_zone_pos >= vol->mft_zone_end) {
637			vol->mft_zone_pos = vol->mft_lcn;
638			if (!vol->mft_zone_end)
639				vol->mft_zone_pos = 0;
640		}
641		bmp_pos = zone_start = bmp_initial_pos =
642				vol->data1_zone_pos = vol->mft_zone_end;
643		search_zone = 2;
644		pass = 2;
645		done_zones &= ~2;
646		ntfs_debug("After shrinking mft zone, mft_zone_size 0x%llx, "
647				"vol->mft_zone_start 0x%llx, "
648				"vol->mft_zone_end 0x%llx, "
649				"vol->mft_zone_pos 0x%llx, search_zone 2, "
650				"pass 2, dones_zones 0x%x, zone_start 0x%llx, "
651				"zone_end 0x%llx, vol->data1_zone_pos 0x%llx, "
652				"continuing outer while loop.",
653				(unsigned long long)mft_zone_size,
654				(unsigned long long)vol->mft_zone_start,
655				(unsigned long long)vol->mft_zone_end,
656				(unsigned long long)vol->mft_zone_pos,
657				done_zones, (unsigned long long)zone_start,
658				(unsigned long long)zone_end,
659				(unsigned long long)vol->data1_zone_pos);
660	}
661	ntfs_debug("After outer while loop.");
662out:
663	ntfs_debug("At out.");
664	/* Add runlist terminator element. */
665	if (likely(rl)) {
666		rl[rlpos].vcn = rl[rlpos - 1].vcn + rl[rlpos - 1].length;
667		rl[rlpos].lcn = is_extension ? LCN_ENOENT : LCN_RL_NOT_MAPPED;
668		rl[rlpos].length = 0;
669	}
670	if (likely(page && !IS_ERR(page))) {
671		if (need_writeback) {
672			ntfs_debug("Marking page dirty.");
673			flush_dcache_page(page);
674			set_page_dirty(page);
675			need_writeback = 0;
676		}
677		ntfs_unmap_page(page);
678	}
679	if (likely(!err)) {
680		up_write(&vol->lcnbmp_lock);
681		ntfs_debug("Done.");
682		return rl;
683	}
684	ntfs_error(vol->sb, "Failed to allocate clusters, aborting "
685			"(error %i).", err);
686	if (rl) {
687		int err2;
688
689		if (err == -ENOSPC)
690			ntfs_debug("Not enough space to complete allocation, "
691					"err -ENOSPC, first free lcn 0x%llx, "
692					"could allocate up to 0x%llx "
693					"clusters.",
694					(unsigned long long)rl[0].lcn,
695					(unsigned long long)(count - clusters));
696		/* Deallocate all allocated clusters. */
697		ntfs_debug("Attempting rollback...");
698		err2 = ntfs_cluster_free_from_rl_nolock(vol, rl);
699		if (err2) {
700			ntfs_error(vol->sb, "Failed to rollback (error %i).  "
701					"Leaving inconsistent metadata!  "
702					"Unmount and run chkdsk.", err2);
703			NVolSetErrors(vol);
704		}
705		/* Free the runlist. */
706		ntfs_free(rl);
707	} else if (err == -ENOSPC)
708		ntfs_debug("No space left at all, err = -ENOSPC, first free "
709				"lcn = 0x%llx.",
710				(long long)vol->data1_zone_pos);
711	up_write(&vol->lcnbmp_lock);
712	return ERR_PTR(err);
713}
714
715/**
716 * __ntfs_cluster_free - free clusters on an ntfs volume
717 * @ni:		ntfs inode whose runlist describes the clusters to free
718 * @start_vcn:	vcn in the runlist of @ni at which to start freeing clusters
719 * @count:	number of clusters to free or -1 for all clusters
720 * @ctx:	active attribute search context if present or NULL if not
721 * @is_rollback:	true if this is a rollback operation
722 *
723 * Free @count clusters starting at the cluster @start_vcn in the runlist
724 * described by the vfs inode @ni.
725 *
726 * If @count is -1, all clusters from @start_vcn to the end of the runlist are
727 * deallocated.  Thus, to completely free all clusters in a runlist, use
728 * @start_vcn = 0 and @count = -1.
729 *
730 * If @ctx is specified, it is an active search context of @ni and its base mft
731 * record.  This is needed when __ntfs_cluster_free() encounters unmapped
732 * runlist fragments and allows their mapping.  If you do not have the mft
733 * record mapped, you can specify @ctx as NULL and __ntfs_cluster_free() will
734 * perform the necessary mapping and unmapping.
735 *
736 * Note, __ntfs_cluster_free() saves the state of @ctx on entry and restores it
737 * before returning.  Thus, @ctx will be left pointing to the same attribute on
738 * return as on entry.  However, the actual pointers in @ctx may point to
739 * different memory locations on return, so you must remember to reset any
740 * cached pointers from the @ctx, i.e. after the call to __ntfs_cluster_free(),
741 * you will probably want to do:
742 *	m = ctx->mrec;
743 *	a = ctx->attr;
744 * Assuming you cache ctx->attr in a variable @a of type ATTR_RECORD * and that
745 * you cache ctx->mrec in a variable @m of type MFT_RECORD *.
746 *
747 * @is_rollback should always be 'false', it is for internal use to rollback
748 * errors.  You probably want to use ntfs_cluster_free() instead.
749 *
750 * Note, __ntfs_cluster_free() does not modify the runlist, so you have to
751 * remove from the runlist or mark sparse the freed runs later.
752 *
753 * Return the number of deallocated clusters (not counting sparse ones) on
754 * success and -errno on error.
755 *
756 * WARNING: If @ctx is supplied, regardless of whether success or failure is
757 *	    returned, you need to check IS_ERR(@ctx->mrec) and if 'true' the @ctx
758 *	    is no longer valid, i.e. you need to either call
759 *	    ntfs_attr_reinit_search_ctx() or ntfs_attr_put_search_ctx() on it.
760 *	    In that case PTR_ERR(@ctx->mrec) will give you the error code for
761 *	    why the mapping of the old inode failed.
762 *
763 * Locking: - The runlist described by @ni must be locked for writing on entry
764 *	      and is locked on return.  Note the runlist may be modified when
765 *	      needed runlist fragments need to be mapped.
766 *	    - The volume lcn bitmap must be unlocked on entry and is unlocked
767 *	      on return.
768 *	    - This function takes the volume lcn bitmap lock for writing and
769 *	      modifies the bitmap contents.
770 *	    - If @ctx is NULL, the base mft record of @ni must not be mapped on
771 *	      entry and it will be left unmapped on return.
772 *	    - If @ctx is not NULL, the base mft record must be mapped on entry
773 *	      and it will be left mapped on return.
774 */
775s64 __ntfs_cluster_free(ntfs_inode *ni, const VCN start_vcn, s64 count,
776		ntfs_attr_search_ctx *ctx, const bool is_rollback)
777{
778	s64 delta, to_free, total_freed, real_freed;
779	ntfs_volume *vol;
780	struct inode *lcnbmp_vi;
781	runlist_element *rl;
782	int err;
783
784	BUG_ON(!ni);
785	ntfs_debug("Entering for i_ino 0x%lx, start_vcn 0x%llx, count "
786			"0x%llx.%s", ni->mft_no, (unsigned long long)start_vcn,
787			(unsigned long long)count,
788			is_rollback ? " (rollback)" : "");
789	vol = ni->vol;
790	lcnbmp_vi = vol->lcnbmp_ino;
791	BUG_ON(!lcnbmp_vi);
792	BUG_ON(start_vcn < 0);
793	BUG_ON(count < -1);
794	/*
795	 * Lock the lcn bitmap for writing but only if not rolling back.  We
796	 * must hold the lock all the way including through rollback otherwise
797	 * rollback is not possible because once we have cleared a bit and
798	 * dropped the lock, anyone could have set the bit again, thus
799	 * allocating the cluster for another use.
800	 */
801	if (likely(!is_rollback))
802		down_write(&vol->lcnbmp_lock);
803
804	total_freed = real_freed = 0;
805
806	rl = ntfs_attr_find_vcn_nolock(ni, start_vcn, ctx);
807	if (IS_ERR(rl)) {
808		if (!is_rollback)
809			ntfs_error(vol->sb, "Failed to find first runlist "
810					"element (error %li), aborting.",
811					PTR_ERR(rl));
812		err = PTR_ERR(rl);
813		goto err_out;
814	}
815	if (unlikely(rl->lcn < LCN_HOLE)) {
816		if (!is_rollback)
817			ntfs_error(vol->sb, "First runlist element has "
818					"invalid lcn, aborting.");
819		err = -EIO;
820		goto err_out;
821	}
822	/* Find the starting cluster inside the run that needs freeing. */
823	delta = start_vcn - rl->vcn;
824
825	/* The number of clusters in this run that need freeing. */
826	to_free = rl->length - delta;
827	if (count >= 0 && to_free > count)
828		to_free = count;
829
830	if (likely(rl->lcn >= 0)) {
831		/* Do the actual freeing of the clusters in this run. */
832		err = ntfs_bitmap_set_bits_in_run(lcnbmp_vi, rl->lcn + delta,
833				to_free, likely(!is_rollback) ? 0 : 1);
834		if (unlikely(err)) {
835			if (!is_rollback)
836				ntfs_error(vol->sb, "Failed to clear first run "
837						"(error %i), aborting.", err);
838			goto err_out;
839		}
840		/* We have freed @to_free real clusters. */
841		real_freed = to_free;
842	};
843	/* Go to the next run and adjust the number of clusters left to free. */
844	++rl;
845	if (count >= 0)
846		count -= to_free;
847
848	/* Keep track of the total "freed" clusters, including sparse ones. */
849	total_freed = to_free;
850	/*
851	 * Loop over the remaining runs, using @count as a capping value, and
852	 * free them.
853	 */
854	for (; rl->length && count != 0; ++rl) {
855		if (unlikely(rl->lcn < LCN_HOLE)) {
856			VCN vcn;
857
858			/* Attempt to map runlist. */
859			vcn = rl->vcn;
860			rl = ntfs_attr_find_vcn_nolock(ni, vcn, ctx);
861			if (IS_ERR(rl)) {
862				err = PTR_ERR(rl);
863				if (!is_rollback)
864					ntfs_error(vol->sb, "Failed to map "
865							"runlist fragment or "
866							"failed to find "
867							"subsequent runlist "
868							"element.");
869				goto err_out;
870			}
871			if (unlikely(rl->lcn < LCN_HOLE)) {
872				if (!is_rollback)
873					ntfs_error(vol->sb, "Runlist element "
874							"has invalid lcn "
875							"(0x%llx).",
876							(unsigned long long)
877							rl->lcn);
878				err = -EIO;
879				goto err_out;
880			}
881		}
882		/* The number of clusters in this run that need freeing. */
883		to_free = rl->length;
884		if (count >= 0 && to_free > count)
885			to_free = count;
886
887		if (likely(rl->lcn >= 0)) {
888			/* Do the actual freeing of the clusters in the run. */
889			err = ntfs_bitmap_set_bits_in_run(lcnbmp_vi, rl->lcn,
890					to_free, likely(!is_rollback) ? 0 : 1);
891			if (unlikely(err)) {
892				if (!is_rollback)
893					ntfs_error(vol->sb, "Failed to clear "
894							"subsequent run.");
895				goto err_out;
896			}
897			/* We have freed @to_free real clusters. */
898			real_freed += to_free;
899		}
900		/* Adjust the number of clusters left to free. */
901		if (count >= 0)
902			count -= to_free;
903
904		/* Update the total done clusters. */
905		total_freed += to_free;
906	}
907	if (likely(!is_rollback))
908		up_write(&vol->lcnbmp_lock);
909
910	BUG_ON(count > 0);
911
912	/* We are done.  Return the number of actually freed clusters. */
913	ntfs_debug("Done.");
914	return real_freed;
915err_out:
916	if (is_rollback)
917		return err;
918	/* If no real clusters were freed, no need to rollback. */
919	if (!real_freed) {
920		up_write(&vol->lcnbmp_lock);
921		return err;
922	}
923	/*
924	 * Attempt to rollback and if that succeeds just return the error code.
925	 * If rollback fails, set the volume errors flag, emit an error
926	 * message, and return the error code.
927	 */
928	delta = __ntfs_cluster_free(ni, start_vcn, total_freed, ctx, true);
929	if (delta < 0) {
930		ntfs_error(vol->sb, "Failed to rollback (error %i).  Leaving "
931				"inconsistent metadata!  Unmount and run "
932				"chkdsk.", (int)delta);
933		NVolSetErrors(vol);
934	}
935	up_write(&vol->lcnbmp_lock);
936	ntfs_error(vol->sb, "Aborting (error %i).", err);
937	return err;
938}
939
940#endif /* NTFS_RW */
941