1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * attrib.c - NTFS attribute operations. Part of the Linux-NTFS project.
5 * Copyright (c) 2001-2012 Anton Altaparmakov and Tuxera Inc.
6 * Copyright (c) 2002 Richard Russon
9 #include <linux/buffer_head.h>
10 #include <linux/sched.h>
11 #include <linux/slab.h>
12 #include <linux/swap.h>
13 #include <linux/writeback.h>
25 * ntfs_map_runlist_nolock - map (a part of) a runlist of an ntfs inode
26 * @ni: ntfs inode for which to map (part of) a runlist
27 * @vcn: map runlist part containing this vcn
28 * @ctx: active attribute search context if present or NULL if not
30 * Map the part of a runlist containing the @vcn of the ntfs inode @ni.
32 * If @ctx is specified, it is an active search context of @ni and its base mft
33 * record. This is needed when ntfs_map_runlist_nolock() encounters unmapped
34 * runlist fragments and allows their mapping. If you do not have the mft
35 * record mapped, you can specify @ctx as NULL and ntfs_map_runlist_nolock()
36 * will perform the necessary mapping and unmapping.
38 * Note, ntfs_map_runlist_nolock() saves the state of @ctx on entry and
39 * restores it before returning. Thus, @ctx will be left pointing to the same
40 * attribute on return as on entry. However, the actual pointers in @ctx may
41 * point to different memory locations on return, so you must remember to reset
42 * any cached pointers from the @ctx, i.e. after the call to
43 * ntfs_map_runlist_nolock(), you will probably want to do:
46 * Assuming you cache ctx->attr in a variable @a of type ATTR_RECORD * and that
47 * you cache ctx->mrec in a variable @m of type MFT_RECORD *.
49 * Return 0 on success and -errno on error. There is one special error code
50 * which is not an error as such. This is -ENOENT. It means that @vcn is out
51 * of bounds of the runlist.
53 * Note the runlist can be NULL after this function returns if @vcn is zero and
54 * the attribute has zero allocated size, i.e. there simply is no runlist.
56 * WARNING: If @ctx is supplied, regardless of whether success or failure is
57 * returned, you need to check IS_ERR(@ctx->mrec) and if 'true' the @ctx
58 * is no longer valid, i.e. you need to either call
59 * ntfs_attr_reinit_search_ctx() or ntfs_attr_put_search_ctx() on it.
60 * In that case PTR_ERR(@ctx->mrec) will give you the error code for
61 * why the mapping of the old inode failed.
63 * Locking: - The runlist described by @ni must be locked for writing on entry
64 * and is locked on return. Note the runlist will be modified.
65 * - If @ctx is NULL, the base mft record of @ni must not be mapped on
66 * entry and it will be left unmapped on return.
67 * - If @ctx is not NULL, the base mft record must be mapped on entry
68 * and it will be left mapped on return.
70 int ntfs_map_runlist_nolock(ntfs_inode *ni, VCN vcn, ntfs_attr_search_ctx *ctx)
78 struct page *put_this_page = NULL;
80 bool ctx_is_temporary, ctx_needs_reset;
81 ntfs_attr_search_ctx old_ctx = { NULL, };
83 ntfs_debug("Mapping runlist part containing vcn 0x%llx.",
84 (unsigned long long)vcn);
88 base_ni = ni->ext.base_ntfs_ino;
90 ctx_is_temporary = ctx_needs_reset = true;
91 m = map_mft_record(base_ni);
94 ctx = ntfs_attr_get_search_ctx(base_ni, m);
100 VCN allocated_size_vcn;
102 BUG_ON(IS_ERR(ctx->mrec));
104 BUG_ON(!a->non_resident);
105 ctx_is_temporary = false;
106 end_vcn = sle64_to_cpu(a->data.non_resident.highest_vcn);
107 read_lock_irqsave(&ni->size_lock, flags);
108 allocated_size_vcn = ni->allocated_size >>
109 ni->vol->cluster_size_bits;
110 read_unlock_irqrestore(&ni->size_lock, flags);
111 if (!a->data.non_resident.lowest_vcn && end_vcn <= 0)
112 end_vcn = allocated_size_vcn - 1;
114 * If we already have the attribute extent containing @vcn in
115 * @ctx, no need to look it up again. We slightly cheat in
116 * that if vcn exceeds the allocated size, we will refuse to
117 * map the runlist below, so there is definitely no need to get
118 * the right attribute extent.
120 if (vcn >= allocated_size_vcn || (a->type == ni->type &&
121 a->name_length == ni->name_len &&
122 !memcmp((u8*)a + le16_to_cpu(a->name_offset),
123 ni->name, ni->name_len) &&
124 sle64_to_cpu(a->data.non_resident.lowest_vcn)
125 <= vcn && end_vcn >= vcn))
126 ctx_needs_reset = false;
128 /* Save the old search context. */
131 * If the currently mapped (extent) inode is not the
132 * base inode we will unmap it when we reinitialize the
133 * search context which means we need to get a
134 * reference to the page containing the mapped mft
135 * record so we do not accidentally drop changes to the
136 * mft record when it has not been marked dirty yet.
138 if (old_ctx.base_ntfs_ino && old_ctx.ntfs_ino !=
139 old_ctx.base_ntfs_ino) {
140 put_this_page = old_ctx.ntfs_ino->page;
141 get_page(put_this_page);
144 * Reinitialize the search context so we can lookup the
145 * needed attribute extent.
147 ntfs_attr_reinit_search_ctx(ctx);
148 ctx_needs_reset = true;
151 if (ctx_needs_reset) {
152 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
153 CASE_SENSITIVE, vcn, NULL, 0, ctx);
159 BUG_ON(!ctx->attr->non_resident);
163 * Only decompress the mapping pairs if @vcn is inside it. Otherwise
164 * we get into problems when we try to map an out of bounds vcn because
165 * we then try to map the already mapped runlist fragment and
166 * ntfs_mapping_pairs_decompress() fails.
168 end_vcn = sle64_to_cpu(a->data.non_resident.highest_vcn) + 1;
169 if (unlikely(vcn && vcn >= end_vcn)) {
173 rl = ntfs_mapping_pairs_decompress(ni->vol, a, ni->runlist.rl);
179 if (ctx_is_temporary) {
181 ntfs_attr_put_search_ctx(ctx);
182 unmap_mft_record(base_ni);
183 } else if (ctx_needs_reset) {
185 * If there is no attribute list, restoring the search context
186 * is accomplished simply by copying the saved context back over
187 * the caller supplied context. If there is an attribute list,
188 * things are more complicated as we need to deal with mapping
189 * of mft records and resulting potential changes in pointers.
191 if (NInoAttrList(base_ni)) {
193 * If the currently mapped (extent) inode is not the
194 * one we had before, we need to unmap it and map the
197 if (ctx->ntfs_ino != old_ctx.ntfs_ino) {
199 * If the currently mapped inode is not the
200 * base inode, unmap it.
202 if (ctx->base_ntfs_ino && ctx->ntfs_ino !=
203 ctx->base_ntfs_ino) {
204 unmap_extent_mft_record(ctx->ntfs_ino);
205 ctx->mrec = ctx->base_mrec;
209 * If the old mapped inode is not the base
212 if (old_ctx.base_ntfs_ino &&
214 old_ctx.base_ntfs_ino) {
216 ctx->mrec = map_mft_record(
219 * Something bad has happened. If out
220 * of memory retry till it succeeds.
221 * Any other errors are fatal and we
222 * return the error code in ctx->mrec.
223 * Let the caller deal with it... We
224 * just need to fudge things so the
225 * caller can reinit and/or put the
226 * search context safely.
228 if (IS_ERR(ctx->mrec)) {
229 if (PTR_ERR(ctx->mrec) ==
240 /* Update the changed pointers in the saved context. */
241 if (ctx->mrec != old_ctx.mrec) {
242 if (!IS_ERR(ctx->mrec))
243 old_ctx.attr = (ATTR_RECORD*)(
247 old_ctx.mrec = ctx->mrec;
250 /* Restore the search context to the saved one. */
253 * We drop the reference on the page we took earlier. In the
254 * case that IS_ERR(ctx->mrec) is true this means we might lose
255 * some changes to the mft record that had been made between
256 * the last time it was marked dirty/written out and now. This
257 * at this stage is not a problem as the mapping error is fatal
258 * enough that the mft record cannot be written out anyway and
259 * the caller is very likely to shutdown the whole inode
260 * immediately and mark the volume dirty for chkdsk to pick up
264 put_page(put_this_page);
270 * ntfs_map_runlist - map (a part of) a runlist of an ntfs inode
271 * @ni: ntfs inode for which to map (part of) a runlist
272 * @vcn: map runlist part containing this vcn
274 * Map the part of a runlist containing the @vcn of the ntfs inode @ni.
276 * Return 0 on success and -errno on error. There is one special error code
277 * which is not an error as such. This is -ENOENT. It means that @vcn is out
278 * of bounds of the runlist.
280 * Locking: - The runlist must be unlocked on entry and is unlocked on return.
281 * - This function takes the runlist lock for writing and may modify
284 int ntfs_map_runlist(ntfs_inode *ni, VCN vcn)
288 down_write(&ni->runlist.lock);
289 /* Make sure someone else didn't do the work while we were sleeping. */
290 if (likely(ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn) <=
292 err = ntfs_map_runlist_nolock(ni, vcn, NULL);
293 up_write(&ni->runlist.lock);
298 * ntfs_attr_vcn_to_lcn_nolock - convert a vcn into a lcn given an ntfs inode
299 * @ni: ntfs inode of the attribute whose runlist to search
300 * @vcn: vcn to convert
301 * @write_locked: true if the runlist is locked for writing
303 * Find the virtual cluster number @vcn in the runlist of the ntfs attribute
304 * described by the ntfs inode @ni and return the corresponding logical cluster
307 * If the @vcn is not mapped yet, the attempt is made to map the attribute
308 * extent containing the @vcn and the vcn to lcn conversion is retried.
310 * If @write_locked is true the caller has locked the runlist for writing and
311 * if false for reading.
313 * Since lcns must be >= 0, we use negative return codes with special meaning:
315 * Return code Meaning / Description
316 * ==========================================
317 * LCN_HOLE Hole / not allocated on disk.
318 * LCN_ENOENT There is no such vcn in the runlist, i.e. @vcn is out of bounds.
319 * LCN_ENOMEM Not enough memory to map runlist.
320 * LCN_EIO Critical error (runlist/file is corrupt, i/o error, etc).
322 * Locking: - The runlist must be locked on entry and is left locked on return.
323 * - If @write_locked is 'false', i.e. the runlist is locked for reading,
324 * the lock may be dropped inside the function so you cannot rely on
325 * the runlist still being the same when this function returns.
327 LCN ntfs_attr_vcn_to_lcn_nolock(ntfs_inode *ni, const VCN vcn,
328 const bool write_locked)
332 bool is_retry = false;
335 ntfs_debug("Entering for i_ino 0x%lx, vcn 0x%llx, %s_locked.",
336 ni->mft_no, (unsigned long long)vcn,
337 write_locked ? "write" : "read");
338 BUG_ON(!NInoNonResident(ni));
340 if (!ni->runlist.rl) {
341 read_lock_irqsave(&ni->size_lock, flags);
342 if (!ni->allocated_size) {
343 read_unlock_irqrestore(&ni->size_lock, flags);
346 read_unlock_irqrestore(&ni->size_lock, flags);
349 /* Convert vcn to lcn. If that fails map the runlist and retry once. */
350 lcn = ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn);
351 if (likely(lcn >= LCN_HOLE)) {
352 ntfs_debug("Done, lcn 0x%llx.", (long long)lcn);
355 if (lcn != LCN_RL_NOT_MAPPED) {
356 if (lcn != LCN_ENOENT)
358 } else if (!is_retry) {
362 up_read(&ni->runlist.lock);
363 down_write(&ni->runlist.lock);
364 if (unlikely(ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn) !=
365 LCN_RL_NOT_MAPPED)) {
366 up_write(&ni->runlist.lock);
367 down_read(&ni->runlist.lock);
371 err = ntfs_map_runlist_nolock(ni, vcn, NULL);
373 up_write(&ni->runlist.lock);
374 down_read(&ni->runlist.lock);
382 else if (err == -ENOMEM)
387 if (lcn != LCN_ENOENT)
388 ntfs_error(ni->vol->sb, "Failed with error code %lli.",
394 * ntfs_attr_find_vcn_nolock - find a vcn in the runlist of an ntfs inode
395 * @ni: ntfs inode describing the runlist to search
397 * @ctx: active attribute search context if present or NULL if not
399 * Find the virtual cluster number @vcn in the runlist described by the ntfs
400 * inode @ni and return the address of the runlist element containing the @vcn.
402 * If the @vcn is not mapped yet, the attempt is made to map the attribute
403 * extent containing the @vcn and the vcn to lcn conversion is retried.
405 * If @ctx is specified, it is an active search context of @ni and its base mft
406 * record. This is needed when ntfs_attr_find_vcn_nolock() encounters unmapped
407 * runlist fragments and allows their mapping. If you do not have the mft
408 * record mapped, you can specify @ctx as NULL and ntfs_attr_find_vcn_nolock()
409 * will perform the necessary mapping and unmapping.
411 * Note, ntfs_attr_find_vcn_nolock() saves the state of @ctx on entry and
412 * restores it before returning. Thus, @ctx will be left pointing to the same
413 * attribute on return as on entry. However, the actual pointers in @ctx may
414 * point to different memory locations on return, so you must remember to reset
415 * any cached pointers from the @ctx, i.e. after the call to
416 * ntfs_attr_find_vcn_nolock(), you will probably want to do:
419 * Assuming you cache ctx->attr in a variable @a of type ATTR_RECORD * and that
420 * you cache ctx->mrec in a variable @m of type MFT_RECORD *.
421 * Note you need to distinguish between the lcn of the returned runlist element
422 * being >= 0 and LCN_HOLE. In the later case you have to return zeroes on
423 * read and allocate clusters on write.
425 * Return the runlist element containing the @vcn on success and
426 * ERR_PTR(-errno) on error. You need to test the return value with IS_ERR()
427 * to decide if the return is success or failure and PTR_ERR() to get to the
428 * error code if IS_ERR() is true.
430 * The possible error return codes are:
431 * -ENOENT - No such vcn in the runlist, i.e. @vcn is out of bounds.
432 * -ENOMEM - Not enough memory to map runlist.
433 * -EIO - Critical error (runlist/file is corrupt, i/o error, etc).
435 * WARNING: If @ctx is supplied, regardless of whether success or failure is
436 * returned, you need to check IS_ERR(@ctx->mrec) and if 'true' the @ctx
437 * is no longer valid, i.e. you need to either call
438 * ntfs_attr_reinit_search_ctx() or ntfs_attr_put_search_ctx() on it.
439 * In that case PTR_ERR(@ctx->mrec) will give you the error code for
440 * why the mapping of the old inode failed.
442 * Locking: - The runlist described by @ni must be locked for writing on entry
443 * and is locked on return. Note the runlist may be modified when
444 * needed runlist fragments need to be mapped.
445 * - If @ctx is NULL, the base mft record of @ni must not be mapped on
446 * entry and it will be left unmapped on return.
447 * - If @ctx is not NULL, the base mft record must be mapped on entry
448 * and it will be left mapped on return.
450 runlist_element *ntfs_attr_find_vcn_nolock(ntfs_inode *ni, const VCN vcn,
451 ntfs_attr_search_ctx *ctx)
456 bool is_retry = false;
459 ntfs_debug("Entering for i_ino 0x%lx, vcn 0x%llx, with%s ctx.",
460 ni->mft_no, (unsigned long long)vcn, ctx ? "" : "out");
461 BUG_ON(!NInoNonResident(ni));
463 if (!ni->runlist.rl) {
464 read_lock_irqsave(&ni->size_lock, flags);
465 if (!ni->allocated_size) {
466 read_unlock_irqrestore(&ni->size_lock, flags);
467 return ERR_PTR(-ENOENT);
469 read_unlock_irqrestore(&ni->size_lock, flags);
473 if (likely(rl && vcn >= rl[0].vcn)) {
474 while (likely(rl->length)) {
475 if (unlikely(vcn < rl[1].vcn)) {
476 if (likely(rl->lcn >= LCN_HOLE)) {
484 if (likely(rl->lcn != LCN_RL_NOT_MAPPED)) {
485 if (likely(rl->lcn == LCN_ENOENT))
491 if (!err && !is_retry) {
493 * If the search context is invalid we cannot map the unmapped
496 if (IS_ERR(ctx->mrec))
497 err = PTR_ERR(ctx->mrec);
500 * The @vcn is in an unmapped region, map the runlist
503 err = ntfs_map_runlist_nolock(ni, vcn, ctx);
514 ntfs_error(ni->vol->sb, "Failed with error code %i.", err);
519 * ntfs_attr_find - find (next) attribute in mft record
520 * @type: attribute type to find
521 * @name: attribute name to find (optional, i.e. NULL means don't care)
522 * @name_len: attribute name length (only needed if @name present)
523 * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
524 * @val: attribute value to find (optional, resident attributes only)
525 * @val_len: attribute value length
526 * @ctx: search context with mft record and attribute to search from
528 * You should not need to call this function directly. Use ntfs_attr_lookup()
531 * ntfs_attr_find() takes a search context @ctx as parameter and searches the
532 * mft record specified by @ctx->mrec, beginning at @ctx->attr, for an
533 * attribute of @type, optionally @name and @val.
535 * If the attribute is found, ntfs_attr_find() returns 0 and @ctx->attr will
536 * point to the found attribute.
538 * If the attribute is not found, ntfs_attr_find() returns -ENOENT and
539 * @ctx->attr will point to the attribute before which the attribute being
540 * searched for would need to be inserted if such an action were to be desired.
542 * On actual error, ntfs_attr_find() returns -EIO. In this case @ctx->attr is
543 * undefined and in particular do not rely on it not changing.
545 * If @ctx->is_first is 'true', the search begins with @ctx->attr itself. If it
546 * is 'false', the search begins after @ctx->attr.
548 * If @ic is IGNORE_CASE, the @name comparisson is not case sensitive and
549 * @ctx->ntfs_ino must be set to the ntfs inode to which the mft record
550 * @ctx->mrec belongs. This is so we can get at the ntfs volume and hence at
551 * the upcase table. If @ic is CASE_SENSITIVE, the comparison is case
552 * sensitive. When @name is present, @name_len is the @name length in Unicode
555 * If @name is not present (NULL), we assume that the unnamed attribute is
556 * being searched for.
558 * Finally, the resident attribute value @val is looked for, if present. If
559 * @val is not present (NULL), @val_len is ignored.
561 * ntfs_attr_find() only searches the specified mft record and it ignores the
562 * presence of an attribute list attribute (unless it is the one being searched
563 * for, obviously). If you need to take attribute lists into consideration,
564 * use ntfs_attr_lookup() instead (see below). This also means that you cannot
565 * use ntfs_attr_find() to search for extent records of non-resident
566 * attributes, as extents with lowest_vcn != 0 are usually described by the
567 * attribute list attribute only. - Note that it is possible that the first
568 * extent is only in the attribute list while the last extent is in the base
569 * mft record, so do not rely on being able to find the first extent in the
572 * Warning: Never use @val when looking for attribute types which can be
573 * non-resident as this most likely will result in a crash!
575 static int ntfs_attr_find(const ATTR_TYPE type, const ntfschar *name,
576 const u32 name_len, const IGNORE_CASE_BOOL ic,
577 const u8 *val, const u32 val_len, ntfs_attr_search_ctx *ctx)
580 ntfs_volume *vol = ctx->ntfs_ino->vol;
581 ntfschar *upcase = vol->upcase;
582 u32 upcase_len = vol->upcase_len;
585 * Iterate over attributes in mft record starting at @ctx->attr, or the
586 * attribute following that, if @ctx->is_first is 'true'.
590 ctx->is_first = false;
592 a = (ATTR_RECORD*)((u8*)ctx->attr +
593 le32_to_cpu(ctx->attr->length));
594 for (;; a = (ATTR_RECORD*)((u8*)a + le32_to_cpu(a->length))) {
595 u8 *mrec_end = (u8 *)ctx->mrec +
596 le32_to_cpu(ctx->mrec->bytes_allocated);
597 u8 *name_end = (u8 *)a + le16_to_cpu(a->name_offset) +
598 a->name_length * sizeof(ntfschar);
599 if ((u8*)a < (u8*)ctx->mrec || (u8*)a > mrec_end ||
603 if (unlikely(le32_to_cpu(a->type) > le32_to_cpu(type) ||
606 if (unlikely(!a->length))
611 * If @name is present, compare the two names. If @name is
612 * missing, assume we want an unnamed attribute.
615 /* The search failed if the found attribute is named. */
618 } else if (!ntfs_are_names_equal(name, name_len,
619 (ntfschar*)((u8*)a + le16_to_cpu(a->name_offset)),
620 a->name_length, ic, upcase, upcase_len)) {
623 rc = ntfs_collate_names(name, name_len,
625 le16_to_cpu(a->name_offset)),
626 a->name_length, 1, IGNORE_CASE,
629 * If @name collates before a->name, there is no
630 * matching attribute.
634 /* If the strings are not equal, continue search. */
637 rc = ntfs_collate_names(name, name_len,
639 le16_to_cpu(a->name_offset)),
640 a->name_length, 1, CASE_SENSITIVE,
648 * The names match or @name not present and attribute is
649 * unnamed. If no @val specified, we have found the attribute
654 /* @val is present; compare values. */
658 rc = memcmp(val, (u8*)a + le16_to_cpu(
659 a->data.resident.value_offset),
660 min_t(u32, val_len, le32_to_cpu(
661 a->data.resident.value_length)));
663 * If @val collates before the current attribute's
664 * value, there is no matching attribute.
670 a->data.resident.value_length);
679 ntfs_error(vol->sb, "Inode is corrupt. Run chkdsk.");
685 * load_attribute_list - load an attribute list into memory
686 * @vol: ntfs volume from which to read
687 * @runlist: runlist of the attribute list
688 * @al_start: destination buffer
689 * @size: size of the destination buffer in bytes
690 * @initialized_size: initialized size of the attribute list
692 * Walk the runlist @runlist and load all clusters from it copying them into
693 * the linear buffer @al. The maximum number of bytes copied to @al is @size
694 * bytes. Note, @size does not need to be a multiple of the cluster size. If
695 * @initialized_size is less than @size, the region in @al between
696 * @initialized_size and @size will be zeroed and not read from disk.
698 * Return 0 on success or -errno on error.
700 int load_attribute_list(ntfs_volume *vol, runlist *runlist, u8 *al_start,
701 const s64 size, const s64 initialized_size)
705 u8 *al_end = al + initialized_size;
707 struct buffer_head *bh;
708 struct super_block *sb;
709 unsigned long block_size;
710 unsigned long block, max_block;
712 unsigned char block_size_bits;
714 ntfs_debug("Entering.");
715 if (!vol || !runlist || !al || size <= 0 || initialized_size < 0 ||
716 initialized_size > size)
718 if (!initialized_size) {
723 block_size = sb->s_blocksize;
724 block_size_bits = sb->s_blocksize_bits;
725 down_read(&runlist->lock);
728 ntfs_error(sb, "Cannot read attribute list since runlist is "
732 /* Read all clusters specified by the runlist one run at a time. */
734 lcn = ntfs_rl_vcn_to_lcn(rl, rl->vcn);
735 ntfs_debug("Reading vcn = 0x%llx, lcn = 0x%llx.",
736 (unsigned long long)rl->vcn,
737 (unsigned long long)lcn);
738 /* The attribute list cannot be sparse. */
740 ntfs_error(sb, "ntfs_rl_vcn_to_lcn() failed. Cannot "
741 "read attribute list.");
744 block = lcn << vol->cluster_size_bits >> block_size_bits;
745 /* Read the run from device in chunks of block_size bytes. */
746 max_block = block + (rl->length << vol->cluster_size_bits >>
748 ntfs_debug("max_block = 0x%lx.", max_block);
750 ntfs_debug("Reading block = 0x%lx.", block);
751 bh = sb_bread(sb, block);
753 ntfs_error(sb, "sb_bread() failed. Cannot "
754 "read attribute list.");
757 if (al + block_size >= al_end)
759 memcpy(al, bh->b_data, block_size);
762 } while (++block < max_block);
765 if (initialized_size < size) {
767 memset(al_start + initialized_size, 0, size - initialized_size);
770 up_read(&runlist->lock);
777 * Note: The attribute list can be smaller than its allocation
778 * by multiple clusters. This has been encountered by at least
779 * two people running Windows XP, thus we cannot do any
780 * truncation sanity checking here. (AIA)
782 memcpy(al, bh->b_data, al_end - al);
784 if (initialized_size < size)
790 ntfs_error(sb, "Attribute list buffer overflow. Read attribute list "
798 * ntfs_external_attr_find - find an attribute in the attribute list of an inode
799 * @type: attribute type to find
800 * @name: attribute name to find (optional, i.e. NULL means don't care)
801 * @name_len: attribute name length (only needed if @name present)
802 * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
803 * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only)
804 * @val: attribute value to find (optional, resident attributes only)
805 * @val_len: attribute value length
806 * @ctx: search context with mft record and attribute to search from
808 * You should not need to call this function directly. Use ntfs_attr_lookup()
811 * Find an attribute by searching the attribute list for the corresponding
812 * attribute list entry. Having found the entry, map the mft record if the
813 * attribute is in a different mft record/inode, ntfs_attr_find() the attribute
814 * in there and return it.
816 * On first search @ctx->ntfs_ino must be the base mft record and @ctx must
817 * have been obtained from a call to ntfs_attr_get_search_ctx(). On subsequent
818 * calls @ctx->ntfs_ino can be any extent inode, too (@ctx->base_ntfs_ino is
819 * then the base inode).
821 * After finishing with the attribute/mft record you need to call
822 * ntfs_attr_put_search_ctx() to cleanup the search context (unmapping any
823 * mapped inodes, etc).
825 * If the attribute is found, ntfs_external_attr_find() returns 0 and
826 * @ctx->attr will point to the found attribute. @ctx->mrec will point to the
827 * mft record in which @ctx->attr is located and @ctx->al_entry will point to
828 * the attribute list entry for the attribute.
830 * If the attribute is not found, ntfs_external_attr_find() returns -ENOENT and
831 * @ctx->attr will point to the attribute in the base mft record before which
832 * the attribute being searched for would need to be inserted if such an action
833 * were to be desired. @ctx->mrec will point to the mft record in which
834 * @ctx->attr is located and @ctx->al_entry will point to the attribute list
835 * entry of the attribute before which the attribute being searched for would
836 * need to be inserted if such an action were to be desired.
838 * Thus to insert the not found attribute, one wants to add the attribute to
839 * @ctx->mrec (the base mft record) and if there is not enough space, the
840 * attribute should be placed in a newly allocated extent mft record. The
841 * attribute list entry for the inserted attribute should be inserted in the
842 * attribute list attribute at @ctx->al_entry.
844 * On actual error, ntfs_external_attr_find() returns -EIO. In this case
845 * @ctx->attr is undefined and in particular do not rely on it not changing.
847 static int ntfs_external_attr_find(const ATTR_TYPE type,
848 const ntfschar *name, const u32 name_len,
849 const IGNORE_CASE_BOOL ic, const VCN lowest_vcn,
850 const u8 *val, const u32 val_len, ntfs_attr_search_ctx *ctx)
852 ntfs_inode *base_ni, *ni;
854 ATTR_LIST_ENTRY *al_entry, *next_al_entry;
855 u8 *al_start, *al_end;
860 static const char *es = " Unmount and run chkdsk.";
863 base_ni = ctx->base_ntfs_ino;
864 ntfs_debug("Entering for inode 0x%lx, type 0x%x.", ni->mft_no, type);
866 /* First call happens with the base mft record. */
867 base_ni = ctx->base_ntfs_ino = ctx->ntfs_ino;
868 ctx->base_mrec = ctx->mrec;
871 ctx->base_attr = ctx->attr;
875 al_start = base_ni->attr_list;
876 al_end = al_start + base_ni->attr_list_size;
878 ctx->al_entry = (ATTR_LIST_ENTRY*)al_start;
880 * Iterate over entries in attribute list starting at @ctx->al_entry,
881 * or the entry following that, if @ctx->is_first is 'true'.
884 al_entry = ctx->al_entry;
885 ctx->is_first = false;
887 al_entry = (ATTR_LIST_ENTRY*)((u8*)ctx->al_entry +
888 le16_to_cpu(ctx->al_entry->length));
889 for (;; al_entry = next_al_entry) {
890 /* Out of bounds check. */
891 if ((u8*)al_entry < base_ni->attr_list ||
892 (u8*)al_entry > al_end)
893 break; /* Inode is corrupt. */
894 ctx->al_entry = al_entry;
895 /* Catch the end of the attribute list. */
896 if ((u8*)al_entry == al_end)
898 if (!al_entry->length)
900 if ((u8*)al_entry + 6 > al_end || (u8*)al_entry +
901 le16_to_cpu(al_entry->length) > al_end)
903 next_al_entry = (ATTR_LIST_ENTRY*)((u8*)al_entry +
904 le16_to_cpu(al_entry->length));
905 if (le32_to_cpu(al_entry->type) > le32_to_cpu(type))
907 if (type != al_entry->type)
910 * If @name is present, compare the two names. If @name is
911 * missing, assume we want an unnamed attribute.
913 al_name_len = al_entry->name_length;
914 al_name = (ntfschar*)((u8*)al_entry + al_entry->name_offset);
918 } else if (!ntfs_are_names_equal(al_name, al_name_len, name,
919 name_len, ic, vol->upcase, vol->upcase_len)) {
922 rc = ntfs_collate_names(name, name_len, al_name,
923 al_name_len, 1, IGNORE_CASE,
924 vol->upcase, vol->upcase_len);
926 * If @name collates before al_name, there is no
927 * matching attribute.
931 /* If the strings are not equal, continue search. */
935 * FIXME: Reverse engineering showed 0, IGNORE_CASE but
936 * that is inconsistent with ntfs_attr_find(). The
937 * subsequent rc checks were also different. Perhaps I
938 * made a mistake in one of the two. Need to recheck
939 * which is correct or at least see what is going on...
942 rc = ntfs_collate_names(name, name_len, al_name,
943 al_name_len, 1, CASE_SENSITIVE,
944 vol->upcase, vol->upcase_len);
951 * The names match or @name not present and attribute is
952 * unnamed. Now check @lowest_vcn. Continue search if the
953 * next attribute list entry still fits @lowest_vcn. Otherwise
954 * we have reached the right one or the search has failed.
956 if (lowest_vcn && (u8*)next_al_entry >= al_start &&
957 (u8*)next_al_entry + 6 < al_end &&
958 (u8*)next_al_entry + le16_to_cpu(
959 next_al_entry->length) <= al_end &&
960 sle64_to_cpu(next_al_entry->lowest_vcn) <=
962 next_al_entry->type == al_entry->type &&
963 next_al_entry->name_length == al_name_len &&
964 ntfs_are_names_equal((ntfschar*)((u8*)
966 next_al_entry->name_offset),
967 next_al_entry->name_length,
968 al_name, al_name_len, CASE_SENSITIVE,
969 vol->upcase, vol->upcase_len))
971 if (MREF_LE(al_entry->mft_reference) == ni->mft_no) {
972 if (MSEQNO_LE(al_entry->mft_reference) != ni->seq_no) {
973 ntfs_error(vol->sb, "Found stale mft "
974 "reference in attribute list "
975 "of base inode 0x%lx.%s",
976 base_ni->mft_no, es);
980 } else { /* Mft references do not match. */
981 /* If there is a mapped record unmap it first. */
983 unmap_extent_mft_record(ni);
984 /* Do we want the base record back? */
985 if (MREF_LE(al_entry->mft_reference) ==
987 ni = ctx->ntfs_ino = base_ni;
988 ctx->mrec = ctx->base_mrec;
990 /* We want an extent record. */
991 ctx->mrec = map_extent_mft_record(base_ni,
993 al_entry->mft_reference), &ni);
994 if (IS_ERR(ctx->mrec)) {
995 ntfs_error(vol->sb, "Failed to map "
997 "0x%lx of base inode "
1001 base_ni->mft_no, es);
1002 err = PTR_ERR(ctx->mrec);
1005 /* Cause @ctx to be sanitized below. */
1011 ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec +
1012 le16_to_cpu(ctx->mrec->attrs_offset));
1015 * ctx->vfs_ino, ctx->mrec, and ctx->attr now point to the
1016 * mft record containing the attribute represented by the
1020 * We could call into ntfs_attr_find() to find the right
1021 * attribute in this mft record but this would be less
1022 * efficient and not quite accurate as ntfs_attr_find() ignores
1023 * the attribute instance numbers for example which become
1024 * important when one plays with attribute lists. Also,
1025 * because a proper match has been found in the attribute list
1026 * entry above, the comparison can now be optimized. So it is
1027 * worth re-implementing a simplified ntfs_attr_find() here.
1031 * Use a manual loop so we can still use break and continue
1032 * with the same meanings as above.
1035 if ((u8*)a < (u8*)ctx->mrec || (u8*)a > (u8*)ctx->mrec +
1036 le32_to_cpu(ctx->mrec->bytes_allocated))
1038 if (a->type == AT_END)
1042 if (al_entry->instance != a->instance)
1045 * If the type and/or the name are mismatched between the
1046 * attribute list entry and the attribute record, there is
1047 * corruption so we break and return error EIO.
1049 if (al_entry->type != a->type)
1051 if (!ntfs_are_names_equal((ntfschar*)((u8*)a +
1052 le16_to_cpu(a->name_offset)), a->name_length,
1053 al_name, al_name_len, CASE_SENSITIVE,
1054 vol->upcase, vol->upcase_len))
1058 * If no @val specified or @val specified and it matches, we
1061 if (!val || (!a->non_resident && le32_to_cpu(
1062 a->data.resident.value_length) == val_len &&
1064 le16_to_cpu(a->data.resident.value_offset),
1066 ntfs_debug("Done, found.");
1070 /* Proceed to the next attribute in the current mft record. */
1071 a = (ATTR_RECORD*)((u8*)a + le32_to_cpu(a->length));
1072 goto do_next_attr_loop;
1075 ntfs_error(vol->sb, "Base inode 0x%lx contains corrupt "
1076 "attribute list attribute.%s", base_ni->mft_no,
1080 if (ni != base_ni) {
1082 unmap_extent_mft_record(ni);
1083 ctx->ntfs_ino = base_ni;
1084 ctx->mrec = ctx->base_mrec;
1085 ctx->attr = ctx->base_attr;
1092 * If we were looking for AT_END, we reset the search context @ctx and
1093 * use ntfs_attr_find() to seek to the end of the base mft record.
1095 if (type == AT_END) {
1096 ntfs_attr_reinit_search_ctx(ctx);
1097 return ntfs_attr_find(AT_END, name, name_len, ic, val, val_len,
1101 * The attribute was not found. Before we return, we want to ensure
1102 * @ctx->mrec and @ctx->attr indicate the position at which the
1103 * attribute should be inserted in the base mft record. Since we also
1104 * want to preserve @ctx->al_entry we cannot reinitialize the search
1105 * context using ntfs_attr_reinit_search_ctx() as this would set
1106 * @ctx->al_entry to NULL. Thus we do the necessary bits manually (see
1107 * ntfs_attr_init_search_ctx() below). Note, we _only_ preserve
1108 * @ctx->al_entry as the remaining fields (base_*) are identical to
1109 * their non base_ counterparts and we cannot set @ctx->base_attr
1110 * correctly yet as we do not know what @ctx->attr will be set to by
1111 * the call to ntfs_attr_find() below.
1114 unmap_extent_mft_record(ni);
1115 ctx->mrec = ctx->base_mrec;
1116 ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec +
1117 le16_to_cpu(ctx->mrec->attrs_offset));
1118 ctx->is_first = true;
1119 ctx->ntfs_ino = base_ni;
1120 ctx->base_ntfs_ino = NULL;
1121 ctx->base_mrec = NULL;
1122 ctx->base_attr = NULL;
1124 * In case there are multiple matches in the base mft record, need to
1125 * keep enumerating until we get an attribute not found response (or
1126 * another error), otherwise we would keep returning the same attribute
1127 * over and over again and all programs using us for enumeration would
1128 * lock up in a tight loop.
1131 err = ntfs_attr_find(type, name, name_len, ic, val, val_len,
1134 ntfs_debug("Done, not found.");
1139 * ntfs_attr_lookup - find an attribute in an ntfs inode
1140 * @type: attribute type to find
1141 * @name: attribute name to find (optional, i.e. NULL means don't care)
1142 * @name_len: attribute name length (only needed if @name present)
1143 * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
1144 * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only)
1145 * @val: attribute value to find (optional, resident attributes only)
1146 * @val_len: attribute value length
1147 * @ctx: search context with mft record and attribute to search from
1149 * Find an attribute in an ntfs inode. On first search @ctx->ntfs_ino must
1150 * be the base mft record and @ctx must have been obtained from a call to
1151 * ntfs_attr_get_search_ctx().
1153 * This function transparently handles attribute lists and @ctx is used to
1154 * continue searches where they were left off at.
1156 * After finishing with the attribute/mft record you need to call
1157 * ntfs_attr_put_search_ctx() to cleanup the search context (unmapping any
1158 * mapped inodes, etc).
1160 * Return 0 if the search was successful and -errno if not.
1162 * When 0, @ctx->attr is the found attribute and it is in mft record
1163 * @ctx->mrec. If an attribute list attribute is present, @ctx->al_entry is
1164 * the attribute list entry of the found attribute.
1166 * When -ENOENT, @ctx->attr is the attribute which collates just after the
1167 * attribute being searched for, i.e. if one wants to add the attribute to the
1168 * mft record this is the correct place to insert it into. If an attribute
1169 * list attribute is present, @ctx->al_entry is the attribute list entry which
1170 * collates just after the attribute list entry of the attribute being searched
1171 * for, i.e. if one wants to add the attribute to the mft record this is the
1172 * correct place to insert its attribute list entry into.
1174 * When -errno != -ENOENT, an error occurred during the lookup. @ctx->attr is
1175 * then undefined and in particular you should not rely on it not changing.
1177 int ntfs_attr_lookup(const ATTR_TYPE type, const ntfschar *name,
1178 const u32 name_len, const IGNORE_CASE_BOOL ic,
1179 const VCN lowest_vcn, const u8 *val, const u32 val_len,
1180 ntfs_attr_search_ctx *ctx)
1182 ntfs_inode *base_ni;
1184 ntfs_debug("Entering.");
1185 BUG_ON(IS_ERR(ctx->mrec));
1186 if (ctx->base_ntfs_ino)
1187 base_ni = ctx->base_ntfs_ino;
1189 base_ni = ctx->ntfs_ino;
1190 /* Sanity check, just for debugging really. */
1192 if (!NInoAttrList(base_ni) || type == AT_ATTRIBUTE_LIST)
1193 return ntfs_attr_find(type, name, name_len, ic, val, val_len,
1195 return ntfs_external_attr_find(type, name, name_len, ic, lowest_vcn,
1200 * ntfs_attr_init_search_ctx - initialize an attribute search context
1201 * @ctx: attribute search context to initialize
1202 * @ni: ntfs inode with which to initialize the search context
1203 * @mrec: mft record with which to initialize the search context
1205 * Initialize the attribute search context @ctx with @ni and @mrec.
1207 static inline void ntfs_attr_init_search_ctx(ntfs_attr_search_ctx *ctx,
1208 ntfs_inode *ni, MFT_RECORD *mrec)
1210 *ctx = (ntfs_attr_search_ctx) {
1212 /* Sanity checks are performed elsewhere. */
1213 .attr = (ATTR_RECORD*)((u8*)mrec +
1214 le16_to_cpu(mrec->attrs_offset)),
1221 * ntfs_attr_reinit_search_ctx - reinitialize an attribute search context
1222 * @ctx: attribute search context to reinitialize
1224 * Reinitialize the attribute search context @ctx, unmapping an associated
1225 * extent mft record if present, and initialize the search context again.
1227 * This is used when a search for a new attribute is being started to reset
1228 * the search context to the beginning.
1230 void ntfs_attr_reinit_search_ctx(ntfs_attr_search_ctx *ctx)
1232 if (likely(!ctx->base_ntfs_ino)) {
1233 /* No attribute list. */
1234 ctx->is_first = true;
1235 /* Sanity checks are performed elsewhere. */
1236 ctx->attr = (ATTR_RECORD*)((u8*)ctx->mrec +
1237 le16_to_cpu(ctx->mrec->attrs_offset));
1239 * This needs resetting due to ntfs_external_attr_find() which
1240 * can leave it set despite having zeroed ctx->base_ntfs_ino.
1242 ctx->al_entry = NULL;
1244 } /* Attribute list. */
1245 if (ctx->ntfs_ino != ctx->base_ntfs_ino)
1246 unmap_extent_mft_record(ctx->ntfs_ino);
1247 ntfs_attr_init_search_ctx(ctx, ctx->base_ntfs_ino, ctx->base_mrec);
1252 * ntfs_attr_get_search_ctx - allocate/initialize a new attribute search context
1253 * @ni: ntfs inode with which to initialize the search context
1254 * @mrec: mft record with which to initialize the search context
1256 * Allocate a new attribute search context, initialize it with @ni and @mrec,
1257 * and return it. Return NULL if allocation failed.
1259 ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(ntfs_inode *ni, MFT_RECORD *mrec)
1261 ntfs_attr_search_ctx *ctx;
1263 ctx = kmem_cache_alloc(ntfs_attr_ctx_cache, GFP_NOFS);
1265 ntfs_attr_init_search_ctx(ctx, ni, mrec);
1270 * ntfs_attr_put_search_ctx - release an attribute search context
1271 * @ctx: attribute search context to free
1273 * Release the attribute search context @ctx, unmapping an associated extent
1274 * mft record if present.
1276 void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx)
1278 if (ctx->base_ntfs_ino && ctx->ntfs_ino != ctx->base_ntfs_ino)
1279 unmap_extent_mft_record(ctx->ntfs_ino);
1280 kmem_cache_free(ntfs_attr_ctx_cache, ctx);
1287 * ntfs_attr_find_in_attrdef - find an attribute in the $AttrDef system file
1288 * @vol: ntfs volume to which the attribute belongs
1289 * @type: attribute type which to find
1291 * Search for the attribute definition record corresponding to the attribute
1292 * @type in the $AttrDef system file.
1294 * Return the attribute type definition record if found and NULL if not found.
1296 static ATTR_DEF *ntfs_attr_find_in_attrdef(const ntfs_volume *vol,
1297 const ATTR_TYPE type)
1301 BUG_ON(!vol->attrdef);
1303 for (ad = vol->attrdef; (u8*)ad - (u8*)vol->attrdef <
1304 vol->attrdef_size && ad->type; ++ad) {
1305 /* We have not found it yet, carry on searching. */
1306 if (likely(le32_to_cpu(ad->type) < le32_to_cpu(type)))
1308 /* We found the attribute; return it. */
1309 if (likely(ad->type == type))
1311 /* We have gone too far already. No point in continuing. */
1314 /* Attribute not found. */
1315 ntfs_debug("Attribute type 0x%x not found in $AttrDef.",
1321 * ntfs_attr_size_bounds_check - check a size of an attribute type for validity
1322 * @vol: ntfs volume to which the attribute belongs
1323 * @type: attribute type which to check
1324 * @size: size which to check
1326 * Check whether the @size in bytes is valid for an attribute of @type on the
1327 * ntfs volume @vol. This information is obtained from $AttrDef system file.
1329 * Return 0 if valid, -ERANGE if not valid, or -ENOENT if the attribute is not
1330 * listed in $AttrDef.
1332 int ntfs_attr_size_bounds_check(const ntfs_volume *vol, const ATTR_TYPE type,
1339 * $ATTRIBUTE_LIST has a maximum size of 256kiB, but this is not
1340 * listed in $AttrDef.
1342 if (unlikely(type == AT_ATTRIBUTE_LIST && size > 256 * 1024))
1344 /* Get the $AttrDef entry for the attribute @type. */
1345 ad = ntfs_attr_find_in_attrdef(vol, type);
1348 /* Do the bounds check. */
1349 if (((sle64_to_cpu(ad->min_size) > 0) &&
1350 size < sle64_to_cpu(ad->min_size)) ||
1351 ((sle64_to_cpu(ad->max_size) > 0) && size >
1352 sle64_to_cpu(ad->max_size)))
1358 * ntfs_attr_can_be_non_resident - check if an attribute can be non-resident
1359 * @vol: ntfs volume to which the attribute belongs
1360 * @type: attribute type which to check
1362 * Check whether the attribute of @type on the ntfs volume @vol is allowed to
1363 * be non-resident. This information is obtained from $AttrDef system file.
1365 * Return 0 if the attribute is allowed to be non-resident, -EPERM if not, and
1366 * -ENOENT if the attribute is not listed in $AttrDef.
1368 int ntfs_attr_can_be_non_resident(const ntfs_volume *vol, const ATTR_TYPE type)
1372 /* Find the attribute definition record in $AttrDef. */
1373 ad = ntfs_attr_find_in_attrdef(vol, type);
1376 /* Check the flags and return the result. */
1377 if (ad->flags & ATTR_DEF_RESIDENT)
1383 * ntfs_attr_can_be_resident - check if an attribute can be resident
1384 * @vol: ntfs volume to which the attribute belongs
1385 * @type: attribute type which to check
1387 * Check whether the attribute of @type on the ntfs volume @vol is allowed to
1388 * be resident. This information is derived from our ntfs knowledge and may
1389 * not be completely accurate, especially when user defined attributes are
1390 * present. Basically we allow everything to be resident except for index
1391 * allocation and $EA attributes.
1393 * Return 0 if the attribute is allowed to be non-resident and -EPERM if not.
1395 * Warning: In the system file $MFT the attribute $Bitmap must be non-resident
1396 * otherwise windows will not boot (blue screen of death)! We cannot
1397 * check for this here as we do not know which inode's $Bitmap is
1398 * being asked about so the caller needs to special case this.
1400 int ntfs_attr_can_be_resident(const ntfs_volume *vol, const ATTR_TYPE type)
1402 if (type == AT_INDEX_ALLOCATION)
1408 * ntfs_attr_record_resize - resize an attribute record
1409 * @m: mft record containing attribute record
1410 * @a: attribute record to resize
1411 * @new_size: new size in bytes to which to resize the attribute record @a
1413 * Resize the attribute record @a, i.e. the resident part of the attribute, in
1414 * the mft record @m to @new_size bytes.
1416 * Return 0 on success and -errno on error. The following error codes are
1418 * -ENOSPC - Not enough space in the mft record @m to perform the resize.
1420 * Note: On error, no modifications have been performed whatsoever.
1422 * Warning: If you make a record smaller without having copied all the data you
1423 * are interested in the data may be overwritten.
1425 int ntfs_attr_record_resize(MFT_RECORD *m, ATTR_RECORD *a, u32 new_size)
1427 ntfs_debug("Entering for new_size %u.", new_size);
1428 /* Align to 8 bytes if it is not already done. */
1430 new_size = (new_size + 7) & ~7;
1431 /* If the actual attribute length has changed, move things around. */
1432 if (new_size != le32_to_cpu(a->length)) {
1433 u32 new_muse = le32_to_cpu(m->bytes_in_use) -
1434 le32_to_cpu(a->length) + new_size;
1435 /* Not enough space in this mft record. */
1436 if (new_muse > le32_to_cpu(m->bytes_allocated))
1438 /* Move attributes following @a to their new location. */
1439 memmove((u8*)a + new_size, (u8*)a + le32_to_cpu(a->length),
1440 le32_to_cpu(m->bytes_in_use) - ((u8*)a -
1441 (u8*)m) - le32_to_cpu(a->length));
1442 /* Adjust @m to reflect the change in used space. */
1443 m->bytes_in_use = cpu_to_le32(new_muse);
1444 /* Adjust @a to reflect the new size. */
1445 if (new_size >= offsetof(ATTR_REC, length) + sizeof(a->length))
1446 a->length = cpu_to_le32(new_size);
1452 * ntfs_resident_attr_value_resize - resize the value of a resident attribute
1453 * @m: mft record containing attribute record
1454 * @a: attribute record whose value to resize
1455 * @new_size: new size in bytes to which to resize the attribute value of @a
1457 * Resize the value of the attribute @a in the mft record @m to @new_size bytes.
1458 * If the value is made bigger, the newly allocated space is cleared.
1460 * Return 0 on success and -errno on error. The following error codes are
1462 * -ENOSPC - Not enough space in the mft record @m to perform the resize.
1464 * Note: On error, no modifications have been performed whatsoever.
1466 * Warning: If you make a record smaller without having copied all the data you
1467 * are interested in the data may be overwritten.
1469 int ntfs_resident_attr_value_resize(MFT_RECORD *m, ATTR_RECORD *a,
1474 /* Resize the resident part of the attribute record. */
1475 if (ntfs_attr_record_resize(m, a,
1476 le16_to_cpu(a->data.resident.value_offset) + new_size))
1479 * The resize succeeded! If we made the attribute value bigger, clear
1480 * the area between the old size and @new_size.
1482 old_size = le32_to_cpu(a->data.resident.value_length);
1483 if (new_size > old_size)
1484 memset((u8*)a + le16_to_cpu(a->data.resident.value_offset) +
1485 old_size, 0, new_size - old_size);
1486 /* Finally update the length of the attribute value. */
1487 a->data.resident.value_length = cpu_to_le32(new_size);
1492 * ntfs_attr_make_non_resident - convert a resident to a non-resident attribute
1493 * @ni: ntfs inode describing the attribute to convert
1494 * @data_size: size of the resident data to copy to the non-resident attribute
1496 * Convert the resident ntfs attribute described by the ntfs inode @ni to a
1499 * @data_size must be equal to the attribute value size. This is needed since
1500 * we need to know the size before we can map the mft record and our callers
1501 * always know it. The reason we cannot simply read the size from the vfs
1502 * inode i_size is that this is not necessarily uptodate. This happens when
1503 * ntfs_attr_make_non_resident() is called in the ->truncate call path(s).
1505 * Return 0 on success and -errno on error. The following error return codes
1507 * -EPERM - The attribute is not allowed to be non-resident.
1508 * -ENOMEM - Not enough memory.
1509 * -ENOSPC - Not enough disk space.
1510 * -EINVAL - Attribute not defined on the volume.
1511 * -EIO - I/o error or other error.
1512 * Note that -ENOSPC is also returned in the case that there is not enough
1513 * space in the mft record to do the conversion. This can happen when the mft
1514 * record is already very full. The caller is responsible for trying to make
1515 * space in the mft record and trying again. FIXME: Do we need a separate
1516 * error return code for this kind of -ENOSPC or is it always worth trying
1517 * again in case the attribute may then fit in a resident state so no need to
1518 * make it non-resident at all? Ho-hum... (AIA)
1520 * NOTE to self: No changes in the attribute list are required to move from
1521 * a resident to a non-resident attribute.
1523 * Locking: - The caller must hold i_mutex on the inode.
1525 int ntfs_attr_make_non_resident(ntfs_inode *ni, const u32 data_size)
1528 struct inode *vi = VFS_I(ni);
1529 ntfs_volume *vol = ni->vol;
1530 ntfs_inode *base_ni;
1533 ntfs_attr_search_ctx *ctx;
1535 runlist_element *rl;
1537 unsigned long flags;
1538 int mp_size, mp_ofs, name_ofs, arec_size, err, err2;
1540 u8 old_res_attr_flags;
1542 /* Check that the attribute is allowed to be non-resident. */
1543 err = ntfs_attr_can_be_non_resident(vol, ni->type);
1544 if (unlikely(err)) {
1546 ntfs_debug("Attribute is not allowed to be "
1549 ntfs_debug("Attribute not defined on the NTFS "
1554 * FIXME: Compressed and encrypted attributes are not supported when
1555 * writing and we should never have gotten here for them.
1557 BUG_ON(NInoCompressed(ni));
1558 BUG_ON(NInoEncrypted(ni));
1560 * The size needs to be aligned to a cluster boundary for allocation
1563 new_size = (data_size + vol->cluster_size - 1) &
1564 ~(vol->cluster_size - 1);
1567 * Will need the page later and since the page lock nests
1568 * outside all ntfs locks, we need to get the page now.
1570 page = find_or_create_page(vi->i_mapping, 0,
1571 mapping_gfp_mask(vi->i_mapping));
1572 if (unlikely(!page))
1574 /* Start by allocating clusters to hold the attribute value. */
1575 rl = ntfs_cluster_alloc(vol, 0, new_size >>
1576 vol->cluster_size_bits, -1, DATA_ZONE, true);
1579 ntfs_debug("Failed to allocate cluster%s, error code "
1581 vol->cluster_size_bits) > 1 ? "s" : "",
1589 /* Determine the size of the mapping pairs array. */
1590 mp_size = ntfs_get_size_for_mapping_pairs(vol, rl, 0, -1);
1591 if (unlikely(mp_size < 0)) {
1593 ntfs_debug("Failed to get size for mapping pairs array, error "
1597 down_write(&ni->runlist.lock);
1601 base_ni = ni->ext.base_ntfs_ino;
1602 m = map_mft_record(base_ni);
1609 ctx = ntfs_attr_get_search_ctx(base_ni, m);
1610 if (unlikely(!ctx)) {
1614 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1615 CASE_SENSITIVE, 0, NULL, 0, ctx);
1616 if (unlikely(err)) {
1623 BUG_ON(NInoNonResident(ni));
1624 BUG_ON(a->non_resident);
1626 * Calculate new offsets for the name and the mapping pairs array.
1628 if (NInoSparse(ni) || NInoCompressed(ni))
1629 name_ofs = (offsetof(ATTR_REC,
1630 data.non_resident.compressed_size) +
1631 sizeof(a->data.non_resident.compressed_size) +
1634 name_ofs = (offsetof(ATTR_REC,
1635 data.non_resident.compressed_size) + 7) & ~7;
1636 mp_ofs = (name_ofs + a->name_length * sizeof(ntfschar) + 7) & ~7;
1638 * Determine the size of the resident part of the now non-resident
1641 arec_size = (mp_ofs + mp_size + 7) & ~7;
1643 * If the page is not uptodate bring it uptodate by copying from the
1646 attr_size = le32_to_cpu(a->data.resident.value_length);
1647 BUG_ON(attr_size != data_size);
1648 if (page && !PageUptodate(page)) {
1649 kaddr = kmap_atomic(page);
1650 memcpy(kaddr, (u8*)a +
1651 le16_to_cpu(a->data.resident.value_offset),
1653 memset(kaddr + attr_size, 0, PAGE_SIZE - attr_size);
1654 kunmap_atomic(kaddr);
1655 flush_dcache_page(page);
1656 SetPageUptodate(page);
1658 /* Backup the attribute flag. */
1659 old_res_attr_flags = a->data.resident.flags;
1660 /* Resize the resident part of the attribute record. */
1661 err = ntfs_attr_record_resize(m, a, arec_size);
1665 * Convert the resident part of the attribute record to describe a
1666 * non-resident attribute.
1668 a->non_resident = 1;
1669 /* Move the attribute name if it exists and update the offset. */
1671 memmove((u8*)a + name_ofs, (u8*)a + le16_to_cpu(a->name_offset),
1672 a->name_length * sizeof(ntfschar));
1673 a->name_offset = cpu_to_le16(name_ofs);
1674 /* Setup the fields specific to non-resident attributes. */
1675 a->data.non_resident.lowest_vcn = 0;
1676 a->data.non_resident.highest_vcn = cpu_to_sle64((new_size - 1) >>
1677 vol->cluster_size_bits);
1678 a->data.non_resident.mapping_pairs_offset = cpu_to_le16(mp_ofs);
1679 memset(&a->data.non_resident.reserved, 0,
1680 sizeof(a->data.non_resident.reserved));
1681 a->data.non_resident.allocated_size = cpu_to_sle64(new_size);
1682 a->data.non_resident.data_size =
1683 a->data.non_resident.initialized_size =
1684 cpu_to_sle64(attr_size);
1685 if (NInoSparse(ni) || NInoCompressed(ni)) {
1686 a->data.non_resident.compression_unit = 0;
1687 if (NInoCompressed(ni) || vol->major_ver < 3)
1688 a->data.non_resident.compression_unit = 4;
1689 a->data.non_resident.compressed_size =
1690 a->data.non_resident.allocated_size;
1692 a->data.non_resident.compression_unit = 0;
1693 /* Generate the mapping pairs array into the attribute record. */
1694 err = ntfs_mapping_pairs_build(vol, (u8*)a + mp_ofs,
1695 arec_size - mp_ofs, rl, 0, -1, NULL);
1696 if (unlikely(err)) {
1697 ntfs_debug("Failed to build mapping pairs, error code %i.",
1701 /* Setup the in-memory attribute structure to be non-resident. */
1702 ni->runlist.rl = rl;
1703 write_lock_irqsave(&ni->size_lock, flags);
1704 ni->allocated_size = new_size;
1705 if (NInoSparse(ni) || NInoCompressed(ni)) {
1706 ni->itype.compressed.size = ni->allocated_size;
1707 if (a->data.non_resident.compression_unit) {
1708 ni->itype.compressed.block_size = 1U << (a->data.
1709 non_resident.compression_unit +
1710 vol->cluster_size_bits);
1711 ni->itype.compressed.block_size_bits =
1712 ffs(ni->itype.compressed.block_size) -
1714 ni->itype.compressed.block_clusters = 1U <<
1715 a->data.non_resident.compression_unit;
1717 ni->itype.compressed.block_size = 0;
1718 ni->itype.compressed.block_size_bits = 0;
1719 ni->itype.compressed.block_clusters = 0;
1721 vi->i_blocks = ni->itype.compressed.size >> 9;
1723 vi->i_blocks = ni->allocated_size >> 9;
1724 write_unlock_irqrestore(&ni->size_lock, flags);
1726 * This needs to be last since the address space operations ->readpage
1727 * and ->writepage can run concurrently with us as they are not
1728 * serialized on i_mutex. Note, we are not allowed to fail once we flip
1729 * this switch, which is another reason to do this last.
1731 NInoSetNonResident(ni);
1732 /* Mark the mft record dirty, so it gets written back. */
1733 flush_dcache_mft_record_page(ctx->ntfs_ino);
1734 mark_mft_record_dirty(ctx->ntfs_ino);
1735 ntfs_attr_put_search_ctx(ctx);
1736 unmap_mft_record(base_ni);
1737 up_write(&ni->runlist.lock);
1739 set_page_dirty(page);
1743 ntfs_debug("Done.");
1746 /* Convert the attribute back into a resident attribute. */
1747 a->non_resident = 0;
1748 /* Move the attribute name if it exists and update the offset. */
1749 name_ofs = (offsetof(ATTR_RECORD, data.resident.reserved) +
1750 sizeof(a->data.resident.reserved) + 7) & ~7;
1752 memmove((u8*)a + name_ofs, (u8*)a + le16_to_cpu(a->name_offset),
1753 a->name_length * sizeof(ntfschar));
1754 mp_ofs = (name_ofs + a->name_length * sizeof(ntfschar) + 7) & ~7;
1755 a->name_offset = cpu_to_le16(name_ofs);
1756 arec_size = (mp_ofs + attr_size + 7) & ~7;
1757 /* Resize the resident part of the attribute record. */
1758 err2 = ntfs_attr_record_resize(m, a, arec_size);
1759 if (unlikely(err2)) {
1761 * This cannot happen (well if memory corruption is at work it
1762 * could happen in theory), but deal with it as well as we can.
1763 * If the old size is too small, truncate the attribute,
1764 * otherwise simply give it a larger allocated size.
1765 * FIXME: Should check whether chkdsk complains when the
1766 * allocated size is much bigger than the resident value size.
1768 arec_size = le32_to_cpu(a->length);
1769 if ((mp_ofs + attr_size) > arec_size) {
1771 attr_size = arec_size - mp_ofs;
1772 ntfs_error(vol->sb, "Failed to undo partial resident "
1773 "to non-resident attribute "
1774 "conversion. Truncating inode 0x%lx, "
1775 "attribute type 0x%x from %i bytes to "
1776 "%i bytes to maintain metadata "
1777 "consistency. THIS MEANS YOU ARE "
1778 "LOSING %i BYTES DATA FROM THIS %s.",
1780 (unsigned)le32_to_cpu(ni->type),
1781 err2, attr_size, err2 - attr_size,
1782 ((ni->type == AT_DATA) &&
1783 !ni->name_len) ? "FILE": "ATTRIBUTE");
1784 write_lock_irqsave(&ni->size_lock, flags);
1785 ni->initialized_size = attr_size;
1786 i_size_write(vi, attr_size);
1787 write_unlock_irqrestore(&ni->size_lock, flags);
1790 /* Setup the fields specific to resident attributes. */
1791 a->data.resident.value_length = cpu_to_le32(attr_size);
1792 a->data.resident.value_offset = cpu_to_le16(mp_ofs);
1793 a->data.resident.flags = old_res_attr_flags;
1794 memset(&a->data.resident.reserved, 0,
1795 sizeof(a->data.resident.reserved));
1796 /* Copy the data from the page back to the attribute value. */
1798 kaddr = kmap_atomic(page);
1799 memcpy((u8*)a + mp_ofs, kaddr, attr_size);
1800 kunmap_atomic(kaddr);
1802 /* Setup the allocated size in the ntfs inode in case it changed. */
1803 write_lock_irqsave(&ni->size_lock, flags);
1804 ni->allocated_size = arec_size - mp_ofs;
1805 write_unlock_irqrestore(&ni->size_lock, flags);
1806 /* Mark the mft record dirty, so it gets written back. */
1807 flush_dcache_mft_record_page(ctx->ntfs_ino);
1808 mark_mft_record_dirty(ctx->ntfs_ino);
1811 ntfs_attr_put_search_ctx(ctx);
1813 unmap_mft_record(base_ni);
1814 ni->runlist.rl = NULL;
1815 up_write(&ni->runlist.lock);
1818 if (ntfs_cluster_free_from_rl(vol, rl) < 0) {
1819 ntfs_error(vol->sb, "Failed to release allocated "
1820 "cluster(s) in error code path. Run "
1821 "chkdsk to recover the lost "
1836 * ntfs_attr_extend_allocation - extend the allocated space of an attribute
1837 * @ni: ntfs inode of the attribute whose allocation to extend
1838 * @new_alloc_size: new size in bytes to which to extend the allocation to
1839 * @new_data_size: new size in bytes to which to extend the data to
1840 * @data_start: beginning of region which is required to be non-sparse
1842 * Extend the allocated space of an attribute described by the ntfs inode @ni
1843 * to @new_alloc_size bytes. If @data_start is -1, the whole extension may be
1844 * implemented as a hole in the file (as long as both the volume and the ntfs
1845 * inode @ni have sparse support enabled). If @data_start is >= 0, then the
1846 * region between the old allocated size and @data_start - 1 may be made sparse
1847 * but the regions between @data_start and @new_alloc_size must be backed by
1850 * If @new_data_size is -1, it is ignored. If it is >= 0, then the data size
1851 * of the attribute is extended to @new_data_size. Note that the i_size of the
1852 * vfs inode is not updated. Only the data size in the base attribute record
1853 * is updated. The caller has to update i_size separately if this is required.
1854 * WARNING: It is a BUG() for @new_data_size to be smaller than the old data
1855 * size as well as for @new_data_size to be greater than @new_alloc_size.
1857 * For resident attributes this involves resizing the attribute record and if
1858 * necessary moving it and/or other attributes into extent mft records and/or
1859 * converting the attribute to a non-resident attribute which in turn involves
1860 * extending the allocation of a non-resident attribute as described below.
1862 * For non-resident attributes this involves allocating clusters in the data
1863 * zone on the volume (except for regions that are being made sparse) and
1864 * extending the run list to describe the allocated clusters as well as
1865 * updating the mapping pairs array of the attribute. This in turn involves
1866 * resizing the attribute record and if necessary moving it and/or other
1867 * attributes into extent mft records and/or splitting the attribute record
1868 * into multiple extent attribute records.
1870 * Also, the attribute list attribute is updated if present and in some of the
1871 * above cases (the ones where extent mft records/attributes come into play),
1872 * an attribute list attribute is created if not already present.
1874 * Return the new allocated size on success and -errno on error. In the case
1875 * that an error is encountered but a partial extension at least up to
1876 * @data_start (if present) is possible, the allocation is partially extended
1877 * and this is returned. This means the caller must check the returned size to
1878 * determine if the extension was partial. If @data_start is -1 then partial
1879 * allocations are not performed.
1881 * WARNING: Do not call ntfs_attr_extend_allocation() for $MFT/$DATA.
1883 * Locking: This function takes the runlist lock of @ni for writing as well as
1884 * locking the mft record of the base ntfs inode. These locks are maintained
1885 * throughout execution of the function. These locks are required so that the
1886 * attribute can be resized safely and so that it can for example be converted
1887 * from resident to non-resident safely.
1889 * TODO: At present attribute list attribute handling is not implemented.
1891 * TODO: At present it is not safe to call this function for anything other
1892 * than the $DATA attribute(s) of an uncompressed and unencrypted file.
1894 s64 ntfs_attr_extend_allocation(ntfs_inode *ni, s64 new_alloc_size,
1895 const s64 new_data_size, const s64 data_start)
1898 s64 ll, allocated_size, start = data_start;
1899 struct inode *vi = VFS_I(ni);
1900 ntfs_volume *vol = ni->vol;
1901 ntfs_inode *base_ni;
1904 ntfs_attr_search_ctx *ctx;
1905 runlist_element *rl, *rl2;
1906 unsigned long flags;
1908 u32 attr_len = 0; /* Silence stupid gcc warning. */
1912 read_lock_irqsave(&ni->size_lock, flags);
1913 allocated_size = ni->allocated_size;
1914 read_unlock_irqrestore(&ni->size_lock, flags);
1915 ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, "
1916 "old_allocated_size 0x%llx, "
1917 "new_allocated_size 0x%llx, new_data_size 0x%llx, "
1918 "data_start 0x%llx.", vi->i_ino,
1919 (unsigned)le32_to_cpu(ni->type),
1920 (unsigned long long)allocated_size,
1921 (unsigned long long)new_alloc_size,
1922 (unsigned long long)new_data_size,
1923 (unsigned long long)start);
1927 * For non-resident attributes, @start and @new_size need to be aligned
1928 * to cluster boundaries for allocation purposes.
1930 if (NInoNonResident(ni)) {
1932 start &= ~(s64)vol->cluster_size_mask;
1933 new_alloc_size = (new_alloc_size + vol->cluster_size - 1) &
1934 ~(s64)vol->cluster_size_mask;
1936 BUG_ON(new_data_size >= 0 && new_data_size > new_alloc_size);
1937 /* Check if new size is allowed in $AttrDef. */
1938 err = ntfs_attr_size_bounds_check(vol, ni->type, new_alloc_size);
1939 if (unlikely(err)) {
1940 /* Only emit errors when the write will fail completely. */
1941 read_lock_irqsave(&ni->size_lock, flags);
1942 allocated_size = ni->allocated_size;
1943 read_unlock_irqrestore(&ni->size_lock, flags);
1944 if (start < 0 || start >= allocated_size) {
1945 if (err == -ERANGE) {
1946 ntfs_error(vol->sb, "Cannot extend allocation "
1947 "of inode 0x%lx, attribute "
1948 "type 0x%x, because the new "
1949 "allocation would exceed the "
1950 "maximum allowed size for "
1951 "this attribute type.",
1952 vi->i_ino, (unsigned)
1953 le32_to_cpu(ni->type));
1955 ntfs_error(vol->sb, "Cannot extend allocation "
1956 "of inode 0x%lx, attribute "
1957 "type 0x%x, because this "
1958 "attribute type is not "
1959 "defined on the NTFS volume. "
1960 "Possible corruption! You "
1961 "should run chkdsk!",
1962 vi->i_ino, (unsigned)
1963 le32_to_cpu(ni->type));
1966 /* Translate error code to be POSIX conformant for write(2). */
1976 base_ni = ni->ext.base_ntfs_ino;
1978 * We will be modifying both the runlist (if non-resident) and the mft
1979 * record so lock them both down.
1981 down_write(&ni->runlist.lock);
1982 m = map_mft_record(base_ni);
1989 ctx = ntfs_attr_get_search_ctx(base_ni, m);
1990 if (unlikely(!ctx)) {
1994 read_lock_irqsave(&ni->size_lock, flags);
1995 allocated_size = ni->allocated_size;
1996 read_unlock_irqrestore(&ni->size_lock, flags);
1998 * If non-resident, seek to the last extent. If resident, there is
1999 * only one extent, so seek to that.
2001 vcn = NInoNonResident(ni) ? allocated_size >> vol->cluster_size_bits :
2004 * Abort if someone did the work whilst we waited for the locks. If we
2005 * just converted the attribute from resident to non-resident it is
2006 * likely that exactly this has happened already. We cannot quite
2007 * abort if we need to update the data size.
2009 if (unlikely(new_alloc_size <= allocated_size)) {
2010 ntfs_debug("Allocated size already exceeds requested size.");
2011 new_alloc_size = allocated_size;
2012 if (new_data_size < 0)
2015 * We want the first attribute extent so that we can update the
2020 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
2021 CASE_SENSITIVE, vcn, NULL, 0, ctx);
2022 if (unlikely(err)) {
2029 /* Use goto to reduce indentation. */
2030 if (a->non_resident)
2031 goto do_non_resident_extend;
2032 BUG_ON(NInoNonResident(ni));
2033 /* The total length of the attribute value. */
2034 attr_len = le32_to_cpu(a->data.resident.value_length);
2036 * Extend the attribute record to be able to store the new attribute
2037 * size. ntfs_attr_record_resize() will not do anything if the size is
2040 if (new_alloc_size < vol->mft_record_size &&
2041 !ntfs_attr_record_resize(m, a,
2042 le16_to_cpu(a->data.resident.value_offset) +
2044 /* The resize succeeded! */
2045 write_lock_irqsave(&ni->size_lock, flags);
2046 ni->allocated_size = le32_to_cpu(a->length) -
2047 le16_to_cpu(a->data.resident.value_offset);
2048 write_unlock_irqrestore(&ni->size_lock, flags);
2049 if (new_data_size >= 0) {
2050 BUG_ON(new_data_size < attr_len);
2051 a->data.resident.value_length =
2052 cpu_to_le32((u32)new_data_size);
2057 * We have to drop all the locks so we can call
2058 * ntfs_attr_make_non_resident(). This could be optimised by try-
2059 * locking the first page cache page and only if that fails dropping
2060 * the locks, locking the page, and redoing all the locking and
2061 * lookups. While this would be a huge optimisation, it is not worth
2062 * it as this is definitely a slow code path.
2064 ntfs_attr_put_search_ctx(ctx);
2065 unmap_mft_record(base_ni);
2066 up_write(&ni->runlist.lock);
2068 * Not enough space in the mft record, try to make the attribute
2069 * non-resident and if successful restart the extension process.
2071 err = ntfs_attr_make_non_resident(ni, attr_len);
2075 * Could not make non-resident. If this is due to this not being
2076 * permitted for this attribute type or there not being enough space,
2077 * try to make other attributes non-resident. Otherwise fail.
2079 if (unlikely(err != -EPERM && err != -ENOSPC)) {
2080 /* Only emit errors when the write will fail completely. */
2081 read_lock_irqsave(&ni->size_lock, flags);
2082 allocated_size = ni->allocated_size;
2083 read_unlock_irqrestore(&ni->size_lock, flags);
2084 if (start < 0 || start >= allocated_size)
2085 ntfs_error(vol->sb, "Cannot extend allocation of "
2086 "inode 0x%lx, attribute type 0x%x, "
2087 "because the conversion from resident "
2088 "to non-resident attribute failed "
2089 "with error code %i.", vi->i_ino,
2090 (unsigned)le32_to_cpu(ni->type), err);
2095 /* TODO: Not implemented from here, abort. */
2096 read_lock_irqsave(&ni->size_lock, flags);
2097 allocated_size = ni->allocated_size;
2098 read_unlock_irqrestore(&ni->size_lock, flags);
2099 if (start < 0 || start >= allocated_size) {
2101 ntfs_error(vol->sb, "Not enough space in the mft "
2102 "record/on disk for the non-resident "
2103 "attribute value. This case is not "
2104 "implemented yet.");
2105 else /* if (err == -EPERM) */
2106 ntfs_error(vol->sb, "This attribute type may not be "
2107 "non-resident. This case is not "
2108 "implemented yet.");
2113 // TODO: Attempt to make other attributes non-resident.
2115 goto do_resident_extend;
2117 * Both the attribute list attribute and the standard information
2118 * attribute must remain in the base inode. Thus, if this is one of
2119 * these attributes, we have to try to move other attributes out into
2120 * extent mft records instead.
2122 if (ni->type == AT_ATTRIBUTE_LIST ||
2123 ni->type == AT_STANDARD_INFORMATION) {
2124 // TODO: Attempt to move other attributes into extent mft
2128 goto do_resident_extend;
2131 // TODO: Attempt to move this attribute to an extent mft record, but
2132 // only if it is not already the only attribute in an mft record in
2133 // which case there would be nothing to gain.
2136 goto do_resident_extend;
2137 /* There is nothing we can do to make enough space. )-: */
2140 do_non_resident_extend:
2141 BUG_ON(!NInoNonResident(ni));
2142 if (new_alloc_size == allocated_size) {
2147 * If the data starts after the end of the old allocation, this is a
2148 * $DATA attribute and sparse attributes are enabled on the volume and
2149 * for this inode, then create a sparse region between the old
2150 * allocated size and the start of the data. Otherwise simply proceed
2151 * with filling the whole space between the old allocated size and the
2152 * new allocated size with clusters.
2154 if ((start >= 0 && start <= allocated_size) || ni->type != AT_DATA ||
2155 !NVolSparseEnabled(vol) || NInoSparseDisabled(ni))
2157 // TODO: This is not implemented yet. We just fill in with real
2158 // clusters for now...
2159 ntfs_debug("Inserting holes is not-implemented yet. Falling back to "
2160 "allocating real clusters instead.");
2162 rl = ni->runlist.rl;
2164 /* Seek to the end of the runlist. */
2168 /* If this attribute extent is not mapped, map it now. */
2169 if (unlikely(!rl || rl->lcn == LCN_RL_NOT_MAPPED ||
2170 (rl->lcn == LCN_ENOENT && rl > ni->runlist.rl &&
2171 (rl-1)->lcn == LCN_RL_NOT_MAPPED))) {
2172 if (!rl && !allocated_size)
2174 rl = ntfs_mapping_pairs_decompress(vol, a, ni->runlist.rl);
2177 if (start < 0 || start >= allocated_size)
2178 ntfs_error(vol->sb, "Cannot extend allocation "
2179 "of inode 0x%lx, attribute "
2180 "type 0x%x, because the "
2181 "mapping of a runlist "
2182 "fragment failed with error "
2183 "code %i.", vi->i_ino,
2184 (unsigned)le32_to_cpu(ni->type),
2190 ni->runlist.rl = rl;
2191 /* Seek to the end of the runlist. */
2196 * We now know the runlist of the last extent is mapped and @rl is at
2197 * the end of the runlist. We want to begin allocating clusters
2198 * starting at the last allocated cluster to reduce fragmentation. If
2199 * there are no valid LCNs in the attribute we let the cluster
2200 * allocator choose the starting cluster.
2202 /* If the last LCN is a hole or simillar seek back to last real LCN. */
2203 while (rl->lcn < 0 && rl > ni->runlist.rl)
2206 // FIXME: Need to implement partial allocations so at least part of the
2207 // write can be performed when start >= 0. (Needed for POSIX write(2)
2209 rl2 = ntfs_cluster_alloc(vol, allocated_size >> vol->cluster_size_bits,
2210 (new_alloc_size - allocated_size) >>
2211 vol->cluster_size_bits, (rl && (rl->lcn >= 0)) ?
2212 rl->lcn + rl->length : -1, DATA_ZONE, true);
2215 if (start < 0 || start >= allocated_size)
2216 ntfs_error(vol->sb, "Cannot extend allocation of "
2217 "inode 0x%lx, attribute type 0x%x, "
2218 "because the allocation of clusters "
2219 "failed with error code %i.", vi->i_ino,
2220 (unsigned)le32_to_cpu(ni->type), err);
2221 if (err != -ENOMEM && err != -ENOSPC)
2225 rl = ntfs_runlists_merge(ni->runlist.rl, rl2);
2228 if (start < 0 || start >= allocated_size)
2229 ntfs_error(vol->sb, "Cannot extend allocation of "
2230 "inode 0x%lx, attribute type 0x%x, "
2231 "because the runlist merge failed "
2232 "with error code %i.", vi->i_ino,
2233 (unsigned)le32_to_cpu(ni->type), err);
2236 if (ntfs_cluster_free_from_rl(vol, rl2)) {
2237 ntfs_error(vol->sb, "Failed to release allocated "
2238 "cluster(s) in error code path. Run "
2239 "chkdsk to recover the lost "
2246 ni->runlist.rl = rl;
2247 ntfs_debug("Allocated 0x%llx clusters.", (long long)(new_alloc_size -
2248 allocated_size) >> vol->cluster_size_bits);
2249 /* Find the runlist element with which the attribute extent starts. */
2250 ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
2251 rl2 = ntfs_rl_find_vcn_nolock(rl, ll);
2253 BUG_ON(!rl2->length);
2254 BUG_ON(rl2->lcn < LCN_HOLE);
2256 /* Get the size for the new mapping pairs array for this extent. */
2257 mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
2258 if (unlikely(mp_size <= 0)) {
2260 if (start < 0 || start >= allocated_size)
2261 ntfs_error(vol->sb, "Cannot extend allocation of "
2262 "inode 0x%lx, attribute type 0x%x, "
2263 "because determining the size for the "
2264 "mapping pairs failed with error code "
2266 (unsigned)le32_to_cpu(ni->type), err);
2270 /* Extend the attribute record to fit the bigger mapping pairs array. */
2271 attr_len = le32_to_cpu(a->length);
2272 err = ntfs_attr_record_resize(m, a, mp_size +
2273 le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
2274 if (unlikely(err)) {
2275 BUG_ON(err != -ENOSPC);
2276 // TODO: Deal with this by moving this extent to a new mft
2277 // record or by starting a new extent in a new mft record,
2278 // possibly by extending this extent partially and filling it
2279 // and creating a new extent for the remainder, or by making
2280 // other attributes non-resident and/or by moving other
2281 // attributes out of this mft record.
2282 if (start < 0 || start >= allocated_size)
2283 ntfs_error(vol->sb, "Not enough space in the mft "
2284 "record for the extended attribute "
2285 "record. This case is not "
2286 "implemented yet.");
2291 /* Generate the mapping pairs array directly into the attr record. */
2292 err = ntfs_mapping_pairs_build(vol, (u8*)a +
2293 le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
2294 mp_size, rl2, ll, -1, NULL);
2295 if (unlikely(err)) {
2296 if (start < 0 || start >= allocated_size)
2297 ntfs_error(vol->sb, "Cannot extend allocation of "
2298 "inode 0x%lx, attribute type 0x%x, "
2299 "because building the mapping pairs "
2300 "failed with error code %i.", vi->i_ino,
2301 (unsigned)le32_to_cpu(ni->type), err);
2305 /* Update the highest_vcn. */
2306 a->data.non_resident.highest_vcn = cpu_to_sle64((new_alloc_size >>
2307 vol->cluster_size_bits) - 1);
2309 * We now have extended the allocated size of the attribute. Reflect
2310 * this in the ntfs_inode structure and the attribute record.
2312 if (a->data.non_resident.lowest_vcn) {
2314 * We are not in the first attribute extent, switch to it, but
2315 * first ensure the changes will make it to disk later.
2317 flush_dcache_mft_record_page(ctx->ntfs_ino);
2318 mark_mft_record_dirty(ctx->ntfs_ino);
2319 ntfs_attr_reinit_search_ctx(ctx);
2320 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
2321 CASE_SENSITIVE, 0, NULL, 0, ctx);
2323 goto restore_undo_alloc;
2324 /* @m is not used any more so no need to set it. */
2327 write_lock_irqsave(&ni->size_lock, flags);
2328 ni->allocated_size = new_alloc_size;
2329 a->data.non_resident.allocated_size = cpu_to_sle64(new_alloc_size);
2331 * FIXME: This would fail if @ni is a directory, $MFT, or an index,
2332 * since those can have sparse/compressed set. For example can be
2333 * set compressed even though it is not compressed itself and in that
2334 * case the bit means that files are to be created compressed in the
2335 * directory... At present this is ok as this code is only called for
2336 * regular files, and only for their $DATA attribute(s).
2337 * FIXME: The calculation is wrong if we created a hole above. For now
2338 * it does not matter as we never create holes.
2340 if (NInoSparse(ni) || NInoCompressed(ni)) {
2341 ni->itype.compressed.size += new_alloc_size - allocated_size;
2342 a->data.non_resident.compressed_size =
2343 cpu_to_sle64(ni->itype.compressed.size);
2344 vi->i_blocks = ni->itype.compressed.size >> 9;
2346 vi->i_blocks = new_alloc_size >> 9;
2347 write_unlock_irqrestore(&ni->size_lock, flags);
2349 if (new_data_size >= 0) {
2350 BUG_ON(new_data_size <
2351 sle64_to_cpu(a->data.non_resident.data_size));
2352 a->data.non_resident.data_size = cpu_to_sle64(new_data_size);
2355 /* Ensure the changes make it to disk. */
2356 flush_dcache_mft_record_page(ctx->ntfs_ino);
2357 mark_mft_record_dirty(ctx->ntfs_ino);
2359 ntfs_attr_put_search_ctx(ctx);
2360 unmap_mft_record(base_ni);
2361 up_write(&ni->runlist.lock);
2362 ntfs_debug("Done, new_allocated_size 0x%llx.",
2363 (unsigned long long)new_alloc_size);
2364 return new_alloc_size;
2366 if (start < 0 || start >= allocated_size)
2367 ntfs_error(vol->sb, "Cannot complete extension of allocation "
2368 "of inode 0x%lx, attribute type 0x%x, because "
2369 "lookup of first attribute extent failed with "
2370 "error code %i.", vi->i_ino,
2371 (unsigned)le32_to_cpu(ni->type), err);
2374 ntfs_attr_reinit_search_ctx(ctx);
2375 if (ntfs_attr_lookup(ni->type, ni->name, ni->name_len, CASE_SENSITIVE,
2376 allocated_size >> vol->cluster_size_bits, NULL, 0,
2378 ntfs_error(vol->sb, "Failed to find last attribute extent of "
2379 "attribute in error code path. Run chkdsk to "
2381 write_lock_irqsave(&ni->size_lock, flags);
2382 ni->allocated_size = new_alloc_size;
2384 * FIXME: This would fail if @ni is a directory... See above.
2385 * FIXME: The calculation is wrong if we created a hole above.
2386 * For now it does not matter as we never create holes.
2388 if (NInoSparse(ni) || NInoCompressed(ni)) {
2389 ni->itype.compressed.size += new_alloc_size -
2391 vi->i_blocks = ni->itype.compressed.size >> 9;
2393 vi->i_blocks = new_alloc_size >> 9;
2394 write_unlock_irqrestore(&ni->size_lock, flags);
2395 ntfs_attr_put_search_ctx(ctx);
2396 unmap_mft_record(base_ni);
2397 up_write(&ni->runlist.lock);
2399 * The only thing that is now wrong is the allocated size of the
2400 * base attribute extent which chkdsk should be able to fix.
2405 ctx->attr->data.non_resident.highest_vcn = cpu_to_sle64(
2406 (allocated_size >> vol->cluster_size_bits) - 1);
2408 ll = allocated_size >> vol->cluster_size_bits;
2409 if (ntfs_cluster_free(ni, ll, -1, ctx) < 0) {
2410 ntfs_error(vol->sb, "Failed to release allocated cluster(s) "
2411 "in error code path. Run chkdsk to recover "
2412 "the lost cluster(s).");
2418 * If the runlist truncation fails and/or the search context is no
2419 * longer valid, we cannot resize the attribute record or build the
2420 * mapping pairs array thus we mark the inode bad so that no access to
2421 * the freed clusters can happen.
2423 if (ntfs_rl_truncate_nolock(vol, &ni->runlist, ll) || IS_ERR(m)) {
2424 ntfs_error(vol->sb, "Failed to %s in error code path. Run "
2425 "chkdsk to recover.", IS_ERR(m) ?
2426 "restore attribute search context" :
2427 "truncate attribute runlist");
2429 } else if (mp_rebuilt) {
2430 if (ntfs_attr_record_resize(m, a, attr_len)) {
2431 ntfs_error(vol->sb, "Failed to restore attribute "
2432 "record in error code path. Run "
2433 "chkdsk to recover.");
2435 } else /* if (success) */ {
2436 if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
2437 a->data.non_resident.
2438 mapping_pairs_offset), attr_len -
2439 le16_to_cpu(a->data.non_resident.
2440 mapping_pairs_offset), rl2, ll, -1,
2442 ntfs_error(vol->sb, "Failed to restore "
2443 "mapping pairs array in error "
2444 "code path. Run chkdsk to "
2448 flush_dcache_mft_record_page(ctx->ntfs_ino);
2449 mark_mft_record_dirty(ctx->ntfs_ino);
2454 ntfs_attr_put_search_ctx(ctx);
2456 unmap_mft_record(base_ni);
2457 up_write(&ni->runlist.lock);
2459 ntfs_debug("Failed. Returning error code %i.", err);
2464 * ntfs_attr_set - fill (a part of) an attribute with a byte
2465 * @ni: ntfs inode describing the attribute to fill
2466 * @ofs: offset inside the attribute at which to start to fill
2467 * @cnt: number of bytes to fill
2468 * @val: the unsigned 8-bit value with which to fill the attribute
2470 * Fill @cnt bytes of the attribute described by the ntfs inode @ni starting at
2471 * byte offset @ofs inside the attribute with the constant byte @val.
2473 * This function is effectively like memset() applied to an ntfs attribute.
2474 * Note thie function actually only operates on the page cache pages belonging
2475 * to the ntfs attribute and it marks them dirty after doing the memset().
2476 * Thus it relies on the vm dirty page write code paths to cause the modified
2477 * pages to be written to the mft record/disk.
2479 * Return 0 on success and -errno on error. An error code of -ESPIPE means
2480 * that @ofs + @cnt were outside the end of the attribute and no write was
2483 int ntfs_attr_set(ntfs_inode *ni, const s64 ofs, const s64 cnt, const u8 val)
2485 ntfs_volume *vol = ni->vol;
2486 struct address_space *mapping;
2490 unsigned start_ofs, end_ofs, size;
2492 ntfs_debug("Entering for ofs 0x%llx, cnt 0x%llx, val 0x%hx.",
2493 (long long)ofs, (long long)cnt, val);
2499 * FIXME: Compressed and encrypted attributes are not supported when
2500 * writing and we should never have gotten here for them.
2502 BUG_ON(NInoCompressed(ni));
2503 BUG_ON(NInoEncrypted(ni));
2504 mapping = VFS_I(ni)->i_mapping;
2505 /* Work out the starting index and page offset. */
2506 idx = ofs >> PAGE_SHIFT;
2507 start_ofs = ofs & ~PAGE_MASK;
2508 /* Work out the ending index and page offset. */
2510 end_ofs = end & ~PAGE_MASK;
2511 /* If the end is outside the inode size return -ESPIPE. */
2512 if (unlikely(end > i_size_read(VFS_I(ni)))) {
2513 ntfs_error(vol->sb, "Request exceeds end of attribute.");
2517 /* If there is a first partial page, need to do it the slow way. */
2519 page = read_mapping_page(mapping, idx, NULL);
2521 ntfs_error(vol->sb, "Failed to read first partial "
2522 "page (error, index 0x%lx).", idx);
2523 return PTR_ERR(page);
2526 * If the last page is the same as the first page, need to
2527 * limit the write to the end offset.
2532 kaddr = kmap_atomic(page);
2533 memset(kaddr + start_ofs, val, size - start_ofs);
2534 flush_dcache_page(page);
2535 kunmap_atomic(kaddr);
2536 set_page_dirty(page);
2538 balance_dirty_pages_ratelimited(mapping);
2544 /* Do the whole pages the fast way. */
2545 for (; idx < end; idx++) {
2546 /* Find or create the current page. (The page is locked.) */
2547 page = grab_cache_page(mapping, idx);
2548 if (unlikely(!page)) {
2549 ntfs_error(vol->sb, "Insufficient memory to grab "
2550 "page (index 0x%lx).", idx);
2553 kaddr = kmap_atomic(page);
2554 memset(kaddr, val, PAGE_SIZE);
2555 flush_dcache_page(page);
2556 kunmap_atomic(kaddr);
2558 * If the page has buffers, mark them uptodate since buffer
2559 * state and not page state is definitive in 2.6 kernels.
2561 if (page_has_buffers(page)) {
2562 struct buffer_head *bh, *head;
2564 bh = head = page_buffers(page);
2566 set_buffer_uptodate(bh);
2567 } while ((bh = bh->b_this_page) != head);
2569 /* Now that buffers are uptodate, set the page uptodate, too. */
2570 SetPageUptodate(page);
2572 * Set the page and all its buffers dirty and mark the inode
2573 * dirty, too. The VM will write the page later on.
2575 set_page_dirty(page);
2576 /* Finally unlock and release the page. */
2579 balance_dirty_pages_ratelimited(mapping);
2582 /* If there is a last partial page, need to do it the slow way. */
2584 page = read_mapping_page(mapping, idx, NULL);
2586 ntfs_error(vol->sb, "Failed to read last partial page "
2587 "(error, index 0x%lx).", idx);
2588 return PTR_ERR(page);
2590 kaddr = kmap_atomic(page);
2591 memset(kaddr, val, end_ofs);
2592 flush_dcache_page(page);
2593 kunmap_atomic(kaddr);
2594 set_page_dirty(page);
2596 balance_dirty_pages_ratelimited(mapping);
2600 ntfs_debug("Done.");
2604 #endif /* NTFS_RW */