1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * NTFS attribute operations.
4 *
5 * Copyright (c) 2001-2012 Anton Altaparmakov and Tuxera Inc.
6 * Copyright (c) 2002 Richard Russon
7 * Copyright (c) 2025 LG Electronics Co., Ltd.
8 *
9 * Part of this file is based on code from the NTFS-3G.
10 * and is copyrighted by the respective authors below:
11 * Copyright (c) 2000-2010 Anton Altaparmakov
12 * Copyright (c) 2002-2005 Richard Russon
13 * Copyright (c) 2002-2008 Szabolcs Szakacsits
14 * Copyright (c) 2004-2007 Yura Pakhuchiy
15 * Copyright (c) 2007-2021 Jean-Pierre Andre
16 * Copyright (c) 2010 Erik Larsson
17 */
18
19 #include <linux/writeback.h>
20 #include <linux/iomap.h>
21
22 #include "attrib.h"
23 #include "attrlist.h"
24 #include "lcnalloc.h"
25 #include "debug.h"
26 #include "mft.h"
27 #include "ntfs.h"
28 #include "iomap.h"
29
30 __le16 AT_UNNAMED[] = { cpu_to_le16('\0') };
31
32 /*
33 * Maximum size allowed for reading attributes by ntfs_attr_readall().
34 * Extended attribute, reparse point are not expected to be larger than this size.
35 */
36
37 #define NTFS_ATTR_READALL_MAX_SIZE (64 * 1024)
38
39 /*
40 * ntfs_map_runlist_nolock - map (a part of) a runlist of an ntfs inode
41 * @ni: ntfs inode for which to map (part of) a runlist
42 * @vcn: map runlist part containing this vcn
43 * @ctx: active attribute search context if present or NULL if not
44 *
45 * Map the part of a runlist containing the @vcn of the ntfs inode @ni.
46 *
47 * If @ctx is specified, it is an active search context of @ni and its base mft
48 * record. This is needed when ntfs_map_runlist_nolock() encounters unmapped
49 * runlist fragments and allows their mapping. If you do not have the mft
50 * record mapped, you can specify @ctx as NULL and ntfs_map_runlist_nolock()
51 * will perform the necessary mapping and unmapping.
52 *
53 * Note, ntfs_map_runlist_nolock() saves the state of @ctx on entry and
54 * restores it before returning. Thus, @ctx will be left pointing to the same
55 * attribute on return as on entry. However, the actual pointers in @ctx may
56 * point to different memory locations on return, so you must remember to reset
57 * any cached pointers from the @ctx, i.e. after the call to
58 * ntfs_map_runlist_nolock(), you will probably want to do:
59 * m = ctx->mrec;
60 * a = ctx->attr;
61 * Assuming you cache ctx->attr in a variable @a of type struct attr_record *
62 * and that you cache ctx->mrec in a variable @m of type struct mft_record *.
63 *
64 * Return 0 on success and -errno on error. There is one special error code
65 * which is not an error as such. This is -ENOENT. It means that @vcn is out
66 * of bounds of the runlist.
67 *
68 * Note the runlist can be NULL after this function returns if @vcn is zero and
69 * the attribute has zero allocated size, i.e. there simply is no runlist.
70 *
71 * WARNING: If @ctx is supplied, regardless of whether success or failure is
72 * returned, you need to check IS_ERR(@ctx->mrec) and if 'true' the @ctx
73 * is no longer valid, i.e. you need to either call
74 * ntfs_attr_reinit_search_ctx() or ntfs_attr_put_search_ctx() on it.
75 * In that case PTR_ERR(@ctx->mrec) will give you the error code for
76 * why the mapping of the old inode failed.
77 *
78 * Locking: - The runlist described by @ni must be locked for writing on entry
79 * and is locked on return. Note the runlist will be modified.
80 * - If @ctx is NULL, the base mft record of @ni must not be mapped on
81 * entry and it will be left unmapped on return.
82 * - If @ctx is not NULL, the base mft record must be mapped on entry
83 * and it will be left mapped on return.
84 */
ntfs_map_runlist_nolock(struct ntfs_inode * ni,s64 vcn,struct ntfs_attr_search_ctx * ctx)85 int ntfs_map_runlist_nolock(struct ntfs_inode *ni, s64 vcn, struct ntfs_attr_search_ctx *ctx)
86 {
87 s64 end_vcn;
88 unsigned long flags;
89 struct ntfs_inode *base_ni;
90 struct mft_record *m;
91 struct attr_record *a;
92 struct runlist_element *rl;
93 struct folio *put_this_folio = NULL;
94 int err = 0;
95 bool ctx_is_temporary = false, ctx_needs_reset = false;
96 struct ntfs_attr_search_ctx old_ctx = { NULL, };
97 size_t new_rl_count;
98
99 ntfs_debug("Mapping runlist part containing vcn 0x%llx.",
100 (unsigned long long)vcn);
101 if (!NInoAttr(ni))
102 base_ni = ni;
103 else
104 base_ni = ni->ext.base_ntfs_ino;
105 if (!ctx) {
106 ctx_is_temporary = ctx_needs_reset = true;
107 m = map_mft_record(base_ni);
108 if (IS_ERR(m))
109 return PTR_ERR(m);
110 ctx = ntfs_attr_get_search_ctx(base_ni, m);
111 if (unlikely(!ctx)) {
112 err = -ENOMEM;
113 goto err_out;
114 }
115 } else {
116 s64 allocated_size_vcn;
117
118 WARN_ON(IS_ERR(ctx->mrec));
119 a = ctx->attr;
120 if (!a->non_resident) {
121 err = -EIO;
122 goto err_out;
123 }
124 end_vcn = le64_to_cpu(a->data.non_resident.highest_vcn);
125 read_lock_irqsave(&ni->size_lock, flags);
126 allocated_size_vcn =
127 ntfs_bytes_to_cluster(ni->vol, ni->allocated_size);
128 read_unlock_irqrestore(&ni->size_lock, flags);
129 if (!a->data.non_resident.lowest_vcn && end_vcn <= 0)
130 end_vcn = allocated_size_vcn - 1;
131 /*
132 * If we already have the attribute extent containing @vcn in
133 * @ctx, no need to look it up again. We slightly cheat in
134 * that if vcn exceeds the allocated size, we will refuse to
135 * map the runlist below, so there is definitely no need to get
136 * the right attribute extent.
137 */
138 if (vcn >= allocated_size_vcn || (a->type == ni->type &&
139 a->name_length == ni->name_len &&
140 !memcmp((u8 *)a + le16_to_cpu(a->name_offset),
141 ni->name, ni->name_len) &&
142 le64_to_cpu(a->data.non_resident.lowest_vcn)
143 <= vcn && end_vcn >= vcn))
144 ctx_needs_reset = false;
145 else {
146 /* Save the old search context. */
147 old_ctx = *ctx;
148 /*
149 * If the currently mapped (extent) inode is not the
150 * base inode we will unmap it when we reinitialize the
151 * search context which means we need to get a
152 * reference to the page containing the mapped mft
153 * record so we do not accidentally drop changes to the
154 * mft record when it has not been marked dirty yet.
155 */
156 if (old_ctx.base_ntfs_ino && old_ctx.ntfs_ino !=
157 old_ctx.base_ntfs_ino) {
158 put_this_folio = old_ctx.ntfs_ino->folio;
159 folio_get(put_this_folio);
160 }
161 /*
162 * Reinitialize the search context so we can lookup the
163 * needed attribute extent.
164 */
165 ntfs_attr_reinit_search_ctx(ctx);
166 ctx_needs_reset = true;
167 }
168 }
169 if (ctx_needs_reset) {
170 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
171 CASE_SENSITIVE, vcn, NULL, 0, ctx);
172 if (unlikely(err)) {
173 if (err == -ENOENT)
174 err = -EIO;
175 goto err_out;
176 }
177 WARN_ON(!ctx->attr->non_resident);
178 }
179 a = ctx->attr;
180 /*
181 * Only decompress the mapping pairs if @vcn is inside it. Otherwise
182 * we get into problems when we try to map an out of bounds vcn because
183 * we then try to map the already mapped runlist fragment and
184 * ntfs_mapping_pairs_decompress() fails.
185 */
186 end_vcn = le64_to_cpu(a->data.non_resident.highest_vcn) + 1;
187 if (unlikely(vcn && vcn >= end_vcn)) {
188 err = -ENOENT;
189 goto err_out;
190 }
191 rl = ntfs_mapping_pairs_decompress(ni->vol, a, &ni->runlist, &new_rl_count);
192 if (IS_ERR(rl))
193 err = PTR_ERR(rl);
194 else {
195 ni->runlist.rl = rl;
196 ni->runlist.count = new_rl_count;
197 }
198 err_out:
199 if (ctx_is_temporary) {
200 if (likely(ctx))
201 ntfs_attr_put_search_ctx(ctx);
202 unmap_mft_record(base_ni);
203 } else if (ctx_needs_reset) {
204 /*
205 * If there is no attribute list, restoring the search context
206 * is accomplished simply by copying the saved context back over
207 * the caller supplied context. If there is an attribute list,
208 * things are more complicated as we need to deal with mapping
209 * of mft records and resulting potential changes in pointers.
210 */
211 if (NInoAttrList(base_ni)) {
212 /*
213 * If the currently mapped (extent) inode is not the
214 * one we had before, we need to unmap it and map the
215 * old one.
216 */
217 if (ctx->ntfs_ino != old_ctx.ntfs_ino) {
218 /*
219 * If the currently mapped inode is not the
220 * base inode, unmap it.
221 */
222 if (ctx->base_ntfs_ino && ctx->ntfs_ino !=
223 ctx->base_ntfs_ino) {
224 unmap_extent_mft_record(ctx->ntfs_ino);
225 ctx->mrec = ctx->base_mrec;
226 WARN_ON(!ctx->mrec);
227 }
228 /*
229 * If the old mapped inode is not the base
230 * inode, map it.
231 */
232 if (old_ctx.base_ntfs_ino &&
233 old_ctx.ntfs_ino != old_ctx.base_ntfs_ino) {
234 retry_map:
235 ctx->mrec = map_mft_record(old_ctx.ntfs_ino);
236 /*
237 * Something bad has happened. If out
238 * of memory retry till it succeeds.
239 * Any other errors are fatal and we
240 * return the error code in ctx->mrec.
241 * Let the caller deal with it... We
242 * just need to fudge things so the
243 * caller can reinit and/or put the
244 * search context safely.
245 */
246 if (IS_ERR(ctx->mrec)) {
247 if (PTR_ERR(ctx->mrec) == -ENOMEM) {
248 schedule();
249 goto retry_map;
250 } else
251 old_ctx.ntfs_ino =
252 old_ctx.base_ntfs_ino;
253 }
254 }
255 }
256 /* Update the changed pointers in the saved context. */
257 if (ctx->mrec != old_ctx.mrec) {
258 if (!IS_ERR(ctx->mrec))
259 old_ctx.attr = (struct attr_record *)(
260 (u8 *)ctx->mrec +
261 ((u8 *)old_ctx.attr -
262 (u8 *)old_ctx.mrec));
263 old_ctx.mrec = ctx->mrec;
264 }
265 }
266 /* Restore the search context to the saved one. */
267 *ctx = old_ctx;
268 /*
269 * We drop the reference on the page we took earlier. In the
270 * case that IS_ERR(ctx->mrec) is true this means we might lose
271 * some changes to the mft record that had been made between
272 * the last time it was marked dirty/written out and now. This
273 * at this stage is not a problem as the mapping error is fatal
274 * enough that the mft record cannot be written out anyway and
275 * the caller is very likely to shutdown the whole inode
276 * immediately and mark the volume dirty for chkdsk to pick up
277 * the pieces anyway.
278 */
279 if (put_this_folio)
280 folio_put(put_this_folio);
281 }
282 return err;
283 }
284
285 /*
286 * ntfs_map_runlist - map (a part of) a runlist of an ntfs inode
287 * @ni: ntfs inode for which to map (part of) a runlist
288 * @vcn: map runlist part containing this vcn
289 *
290 * Map the part of a runlist containing the @vcn of the ntfs inode @ni.
291 *
292 * Return 0 on success and -errno on error. There is one special error code
293 * which is not an error as such. This is -ENOENT. It means that @vcn is out
294 * of bounds of the runlist.
295 *
296 * Locking: - The runlist must be unlocked on entry and is unlocked on return.
297 * - This function takes the runlist lock for writing and may modify
298 * the runlist.
299 */
ntfs_map_runlist(struct ntfs_inode * ni,s64 vcn)300 int ntfs_map_runlist(struct ntfs_inode *ni, s64 vcn)
301 {
302 int err = 0;
303
304 down_write(&ni->runlist.lock);
305 /* Make sure someone else didn't do the work while we were sleeping. */
306 if (likely(ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn) <=
307 LCN_RL_NOT_MAPPED))
308 err = ntfs_map_runlist_nolock(ni, vcn, NULL);
309 up_write(&ni->runlist.lock);
310 return err;
311 }
312
ntfs_attr_vcn_to_rl(struct ntfs_inode * ni,s64 vcn,s64 * lcn)313 struct runlist_element *ntfs_attr_vcn_to_rl(struct ntfs_inode *ni, s64 vcn, s64 *lcn)
314 {
315 struct runlist_element *rl = ni->runlist.rl;
316 int err;
317 bool is_retry = false;
318
319 if (!rl) {
320 err = ntfs_attr_map_whole_runlist(ni);
321 if (err)
322 return ERR_PTR(-ENOENT);
323 rl = ni->runlist.rl;
324 }
325
326 remap_rl:
327 /* Seek to element containing target vcn. */
328 while (rl->length && rl[1].vcn <= vcn)
329 rl++;
330 *lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
331
332 if (*lcn <= LCN_RL_NOT_MAPPED && is_retry == false) {
333 is_retry = true;
334 if (!ntfs_map_runlist_nolock(ni, vcn, NULL)) {
335 rl = ni->runlist.rl;
336 goto remap_rl;
337 }
338 }
339
340 return rl;
341 }
342
343 /*
344 * ntfs_attr_vcn_to_lcn_nolock - convert a vcn into a lcn given an ntfs inode
345 * @ni: ntfs inode of the attribute whose runlist to search
346 * @vcn: vcn to convert
347 * @write_locked: true if the runlist is locked for writing
348 *
349 * Find the virtual cluster number @vcn in the runlist of the ntfs attribute
350 * described by the ntfs inode @ni and return the corresponding logical cluster
351 * number (lcn).
352 *
353 * If the @vcn is not mapped yet, the attempt is made to map the attribute
354 * extent containing the @vcn and the vcn to lcn conversion is retried.
355 *
356 * If @write_locked is true the caller has locked the runlist for writing and
357 * if false for reading.
358 *
359 * Since lcns must be >= 0, we use negative return codes with special meaning:
360 *
361 * Return code Meaning / Description
362 * ==========================================
363 * LCN_HOLE Hole / not allocated on disk.
364 * LCN_ENOENT There is no such vcn in the runlist, i.e. @vcn is out of bounds.
365 * LCN_ENOMEM Not enough memory to map runlist.
366 * LCN_EIO Critical error (runlist/file is corrupt, i/o error, etc).
367 *
368 * Locking: - The runlist must be locked on entry and is left locked on return.
369 * - If @write_locked is 'false', i.e. the runlist is locked for reading,
370 * the lock may be dropped inside the function so you cannot rely on
371 * the runlist still being the same when this function returns.
372 */
ntfs_attr_vcn_to_lcn_nolock(struct ntfs_inode * ni,const s64 vcn,const bool write_locked)373 s64 ntfs_attr_vcn_to_lcn_nolock(struct ntfs_inode *ni, const s64 vcn,
374 const bool write_locked)
375 {
376 s64 lcn;
377 unsigned long flags;
378 bool is_retry = false;
379
380 ntfs_debug("Entering for i_ino 0x%llx, vcn 0x%llx, %s_locked.",
381 ni->mft_no, (unsigned long long)vcn,
382 write_locked ? "write" : "read");
383 if (!ni->runlist.rl) {
384 read_lock_irqsave(&ni->size_lock, flags);
385 if (!ni->allocated_size) {
386 read_unlock_irqrestore(&ni->size_lock, flags);
387 return LCN_ENOENT;
388 }
389 read_unlock_irqrestore(&ni->size_lock, flags);
390 }
391 retry_remap:
392 /* Convert vcn to lcn. If that fails map the runlist and retry once. */
393 lcn = ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn);
394 if (likely(lcn >= LCN_HOLE)) {
395 ntfs_debug("Done, lcn 0x%llx.", (long long)lcn);
396 return lcn;
397 }
398 if (lcn != LCN_RL_NOT_MAPPED) {
399 if (lcn != LCN_ENOENT)
400 lcn = LCN_EIO;
401 } else if (!is_retry) {
402 int err;
403
404 if (!write_locked) {
405 up_read(&ni->runlist.lock);
406 down_write(&ni->runlist.lock);
407 if (unlikely(ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn) !=
408 LCN_RL_NOT_MAPPED)) {
409 up_write(&ni->runlist.lock);
410 down_read(&ni->runlist.lock);
411 goto retry_remap;
412 }
413 }
414 err = ntfs_map_runlist_nolock(ni, vcn, NULL);
415 if (!write_locked) {
416 up_write(&ni->runlist.lock);
417 down_read(&ni->runlist.lock);
418 }
419 if (likely(!err)) {
420 is_retry = true;
421 goto retry_remap;
422 }
423 if (err == -ENOENT)
424 lcn = LCN_ENOENT;
425 else if (err == -ENOMEM)
426 lcn = LCN_ENOMEM;
427 else
428 lcn = LCN_EIO;
429 }
430 if (lcn != LCN_ENOENT)
431 ntfs_error(ni->vol->sb, "Failed with error code %lli.",
432 (long long)lcn);
433 return lcn;
434 }
435
__ntfs_attr_find_vcn_nolock(struct runlist * runlist,const s64 vcn)436 struct runlist_element *__ntfs_attr_find_vcn_nolock(struct runlist *runlist, const s64 vcn)
437 {
438 size_t lower_idx, upper_idx, idx;
439 struct runlist_element *run;
440 int rh = runlist->rl_hint;
441
442 if (runlist->count <= 1)
443 return ERR_PTR(-ENOENT);
444
445 if (runlist->count - 1 > rh && runlist->rl[rh].vcn <= vcn) {
446 if (vcn < runlist->rl[rh].vcn + runlist->rl[rh].length)
447 return &runlist->rl[rh];
448 if (runlist->count - 2 == rh)
449 return ERR_PTR(-ENOENT);
450
451 lower_idx = rh + 1;
452 } else {
453 run = &runlist->rl[0];
454 if (vcn < run->vcn)
455 return ERR_PTR(-ENOENT);
456 else if (vcn < run->vcn + run->length) {
457 runlist->rl_hint = 0;
458 return run;
459 }
460
461 lower_idx = 1;
462 }
463
464 run = &runlist->rl[runlist->count - 2];
465 if (vcn >= run->vcn && vcn < run->vcn + run->length) {
466 runlist->rl_hint = runlist->count - 2;
467 return run;
468 }
469 if (vcn >= run->vcn + run->length)
470 return ERR_PTR(-ENOENT);
471
472 upper_idx = runlist->count - 2;
473
474 while (lower_idx <= upper_idx) {
475 idx = (lower_idx + upper_idx) >> 1;
476 run = &runlist->rl[idx];
477
478 if (vcn < run->vcn)
479 upper_idx = idx - 1;
480 else if (vcn >= run->vcn + run->length)
481 lower_idx = idx + 1;
482 else {
483 runlist->rl_hint = idx;
484 return run;
485 }
486 }
487
488 return ERR_PTR(-ENOENT);
489 }
490
491 /*
492 * ntfs_attr_find_vcn_nolock - find a vcn in the runlist of an ntfs inode
493 * @ni: ntfs inode describing the runlist to search
494 * @vcn: vcn to find
495 * @ctx: active attribute search context if present or NULL if not
496 *
497 * Find the virtual cluster number @vcn in the runlist described by the ntfs
498 * inode @ni and return the address of the runlist element containing the @vcn.
499 *
500 * If the @vcn is not mapped yet, the attempt is made to map the attribute
501 * extent containing the @vcn and the vcn to lcn conversion is retried.
502 *
503 * If @ctx is specified, it is an active search context of @ni and its base mft
504 * record. This is needed when ntfs_attr_find_vcn_nolock() encounters unmapped
505 * runlist fragments and allows their mapping. If you do not have the mft
506 * record mapped, you can specify @ctx as NULL and ntfs_attr_find_vcn_nolock()
507 * will perform the necessary mapping and unmapping.
508 *
509 * Note, ntfs_attr_find_vcn_nolock() saves the state of @ctx on entry and
510 * restores it before returning. Thus, @ctx will be left pointing to the same
511 * attribute on return as on entry. However, the actual pointers in @ctx may
512 * point to different memory locations on return, so you must remember to reset
513 * any cached pointers from the @ctx, i.e. after the call to
514 * ntfs_attr_find_vcn_nolock(), you will probably want to do:
515 * m = ctx->mrec;
516 * a = ctx->attr;
517 * Assuming you cache ctx->attr in a variable @a of type attr_record * and that
518 * you cache ctx->mrec in a variable @m of type struct mft_record *.
519 * Note you need to distinguish between the lcn of the returned runlist element
520 * being >= 0 and LCN_HOLE. In the later case you have to return zeroes on
521 * read and allocate clusters on write.
522 */
ntfs_attr_find_vcn_nolock(struct ntfs_inode * ni,const s64 vcn,struct ntfs_attr_search_ctx * ctx)523 struct runlist_element *ntfs_attr_find_vcn_nolock(struct ntfs_inode *ni, const s64 vcn,
524 struct ntfs_attr_search_ctx *ctx)
525 {
526 unsigned long flags;
527 struct runlist_element *rl;
528 int err = 0;
529 bool is_retry = false;
530
531 ntfs_debug("Entering for i_ino 0x%llx, vcn 0x%llx, with%s ctx.",
532 ni->mft_no, (unsigned long long)vcn, ctx ? "" : "out");
533 if (!ni->runlist.rl) {
534 read_lock_irqsave(&ni->size_lock, flags);
535 if (!ni->allocated_size) {
536 read_unlock_irqrestore(&ni->size_lock, flags);
537 return ERR_PTR(-ENOENT);
538 }
539 read_unlock_irqrestore(&ni->size_lock, flags);
540 }
541
542 retry_remap:
543 rl = ni->runlist.rl;
544 if (likely(rl && vcn >= rl[0].vcn)) {
545 rl = __ntfs_attr_find_vcn_nolock(&ni->runlist, vcn);
546 if (IS_ERR(rl))
547 err = PTR_ERR(rl);
548 else if (rl->lcn >= LCN_HOLE)
549 return rl;
550 else if (rl->lcn <= LCN_ENOENT)
551 err = -EIO;
552 }
553 if (!err && !is_retry) {
554 /*
555 * If the search context is invalid we cannot map the unmapped
556 * region.
557 */
558 if (ctx && IS_ERR(ctx->mrec))
559 err = PTR_ERR(ctx->mrec);
560 else {
561 /*
562 * The @vcn is in an unmapped region, map the runlist
563 * and retry.
564 */
565 err = ntfs_map_runlist_nolock(ni, vcn, ctx);
566 if (likely(!err)) {
567 is_retry = true;
568 goto retry_remap;
569 }
570 }
571 if (err == -EINVAL)
572 err = -EIO;
573 } else if (!err)
574 err = -EIO;
575 if (err != -ENOENT)
576 ntfs_error(ni->vol->sb, "Failed with error code %i.", err);
577 return ERR_PTR(err);
578 }
579
ntfs_resident_attr_min_value_length(const __le32 type)580 static u32 ntfs_resident_attr_min_value_length(const __le32 type)
581 {
582 switch (type) {
583 case AT_STANDARD_INFORMATION:
584 return offsetof(struct standard_information, ver) +
585 sizeof(((struct standard_information *)0)->ver.v1.reserved12);
586 case AT_ATTRIBUTE_LIST:
587 return offsetof(struct attr_list_entry, name);
588 case AT_FILE_NAME:
589 return offsetof(struct file_name_attr, file_name);
590 case AT_OBJECT_ID:
591 return sizeof(struct guid);
592 case AT_SECURITY_DESCRIPTOR:
593 return sizeof(struct security_descriptor_relative);
594 case AT_VOLUME_INFORMATION:
595 return sizeof(struct volume_information);
596 case AT_INDEX_ROOT:
597 return sizeof(struct index_root);
598 case AT_REPARSE_POINT:
599 return offsetof(struct reparse_point, reparse_data);
600 case AT_EA_INFORMATION:
601 return sizeof(struct ea_information);
602 case AT_EA:
603 return offsetof(struct ea_attr, ea_name) + 1;
604 default:
605 return 0;
606 }
607 }
608
609 /*
610 * ntfs_attr_find - find (next) attribute in mft record
611 * @type: attribute type to find
612 * @name: attribute name to find (optional, i.e. NULL means don't care)
613 * @name_len: attribute name length (only needed if @name present)
614 * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
615 * @val: attribute value to find (optional, resident attributes only)
616 * @val_len: attribute value length
617 * @ctx: search context with mft record and attribute to search from
618 *
619 * You should not need to call this function directly. Use ntfs_attr_lookup()
620 * instead.
621 *
622 * ntfs_attr_find() takes a search context @ctx as parameter and searches the
623 * mft record specified by @ctx->mrec, beginning at @ctx->attr, for an
624 * attribute of @type, optionally @name and @val.
625 *
626 * If the attribute is found, ntfs_attr_find() returns 0 and @ctx->attr will
627 * point to the found attribute.
628 *
629 * If the attribute is not found, ntfs_attr_find() returns -ENOENT and
630 * @ctx->attr will point to the attribute before which the attribute being
631 * searched for would need to be inserted if such an action were to be desired.
632 *
633 * On actual error, ntfs_attr_find() returns -EIO. In this case @ctx->attr is
634 * undefined and in particular do not rely on it not changing.
635 *
636 * If @ctx->is_first is 'true', the search begins with @ctx->attr itself. If it
637 * is 'false', the search begins after @ctx->attr.
638 *
639 * If @ic is IGNORE_CASE, the @name comparisson is not case sensitive and
640 * @ctx->ntfs_ino must be set to the ntfs inode to which the mft record
641 * @ctx->mrec belongs. This is so we can get at the ntfs volume and hence at
642 * the upcase table. If @ic is CASE_SENSITIVE, the comparison is case
643 * sensitive. When @name is present, @name_len is the @name length in Unicode
644 * characters.
645 *
646 * If @name is not present (NULL), we assume that the unnamed attribute is
647 * being searched for.
648 *
649 * Finally, the resident attribute value @val is looked for, if present. If
650 * @val is not present (NULL), @val_len is ignored.
651 *
652 * ntfs_attr_find() only searches the specified mft record and it ignores the
653 * presence of an attribute list attribute (unless it is the one being searched
654 * for, obviously). If you need to take attribute lists into consideration,
655 * use ntfs_attr_lookup() instead (see below). This also means that you cannot
656 * use ntfs_attr_find() to search for extent records of non-resident
657 * attributes, as extents with lowest_vcn != 0 are usually described by the
658 * attribute list attribute only. - Note that it is possible that the first
659 * extent is only in the attribute list while the last extent is in the base
660 * mft record, so do not rely on being able to find the first extent in the
661 * base mft record.
662 *
663 * Warning: Never use @val when looking for attribute types which can be
664 * non-resident as this most likely will result in a crash!
665 */
ntfs_attr_find(const __le32 type,const __le16 * name,const u32 name_len,const u32 ic,const u8 * val,const u32 val_len,struct ntfs_attr_search_ctx * ctx)666 static int ntfs_attr_find(const __le32 type, const __le16 *name,
667 const u32 name_len, const u32 ic,
668 const u8 *val, const u32 val_len, struct ntfs_attr_search_ctx *ctx)
669 {
670 struct attr_record *a;
671 struct ntfs_volume *vol = ctx->ntfs_ino->vol;
672 __le16 *upcase = vol->upcase;
673 u32 upcase_len = vol->upcase_len;
674 unsigned int space;
675
676 /*
677 * Iterate over attributes in mft record starting at @ctx->attr, or the
678 * attribute following that, if @ctx->is_first is 'true'.
679 */
680 if (ctx->is_first) {
681 a = ctx->attr;
682 ctx->is_first = false;
683 } else
684 a = (struct attr_record *)((u8 *)ctx->attr +
685 le32_to_cpu(ctx->attr->length));
686 for (;; a = (struct attr_record *)((u8 *)a + le32_to_cpu(a->length))) {
687 if ((u8 *)a < (u8 *)ctx->mrec || (u8 *)a > (u8 *)ctx->mrec +
688 le32_to_cpu(ctx->mrec->bytes_allocated))
689 break;
690
691 space = le32_to_cpu(ctx->mrec->bytes_in_use) - ((u8 *)a - (u8 *)ctx->mrec);
692 if ((space < offsetof(struct attr_record, data.resident.reserved) + 1 ||
693 space < le32_to_cpu(a->length)) && (space < 4 || a->type != AT_END))
694 break;
695
696 ctx->attr = a;
697 if (((type != AT_UNUSED) && (le32_to_cpu(a->type) > le32_to_cpu(type))) ||
698 a->type == AT_END)
699 return -ENOENT;
700 if (unlikely(!a->length))
701 break;
702 if (type == AT_UNUSED)
703 return 0;
704 if (a->type != type)
705 continue;
706 /*
707 * If @name is present, compare the two names. If @name is
708 * missing, assume we want an unnamed attribute.
709 */
710 if (!name || name == AT_UNNAMED) {
711 /* The search failed if the found attribute is named. */
712 if (a->name_length)
713 return -ENOENT;
714 } else {
715 if (a->name_length && ((le16_to_cpu(a->name_offset) +
716 a->name_length * sizeof(__le16)) >
717 le32_to_cpu(a->length))) {
718 ntfs_error(vol->sb, "Corrupt attribute name in MFT record %llu\n",
719 ctx->ntfs_ino->mft_no);
720 break;
721 }
722
723 if (!ntfs_are_names_equal(name, name_len,
724 (__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
725 a->name_length, ic, upcase, upcase_len)) {
726 register int rc;
727
728 rc = ntfs_collate_names(name, name_len,
729 (__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
730 a->name_length, 1, IGNORE_CASE,
731 upcase, upcase_len);
732 /*
733 * If @name collates before a->name, there is no
734 * matching attribute.
735 */
736 if (rc == -1)
737 return -ENOENT;
738 /* If the strings are not equal, continue search. */
739 if (rc)
740 continue;
741 rc = ntfs_collate_names(name, name_len,
742 (__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
743 a->name_length, 1, CASE_SENSITIVE,
744 upcase, upcase_len);
745 if (rc == -1)
746 return -ENOENT;
747 if (rc)
748 continue;
749 }
750 }
751
752 /* Validate attribute's value offset/length */
753 if (!a->non_resident) {
754 u32 min_len;
755 u32 value_length = le32_to_cpu(a->data.resident.value_length);
756 u16 value_offset = le16_to_cpu(a->data.resident.value_offset);
757
758 if (value_length > le32_to_cpu(a->length) ||
759 value_offset > le32_to_cpu(a->length) - value_length)
760 break;
761
762 min_len = ntfs_resident_attr_min_value_length(a->type);
763 if (min_len && value_length < min_len) {
764 ntfs_error(vol->sb,
765 "Too small %#x resident attribute value in MFT record %lld\n",
766 le32_to_cpu(a->type), (long long)ctx->ntfs_ino->mft_no);
767 break;
768 }
769 } else {
770 u32 min_len;
771 u16 mp_offset;
772
773 min_len = offsetof(struct attr_record, data.non_resident.initialized_size) +
774 sizeof(a->data.non_resident.initialized_size);
775 if (le32_to_cpu(a->length) < min_len)
776 break;
777
778 mp_offset = le16_to_cpu(a->data.non_resident.mapping_pairs_offset);
779 if (mp_offset < min_len ||
780 mp_offset > le32_to_cpu(a->length))
781 break;
782 }
783
784 /*
785 * The names match or @name not present and attribute is
786 * unnamed. If no @val specified, we have found the attribute
787 * and are done.
788 */
789 if (!val || a->non_resident)
790 return 0;
791 /* @val is present; compare values. */
792 else {
793 u32 value_length = le32_to_cpu(a->data.resident.value_length);
794 int rc;
795
796 rc = memcmp(val, (u8 *)a + le16_to_cpu(
797 a->data.resident.value_offset),
798 min_t(u32, val_len, value_length));
799 /*
800 * If @val collates before the current attribute's
801 * value, there is no matching attribute.
802 */
803 if (!rc) {
804 if (val_len == value_length)
805 return 0;
806 if (val_len < value_length)
807 return -ENOENT;
808 } else if (rc < 0)
809 return -ENOENT;
810 }
811 }
812 ntfs_error(vol->sb, "mft %#llx, type %#x is corrupt. Run chkdsk.",
813 (long long)ctx->ntfs_ino->mft_no, le32_to_cpu(type));
814 NVolSetErrors(vol);
815 return -EIO;
816 }
817
ntfs_attr_name_free(unsigned char ** name)818 void ntfs_attr_name_free(unsigned char **name)
819 {
820 if (*name) {
821 kfree(*name);
822 *name = NULL;
823 }
824 }
825
ntfs_attr_name_get(const struct ntfs_volume * vol,const __le16 * uname,const int uname_len)826 char *ntfs_attr_name_get(const struct ntfs_volume *vol, const __le16 *uname,
827 const int uname_len)
828 {
829 unsigned char *name = NULL;
830 int name_len;
831
832 name_len = ntfs_ucstonls(vol, uname, uname_len, &name, 0);
833 if (name_len < 0) {
834 ntfs_error(vol->sb, "ntfs_ucstonls error");
835 /* This function when returns -1, memory for name might
836 * be allocated. So lets free this memory.
837 */
838 ntfs_attr_name_free(&name);
839 return NULL;
840
841 } else if (name_len > 0)
842 return name;
843
844 ntfs_attr_name_free(&name);
845 return NULL;
846 }
847
load_attribute_list(struct ntfs_inode * base_ni,u8 * al_start,const s64 size)848 int load_attribute_list(struct ntfs_inode *base_ni, u8 *al_start, const s64 size)
849 {
850 struct inode *attr_vi = NULL;
851 u8 *al;
852 struct attr_list_entry *ale;
853
854 if (!al_start || size <= 0)
855 return -EINVAL;
856
857 attr_vi = ntfs_attr_iget(VFS_I(base_ni), AT_ATTRIBUTE_LIST, AT_UNNAMED, 0);
858 if (IS_ERR(attr_vi)) {
859 ntfs_error(base_ni->vol->sb,
860 "Failed to open an inode for Attribute list, mft = %llu",
861 base_ni->mft_no);
862 return PTR_ERR(attr_vi);
863 }
864
865 if (ntfs_inode_attr_pread(attr_vi, 0, size, al_start) != size) {
866 iput(attr_vi);
867 ntfs_error(base_ni->vol->sb,
868 "Failed to read attribute list, mft = %llu",
869 base_ni->mft_no);
870 return -EIO;
871 }
872 iput(attr_vi);
873
874 for (al = al_start; al < al_start + size; al += le16_to_cpu(ale->length)) {
875 ale = (struct attr_list_entry *)al;
876 if (ale->name_offset != sizeof(struct attr_list_entry))
877 break;
878 if (le16_to_cpu(ale->length) <= ale->name_offset + ale->name_length ||
879 al + le16_to_cpu(ale->length) > al_start + size)
880 break;
881 if (ale->type == AT_UNUSED)
882 break;
883 if (MSEQNO_LE(ale->mft_reference) == 0)
884 break;
885 }
886 if (al != al_start + size) {
887 ntfs_error(base_ni->vol->sb, "Corrupt attribute list, mft = %llu",
888 base_ni->mft_no);
889 return -EIO;
890 }
891 return 0;
892 }
893
894 /*
895 * ntfs_external_attr_find - find an attribute in the attribute list of an inode
896 * @type: attribute type to find
897 * @name: attribute name to find (optional, i.e. NULL means don't care)
898 * @name_len: attribute name length (only needed if @name present)
899 * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
900 * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only)
901 * @val: attribute value to find (optional, resident attributes only)
902 * @val_len: attribute value length
903 * @ctx: search context with mft record and attribute to search from
904 *
905 * You should not need to call this function directly. Use ntfs_attr_lookup()
906 * instead.
907 *
908 * Find an attribute by searching the attribute list for the corresponding
909 * attribute list entry. Having found the entry, map the mft record if the
910 * attribute is in a different mft record/inode, ntfs_attr_find() the attribute
911 * in there and return it.
912 *
913 * On first search @ctx->ntfs_ino must be the base mft record and @ctx must
914 * have been obtained from a call to ntfs_attr_get_search_ctx(). On subsequent
915 * calls @ctx->ntfs_ino can be any extent inode, too (@ctx->base_ntfs_ino is
916 * then the base inode).
917 *
918 * After finishing with the attribute/mft record you need to call
919 * ntfs_attr_put_search_ctx() to cleanup the search context (unmapping any
920 * mapped inodes, etc).
921 *
922 * If the attribute is found, ntfs_external_attr_find() returns 0 and
923 * @ctx->attr will point to the found attribute. @ctx->mrec will point to the
924 * mft record in which @ctx->attr is located and @ctx->al_entry will point to
925 * the attribute list entry for the attribute.
926 *
927 * If the attribute is not found, ntfs_external_attr_find() returns -ENOENT and
928 * @ctx->attr will point to the attribute in the base mft record before which
929 * the attribute being searched for would need to be inserted if such an action
930 * were to be desired. @ctx->mrec will point to the mft record in which
931 * @ctx->attr is located and @ctx->al_entry will point to the attribute list
932 * entry of the attribute before which the attribute being searched for would
933 * need to be inserted if such an action were to be desired.
934 *
935 * Thus to insert the not found attribute, one wants to add the attribute to
936 * @ctx->mrec (the base mft record) and if there is not enough space, the
937 * attribute should be placed in a newly allocated extent mft record. The
938 * attribute list entry for the inserted attribute should be inserted in the
939 * attribute list attribute at @ctx->al_entry.
940 *
941 * On actual error, ntfs_external_attr_find() returns -EIO. In this case
942 * @ctx->attr is undefined and in particular do not rely on it not changing.
943 */
ntfs_external_attr_find(const __le32 type,const __le16 * name,const u32 name_len,const u32 ic,const s64 lowest_vcn,const u8 * val,const u32 val_len,struct ntfs_attr_search_ctx * ctx)944 static int ntfs_external_attr_find(const __le32 type,
945 const __le16 *name, const u32 name_len,
946 const u32 ic, const s64 lowest_vcn,
947 const u8 *val, const u32 val_len, struct ntfs_attr_search_ctx *ctx)
948 {
949 struct ntfs_inode *base_ni = ctx->base_ntfs_ino, *ni = ctx->ntfs_ino;
950 struct ntfs_volume *vol;
951 struct attr_list_entry *al_entry, *next_al_entry;
952 u8 *al_start, *al_end;
953 struct attr_record *a;
954 __le16 *al_name;
955 u32 al_name_len;
956 u32 attr_len, mft_free_len;
957 bool is_first_search = false;
958 int err = 0;
959 static const char *es = " Unmount and run chkdsk.";
960
961 ntfs_debug("Entering for inode 0x%llx, type 0x%x.", ni->mft_no, type);
962 if (!base_ni) {
963 /* First call happens with the base mft record. */
964 base_ni = ctx->base_ntfs_ino = ctx->ntfs_ino;
965 ctx->base_mrec = ctx->mrec;
966 ctx->mapped_base_mrec = ctx->mapped_mrec;
967 }
968 if (ni == base_ni)
969 ctx->base_attr = ctx->attr;
970 if (type == AT_END)
971 goto not_found;
972 vol = base_ni->vol;
973 al_start = base_ni->attr_list;
974 al_end = al_start + base_ni->attr_list_size;
975 if (!ctx->al_entry) {
976 ctx->al_entry = (struct attr_list_entry *)al_start;
977 is_first_search = true;
978 }
979 /*
980 * Iterate over entries in attribute list starting at @ctx->al_entry,
981 * or the entry following that, if @ctx->is_first is 'true'.
982 */
983 if (ctx->is_first) {
984 al_entry = ctx->al_entry;
985 ctx->is_first = false;
986 /*
987 * If an enumeration and the first attribute is higher than
988 * the attribute list itself, need to return the attribute list
989 * attribute.
990 */
991 if ((type == AT_UNUSED) && is_first_search &&
992 le32_to_cpu(al_entry->type) >
993 le32_to_cpu(AT_ATTRIBUTE_LIST))
994 goto find_attr_list_attr;
995 } else {
996 /* Check for small entry */
997 if (((al_end - (u8 *)ctx->al_entry) <
998 (long)offsetof(struct attr_list_entry, name)) ||
999 (le16_to_cpu(ctx->al_entry->length) & 7) ||
1000 (le16_to_cpu(ctx->al_entry->length) < offsetof(struct attr_list_entry, name)))
1001 goto corrupt;
1002
1003 al_entry = (struct attr_list_entry *)((u8 *)ctx->al_entry +
1004 le16_to_cpu(ctx->al_entry->length));
1005
1006 if ((u8 *)al_entry == al_end)
1007 goto not_found;
1008
1009 /* Preliminary check for small entry */
1010 if ((al_end - (u8 *)al_entry) <
1011 (long)offsetof(struct attr_list_entry, name))
1012 goto corrupt;
1013
1014 /*
1015 * If this is an enumeration and the attribute list attribute
1016 * is the next one in the enumeration sequence, just return the
1017 * attribute list attribute from the base mft record as it is
1018 * not listed in the attribute list itself.
1019 */
1020 if ((type == AT_UNUSED) && le32_to_cpu(ctx->al_entry->type) <
1021 le32_to_cpu(AT_ATTRIBUTE_LIST) &&
1022 le32_to_cpu(al_entry->type) >
1023 le32_to_cpu(AT_ATTRIBUTE_LIST)) {
1024 find_attr_list_attr:
1025
1026 /* Check for bogus calls. */
1027 if (name || name_len || val || val_len || lowest_vcn)
1028 return -EINVAL;
1029
1030 /* We want the base record. */
1031 if (ctx->ntfs_ino != base_ni)
1032 unmap_mft_record(ctx->ntfs_ino);
1033 ctx->ntfs_ino = base_ni;
1034 ctx->mapped_mrec = ctx->mapped_base_mrec;
1035 ctx->mrec = ctx->base_mrec;
1036 ctx->is_first = true;
1037
1038 /* Sanity checks are performed elsewhere. */
1039 ctx->attr = (struct attr_record *)((u8 *)ctx->mrec +
1040 le16_to_cpu(ctx->mrec->attrs_offset));
1041
1042 /* Find the attribute list attribute. */
1043 err = ntfs_attr_find(AT_ATTRIBUTE_LIST, NULL, 0,
1044 IGNORE_CASE, NULL, 0, ctx);
1045
1046 /*
1047 * Setup the search context so the correct
1048 * attribute is returned next time round.
1049 */
1050 ctx->al_entry = al_entry;
1051 ctx->is_first = true;
1052
1053 /* Got it. Done. */
1054 if (!err)
1055 return 0;
1056
1057 /* Error! If other than not found return it. */
1058 if (err != -ENOENT)
1059 return err;
1060
1061 /* Not found?!? Absurd! */
1062 ntfs_error(ctx->ntfs_ino->vol->sb, "Attribute list wasn't found");
1063 return -EIO;
1064 }
1065 }
1066 for (;; al_entry = next_al_entry) {
1067 /* Out of bounds check. */
1068 if ((u8 *)al_entry < base_ni->attr_list ||
1069 (u8 *)al_entry > al_end)
1070 break; /* Inode is corrupt. */
1071 ctx->al_entry = al_entry;
1072 /* Catch the end of the attribute list. */
1073 if ((u8 *)al_entry == al_end)
1074 goto not_found;
1075
1076 if ((((u8 *)al_entry + offsetof(struct attr_list_entry, name)) > al_end) ||
1077 ((u8 *)al_entry + le16_to_cpu(al_entry->length) > al_end) ||
1078 (le16_to_cpu(al_entry->length) & 7) ||
1079 (le16_to_cpu(al_entry->length) <
1080 offsetof(struct attr_list_entry, name_length)) ||
1081 (al_entry->name_length && ((u8 *)al_entry + al_entry->name_offset +
1082 al_entry->name_length * sizeof(__le16)) > al_end))
1083 break; /* corrupt */
1084
1085 next_al_entry = (struct attr_list_entry *)((u8 *)al_entry +
1086 le16_to_cpu(al_entry->length));
1087 if (type != AT_UNUSED) {
1088 if (le32_to_cpu(al_entry->type) > le32_to_cpu(type))
1089 goto not_found;
1090 if (type != al_entry->type)
1091 continue;
1092 }
1093 /*
1094 * If @name is present, compare the two names. If @name is
1095 * missing, assume we want an unnamed attribute.
1096 */
1097 al_name_len = al_entry->name_length;
1098 al_name = (__le16 *)((u8 *)al_entry + al_entry->name_offset);
1099
1100 /*
1101 * If !@type we want the attribute represented by this
1102 * attribute list entry.
1103 */
1104 if (type == AT_UNUSED)
1105 goto is_enumeration;
1106
1107 if (!name || name == AT_UNNAMED) {
1108 if (al_name_len)
1109 goto not_found;
1110 } else if (!ntfs_are_names_equal(al_name, al_name_len, name,
1111 name_len, ic, vol->upcase, vol->upcase_len)) {
1112 register int rc;
1113
1114 rc = ntfs_collate_names(name, name_len, al_name,
1115 al_name_len, 1, IGNORE_CASE,
1116 vol->upcase, vol->upcase_len);
1117 /*
1118 * If @name collates before al_name, there is no
1119 * matching attribute.
1120 */
1121 if (rc == -1)
1122 goto not_found;
1123 /* If the strings are not equal, continue search. */
1124 if (rc)
1125 continue;
1126
1127 rc = ntfs_collate_names(name, name_len, al_name,
1128 al_name_len, 1, CASE_SENSITIVE,
1129 vol->upcase, vol->upcase_len);
1130 if (rc == -1)
1131 goto not_found;
1132 if (rc)
1133 continue;
1134 }
1135 /*
1136 * The names match or @name not present and attribute is
1137 * unnamed. Now check @lowest_vcn. Continue search if the
1138 * next attribute list entry still fits @lowest_vcn. Otherwise
1139 * we have reached the right one or the search has failed.
1140 */
1141 if (lowest_vcn && (u8 *)next_al_entry >= al_start &&
1142 (u8 *)next_al_entry + 6 < al_end &&
1143 (u8 *)next_al_entry + le16_to_cpu(
1144 next_al_entry->length) <= al_end &&
1145 le64_to_cpu(next_al_entry->lowest_vcn) <=
1146 lowest_vcn &&
1147 next_al_entry->type == al_entry->type &&
1148 next_al_entry->name_length == al_name_len &&
1149 ntfs_are_names_equal((__le16 *)((u8 *)
1150 next_al_entry +
1151 next_al_entry->name_offset),
1152 next_al_entry->name_length,
1153 al_name, al_name_len, CASE_SENSITIVE,
1154 vol->upcase, vol->upcase_len))
1155 continue;
1156
1157 is_enumeration:
1158 if (MREF_LE(al_entry->mft_reference) == ni->mft_no) {
1159 if (MSEQNO_LE(al_entry->mft_reference) != ni->seq_no) {
1160 ntfs_error(vol->sb,
1161 "Found stale mft reference in attribute list of base inode 0x%llx.%s",
1162 base_ni->mft_no, es);
1163 err = -EIO;
1164 break;
1165 }
1166 } else { /* Mft references do not match. */
1167 /* If there is a mapped record unmap it first. */
1168 if (ni != base_ni)
1169 unmap_extent_mft_record(ni);
1170 /* Do we want the base record back? */
1171 if (MREF_LE(al_entry->mft_reference) ==
1172 base_ni->mft_no) {
1173 ni = ctx->ntfs_ino = base_ni;
1174 ctx->mrec = ctx->base_mrec;
1175 ctx->mapped_mrec = ctx->mapped_base_mrec;
1176 } else {
1177 /* We want an extent record. */
1178 ctx->mrec = map_extent_mft_record(base_ni,
1179 le64_to_cpu(
1180 al_entry->mft_reference), &ni);
1181 if (IS_ERR(ctx->mrec)) {
1182 ntfs_error(vol->sb,
1183 "Failed to map extent mft record 0x%lx of base inode 0x%llx.%s",
1184 MREF_LE(al_entry->mft_reference),
1185 base_ni->mft_no, es);
1186 err = PTR_ERR(ctx->mrec);
1187 if (err == -ENOENT)
1188 err = -EIO;
1189 /* Cause @ctx to be sanitized below. */
1190 ni = NULL;
1191 break;
1192 }
1193 ctx->ntfs_ino = ni;
1194 ctx->mapped_mrec = true;
1195
1196 }
1197 }
1198 a = ctx->attr = (struct attr_record *)((u8 *)ctx->mrec +
1199 le16_to_cpu(ctx->mrec->attrs_offset));
1200 /*
1201 * ctx->vfs_ino, ctx->mrec, and ctx->attr now point to the
1202 * mft record containing the attribute represented by the
1203 * current al_entry.
1204 */
1205 /*
1206 * We could call into ntfs_attr_find() to find the right
1207 * attribute in this mft record but this would be less
1208 * efficient and not quite accurate as ntfs_attr_find() ignores
1209 * the attribute instance numbers for example which become
1210 * important when one plays with attribute lists. Also,
1211 * because a proper match has been found in the attribute list
1212 * entry above, the comparison can now be optimized. So it is
1213 * worth re-implementing a simplified ntfs_attr_find() here.
1214 */
1215 /*
1216 * Use a manual loop so we can still use break and continue
1217 * with the same meanings as above.
1218 */
1219 do_next_attr_loop:
1220 if ((u8 *)a < (u8 *)ctx->mrec ||
1221 (u8 *)a >= (u8 *)ctx->mrec + le32_to_cpu(ctx->mrec->bytes_allocated) ||
1222 (u8 *)a >= (u8 *)ctx->mrec + le32_to_cpu(ctx->mrec->bytes_in_use))
1223 break;
1224
1225 mft_free_len = le32_to_cpu(ctx->mrec->bytes_in_use) -
1226 ((u8 *)a - (u8 *)ctx->mrec);
1227 if (mft_free_len >= sizeof(a->type) && a->type == AT_END)
1228 continue;
1229
1230 attr_len = le32_to_cpu(a->length);
1231 if (!attr_len ||
1232 attr_len < offsetof(struct attr_record, data.resident.reserved) +
1233 sizeof(a->data.resident.reserved) ||
1234 attr_len > mft_free_len)
1235 break;
1236
1237 if (al_entry->instance != a->instance)
1238 goto do_next_attr;
1239 /*
1240 * If the type and/or the name are mismatched between the
1241 * attribute list entry and the attribute record, there is
1242 * corruption so we break and return error EIO.
1243 */
1244 if (al_entry->type != a->type)
1245 break;
1246 if (a->name_length && ((le16_to_cpu(a->name_offset) +
1247 a->name_length * sizeof(__le16)) > attr_len))
1248 break;
1249 if (!ntfs_are_names_equal((__le16 *)((u8 *)a +
1250 le16_to_cpu(a->name_offset)), a->name_length,
1251 al_name, al_name_len, CASE_SENSITIVE,
1252 vol->upcase, vol->upcase_len))
1253 break;
1254
1255 ctx->attr = a;
1256
1257 if (a->non_resident) {
1258 u32 min_len;
1259 u16 mp_offset;
1260
1261 min_len = offsetof(struct attr_record,
1262 data.non_resident.initialized_size) +
1263 sizeof(a->data.non_resident.initialized_size);
1264
1265 if (le32_to_cpu(a->length) < min_len)
1266 break;
1267
1268 mp_offset =
1269 le16_to_cpu(a->data.non_resident.mapping_pairs_offset);
1270 if (mp_offset < min_len || mp_offset > attr_len)
1271 break;
1272 }
1273
1274 /*
1275 * If no @val specified or @val specified and it matches, we
1276 * have found it!
1277 */
1278 if ((type == AT_UNUSED) || !val)
1279 goto attr_found;
1280 if (!a->non_resident) {
1281 u32 value_length = le32_to_cpu(a->data.resident.value_length);
1282 u16 value_offset = le16_to_cpu(a->data.resident.value_offset);
1283
1284 if (attr_len < offsetof(struct attr_record, data.resident.reserved) +
1285 sizeof(a->data.resident.reserved))
1286 break;
1287 if (value_length > attr_len || value_offset > attr_len - value_length)
1288 break;
1289
1290 value_length = ntfs_resident_attr_min_value_length(a->type);
1291 if (value_length && le32_to_cpu(a->data.resident.value_length) <
1292 value_length) {
1293 pr_err("Too small resident attribute value in MFT record %lld, type %#x\n",
1294 (long long)ctx->ntfs_ino->mft_no, a->type);
1295 break;
1296 }
1297 if (value_length == val_len &&
1298 !memcmp((u8 *)a + value_offset, val, val_len)) {
1299 attr_found:
1300 ntfs_debug("Done, found.");
1301 return 0;
1302 }
1303 }
1304 do_next_attr:
1305 /* Proceed to the next attribute in the current mft record. */
1306 a = (struct attr_record *)((u8 *)a + attr_len);
1307 goto do_next_attr_loop;
1308 }
1309
1310 corrupt:
1311 if (ni != base_ni) {
1312 if (ni)
1313 unmap_extent_mft_record(ni);
1314 ctx->ntfs_ino = base_ni;
1315 ctx->mrec = ctx->base_mrec;
1316 ctx->attr = ctx->base_attr;
1317 ctx->mapped_mrec = ctx->mapped_base_mrec;
1318 }
1319
1320 if (!err) {
1321 u64 mft_no = ctx->al_entry ? MREF_LE(ctx->al_entry->mft_reference) : 0;
1322 u32 type = ctx->al_entry ? le32_to_cpu(ctx->al_entry->type) : 0;
1323
1324 ntfs_error(vol->sb,
1325 "Base inode 0x%llx contains corrupt attribute, mft %#llx, type %#x. %s",
1326 (long long)base_ni->mft_no, (long long)mft_no, type,
1327 "Unmount and run chkdsk.");
1328 err = -EIO;
1329 }
1330
1331 if (err != -ENOMEM)
1332 NVolSetErrors(vol);
1333 return err;
1334 not_found:
1335 /*
1336 * If we were looking for AT_END, we reset the search context @ctx and
1337 * use ntfs_attr_find() to seek to the end of the base mft record.
1338 */
1339 if (type == AT_UNUSED || type == AT_END) {
1340 ntfs_attr_reinit_search_ctx(ctx);
1341 return ntfs_attr_find(AT_END, name, name_len, ic, val, val_len,
1342 ctx);
1343 }
1344 /*
1345 * The attribute was not found. Before we return, we want to ensure
1346 * @ctx->mrec and @ctx->attr indicate the position at which the
1347 * attribute should be inserted in the base mft record. Since we also
1348 * want to preserve @ctx->al_entry we cannot reinitialize the search
1349 * context using ntfs_attr_reinit_search_ctx() as this would set
1350 * @ctx->al_entry to NULL. Thus we do the necessary bits manually (see
1351 * ntfs_attr_init_search_ctx() below). Note, we _only_ preserve
1352 * @ctx->al_entry as the remaining fields (base_*) are identical to
1353 * their non base_ counterparts and we cannot set @ctx->base_attr
1354 * correctly yet as we do not know what @ctx->attr will be set to by
1355 * the call to ntfs_attr_find() below.
1356 */
1357 if (ni != base_ni)
1358 unmap_extent_mft_record(ni);
1359 ctx->mrec = ctx->base_mrec;
1360 ctx->attr = (struct attr_record *)((u8 *)ctx->mrec +
1361 le16_to_cpu(ctx->mrec->attrs_offset));
1362 ctx->is_first = true;
1363 ctx->ntfs_ino = base_ni;
1364 ctx->base_ntfs_ino = NULL;
1365 ctx->base_mrec = NULL;
1366 ctx->base_attr = NULL;
1367 ctx->mapped_mrec = ctx->mapped_base_mrec;
1368 /*
1369 * In case there are multiple matches in the base mft record, need to
1370 * keep enumerating until we get an attribute not found response (or
1371 * another error), otherwise we would keep returning the same attribute
1372 * over and over again and all programs using us for enumeration would
1373 * lock up in a tight loop.
1374 */
1375 do {
1376 err = ntfs_attr_find(type, name, name_len, ic, val, val_len,
1377 ctx);
1378 } while (!err);
1379 ntfs_debug("Done, not found.");
1380 return err;
1381 }
1382
1383 /*
1384 * ntfs_attr_lookup - find an attribute in an ntfs inode
1385 * @type: attribute type to find
1386 * @name: attribute name to find (optional, i.e. NULL means don't care)
1387 * @name_len: attribute name length (only needed if @name present)
1388 * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
1389 * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only)
1390 * @val: attribute value to find (optional, resident attributes only)
1391 * @val_len: attribute value length
1392 * @ctx: search context with mft record and attribute to search from
1393 *
1394 * Find an attribute in an ntfs inode. On first search @ctx->ntfs_ino must
1395 * be the base mft record and @ctx must have been obtained from a call to
1396 * ntfs_attr_get_search_ctx().
1397 *
1398 * This function transparently handles attribute lists and @ctx is used to
1399 * continue searches where they were left off at.
1400 *
1401 * After finishing with the attribute/mft record you need to call
1402 * ntfs_attr_put_search_ctx() to cleanup the search context (unmapping any
1403 * mapped inodes, etc).
1404 *
1405 * Return 0 if the search was successful and -errno if not.
1406 *
1407 * When 0, @ctx->attr is the found attribute and it is in mft record
1408 * @ctx->mrec. If an attribute list attribute is present, @ctx->al_entry is
1409 * the attribute list entry of the found attribute.
1410 *
1411 * When -ENOENT, @ctx->attr is the attribute which collates just after the
1412 * attribute being searched for, i.e. if one wants to add the attribute to the
1413 * mft record this is the correct place to insert it into. If an attribute
1414 * list attribute is present, @ctx->al_entry is the attribute list entry which
1415 * collates just after the attribute list entry of the attribute being searched
1416 * for, i.e. if one wants to add the attribute to the mft record this is the
1417 * correct place to insert its attribute list entry into.
1418 */
ntfs_attr_lookup(const __le32 type,const __le16 * name,const u32 name_len,const u32 ic,const s64 lowest_vcn,const u8 * val,const u32 val_len,struct ntfs_attr_search_ctx * ctx)1419 int ntfs_attr_lookup(const __le32 type, const __le16 *name,
1420 const u32 name_len, const u32 ic,
1421 const s64 lowest_vcn, const u8 *val, const u32 val_len,
1422 struct ntfs_attr_search_ctx *ctx)
1423 {
1424 struct ntfs_inode *base_ni;
1425
1426 ntfs_debug("Entering.");
1427 if (ctx->base_ntfs_ino)
1428 base_ni = ctx->base_ntfs_ino;
1429 else
1430 base_ni = ctx->ntfs_ino;
1431 /* Sanity check, just for debugging really. */
1432 if (!base_ni || !NInoAttrList(base_ni) || type == AT_ATTRIBUTE_LIST)
1433 return ntfs_attr_find(type, name, name_len, ic, val, val_len,
1434 ctx);
1435 return ntfs_external_attr_find(type, name, name_len, ic, lowest_vcn,
1436 val, val_len, ctx);
1437 }
1438
1439 /**
1440 * ntfs_attr_init_search_ctx - initialize an attribute search context
1441 * @ctx: attribute search context to initialize
1442 * @ni: ntfs inode with which to initialize the search context
1443 * @mrec: mft record with which to initialize the search context
1444 *
1445 * Initialize the attribute search context @ctx with @ni and @mrec.
1446 */
ntfs_attr_init_search_ctx(struct ntfs_attr_search_ctx * ctx,struct ntfs_inode * ni,struct mft_record * mrec)1447 static bool ntfs_attr_init_search_ctx(struct ntfs_attr_search_ctx *ctx,
1448 struct ntfs_inode *ni, struct mft_record *mrec)
1449 {
1450 if (!mrec) {
1451 mrec = map_mft_record(ni);
1452 if (IS_ERR(mrec))
1453 return false;
1454 ctx->mapped_mrec = true;
1455 } else {
1456 ctx->mapped_mrec = false;
1457 }
1458
1459 ctx->mrec = mrec;
1460 /* Sanity checks are performed elsewhere. */
1461 ctx->attr = (struct attr_record *)((u8 *)mrec + le16_to_cpu(mrec->attrs_offset));
1462 ctx->is_first = true;
1463 ctx->ntfs_ino = ni;
1464 ctx->al_entry = NULL;
1465 ctx->base_ntfs_ino = NULL;
1466 ctx->base_mrec = NULL;
1467 ctx->base_attr = NULL;
1468 ctx->mapped_base_mrec = false;
1469 return true;
1470 }
1471
1472 /*
1473 * ntfs_attr_reinit_search_ctx - reinitialize an attribute search context
1474 * @ctx: attribute search context to reinitialize
1475 *
1476 * Reinitialize the attribute search context @ctx, unmapping an associated
1477 * extent mft record if present, and initialize the search context again.
1478 *
1479 * This is used when a search for a new attribute is being started to reset
1480 * the search context to the beginning.
1481 */
ntfs_attr_reinit_search_ctx(struct ntfs_attr_search_ctx * ctx)1482 void ntfs_attr_reinit_search_ctx(struct ntfs_attr_search_ctx *ctx)
1483 {
1484 bool mapped_mrec;
1485
1486 if (likely(!ctx->base_ntfs_ino)) {
1487 /* No attribute list. */
1488 ctx->is_first = true;
1489 /* Sanity checks are performed elsewhere. */
1490 ctx->attr = (struct attr_record *)((u8 *)ctx->mrec +
1491 le16_to_cpu(ctx->mrec->attrs_offset));
1492 /*
1493 * This needs resetting due to ntfs_external_attr_find() which
1494 * can leave it set despite having zeroed ctx->base_ntfs_ino.
1495 */
1496 ctx->al_entry = NULL;
1497 return;
1498 } /* Attribute list. */
1499 if (ctx->ntfs_ino != ctx->base_ntfs_ino && ctx->ntfs_ino)
1500 unmap_extent_mft_record(ctx->ntfs_ino);
1501
1502 mapped_mrec = ctx->mapped_base_mrec;
1503 ntfs_attr_init_search_ctx(ctx, ctx->base_ntfs_ino, ctx->base_mrec);
1504 ctx->mapped_mrec = mapped_mrec;
1505 }
1506
1507 /*
1508 * ntfs_attr_get_search_ctx - allocate/initialize a new attribute search context
1509 * @ni: ntfs inode with which to initialize the search context
1510 * @mrec: mft record with which to initialize the search context
1511 *
1512 * Allocate a new attribute search context, initialize it with @ni and @mrec,
1513 * and return it. Return NULL if allocation failed.
1514 */
ntfs_attr_get_search_ctx(struct ntfs_inode * ni,struct mft_record * mrec)1515 struct ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(struct ntfs_inode *ni,
1516 struct mft_record *mrec)
1517 {
1518 struct ntfs_attr_search_ctx *ctx;
1519 bool init;
1520
1521 ctx = kmem_cache_alloc(ntfs_attr_ctx_cache, GFP_NOFS);
1522 if (ctx) {
1523 init = ntfs_attr_init_search_ctx(ctx, ni, mrec);
1524 if (init == false) {
1525 kmem_cache_free(ntfs_attr_ctx_cache, ctx);
1526 ctx = NULL;
1527 }
1528 }
1529
1530 return ctx;
1531 }
1532
1533 /*
1534 * ntfs_attr_put_search_ctx - release an attribute search context
1535 * @ctx: attribute search context to free
1536 *
1537 * Release the attribute search context @ctx, unmapping an associated extent
1538 * mft record if present.
1539 */
ntfs_attr_put_search_ctx(struct ntfs_attr_search_ctx * ctx)1540 void ntfs_attr_put_search_ctx(struct ntfs_attr_search_ctx *ctx)
1541 {
1542 if (ctx->mapped_mrec)
1543 unmap_mft_record(ctx->ntfs_ino);
1544
1545 if (ctx->mapped_base_mrec && ctx->base_ntfs_ino &&
1546 ctx->ntfs_ino != ctx->base_ntfs_ino)
1547 unmap_extent_mft_record(ctx->base_ntfs_ino);
1548 kmem_cache_free(ntfs_attr_ctx_cache, ctx);
1549 }
1550
1551 /*
1552 * ntfs_attr_find_in_attrdef - find an attribute in the $AttrDef system file
1553 * @vol: ntfs volume to which the attribute belongs
1554 * @type: attribute type which to find
1555 *
1556 * Search for the attribute definition record corresponding to the attribute
1557 * @type in the $AttrDef system file.
1558 *
1559 * Return the attribute type definition record if found and NULL if not found.
1560 */
ntfs_attr_find_in_attrdef(const struct ntfs_volume * vol,const __le32 type)1561 static struct attr_def *ntfs_attr_find_in_attrdef(const struct ntfs_volume *vol,
1562 const __le32 type)
1563 {
1564 struct attr_def *ad;
1565
1566 WARN_ON(!type);
1567 for (ad = vol->attrdef; (u8 *)ad - (u8 *)vol->attrdef <
1568 vol->attrdef_size && ad->type; ++ad) {
1569 /* We have not found it yet, carry on searching. */
1570 if (likely(le32_to_cpu(ad->type) < le32_to_cpu(type)))
1571 continue;
1572 /* We found the attribute; return it. */
1573 if (likely(ad->type == type))
1574 return ad;
1575 /* We have gone too far already. No point in continuing. */
1576 break;
1577 }
1578 /* Attribute not found. */
1579 ntfs_debug("Attribute type 0x%x not found in $AttrDef.",
1580 le32_to_cpu(type));
1581 return NULL;
1582 }
1583
1584 /*
1585 * ntfs_attr_size_bounds_check - check a size of an attribute type for validity
1586 * @vol: ntfs volume to which the attribute belongs
1587 * @type: attribute type which to check
1588 * @size: size which to check
1589 *
1590 * Check whether the @size in bytes is valid for an attribute of @type on the
1591 * ntfs volume @vol. This information is obtained from $AttrDef system file.
1592 */
ntfs_attr_size_bounds_check(const struct ntfs_volume * vol,const __le32 type,const s64 size)1593 int ntfs_attr_size_bounds_check(const struct ntfs_volume *vol, const __le32 type,
1594 const s64 size)
1595 {
1596 struct attr_def *ad;
1597
1598 if (size < 0)
1599 return -EINVAL;
1600
1601 /*
1602 * $ATTRIBUTE_LIST has a maximum size of 256kiB, but this is not
1603 * listed in $AttrDef.
1604 */
1605 if (unlikely(type == AT_ATTRIBUTE_LIST && size > 256 * 1024))
1606 return -ERANGE;
1607 /* Get the $AttrDef entry for the attribute @type. */
1608 ad = ntfs_attr_find_in_attrdef(vol, type);
1609 if (unlikely(!ad))
1610 return -ENOENT;
1611 /* Do the bounds check. */
1612 if (((le64_to_cpu(ad->min_size) > 0) &&
1613 size < le64_to_cpu(ad->min_size)) ||
1614 ((le64_to_cpu(ad->max_size) > 0) && size >
1615 le64_to_cpu(ad->max_size)))
1616 return -ERANGE;
1617 return 0;
1618 }
1619
1620 /*
1621 * ntfs_attr_can_be_non_resident - check if an attribute can be non-resident
1622 * @vol: ntfs volume to which the attribute belongs
1623 * @type: attribute type which to check
1624 *
1625 * Check whether the attribute of @type on the ntfs volume @vol is allowed to
1626 * be non-resident. This information is obtained from $AttrDef system file.
1627 */
ntfs_attr_can_be_non_resident(const struct ntfs_volume * vol,const __le32 type)1628 static int ntfs_attr_can_be_non_resident(const struct ntfs_volume *vol,
1629 const __le32 type)
1630 {
1631 struct attr_def *ad;
1632
1633 /* Find the attribute definition record in $AttrDef. */
1634 ad = ntfs_attr_find_in_attrdef(vol, type);
1635 if (unlikely(!ad))
1636 return -ENOENT;
1637 /* Check the flags and return the result. */
1638 if (ad->flags & ATTR_DEF_RESIDENT)
1639 return -EPERM;
1640 return 0;
1641 }
1642
1643 /*
1644 * ntfs_attr_can_be_resident - check if an attribute can be resident
1645 * @vol: ntfs volume to which the attribute belongs
1646 * @type: attribute type which to check
1647 *
1648 * Check whether the attribute of @type on the ntfs volume @vol is allowed to
1649 * be resident. This information is derived from our ntfs knowledge and may
1650 * not be completely accurate, especially when user defined attributes are
1651 * present. Basically we allow everything to be resident except for index
1652 * allocation and $EA attributes.
1653 *
1654 * Return 0 if the attribute is allowed to be non-resident and -EPERM if not.
1655 *
1656 * Warning: In the system file $MFT the attribute $Bitmap must be non-resident
1657 * otherwise windows will not boot (blue screen of death)! We cannot
1658 * check for this here as we do not know which inode's $Bitmap is
1659 * being asked about so the caller needs to special case this.
1660 */
ntfs_attr_can_be_resident(const struct ntfs_volume * vol,const __le32 type)1661 int ntfs_attr_can_be_resident(const struct ntfs_volume *vol, const __le32 type)
1662 {
1663 if (type == AT_INDEX_ALLOCATION)
1664 return -EPERM;
1665 return 0;
1666 }
1667
1668 /*
1669 * ntfs_attr_record_resize - resize an attribute record
1670 * @m: mft record containing attribute record
1671 * @a: attribute record to resize
1672 * @new_size: new size in bytes to which to resize the attribute record @a
1673 *
1674 * Resize the attribute record @a, i.e. the resident part of the attribute, in
1675 * the mft record @m to @new_size bytes.
1676 */
ntfs_attr_record_resize(struct mft_record * m,struct attr_record * a,u32 new_size)1677 int ntfs_attr_record_resize(struct mft_record *m, struct attr_record *a, u32 new_size)
1678 {
1679 u32 old_size, alloc_size, attr_size;
1680
1681 old_size = le32_to_cpu(m->bytes_in_use);
1682 alloc_size = le32_to_cpu(m->bytes_allocated);
1683 attr_size = le32_to_cpu(a->length);
1684
1685 ntfs_debug("Sizes: old=%u alloc=%u attr=%u new=%u\n",
1686 (unsigned int)old_size, (unsigned int)alloc_size,
1687 (unsigned int)attr_size, (unsigned int)new_size);
1688
1689 /* Align to 8 bytes if it is not already done. */
1690 if (new_size & 7)
1691 new_size = (new_size + 7) & ~7;
1692 /* If the actual attribute length has changed, move things around. */
1693 if (new_size != attr_size) {
1694 u32 new_muse = le32_to_cpu(m->bytes_in_use) -
1695 attr_size + new_size;
1696 /* Not enough space in this mft record. */
1697 if (new_muse > le32_to_cpu(m->bytes_allocated))
1698 return -ENOSPC;
1699
1700 if (a->type == AT_INDEX_ROOT && new_size > attr_size &&
1701 new_muse + 120 > alloc_size && old_size + 120 <= alloc_size) {
1702 ntfs_debug("Too big struct index_root (%u > %u)\n",
1703 new_muse, alloc_size);
1704 return -ENOSPC;
1705 }
1706
1707 /* Move attributes following @a to their new location. */
1708 memmove((u8 *)a + new_size, (u8 *)a + le32_to_cpu(a->length),
1709 le32_to_cpu(m->bytes_in_use) - ((u8 *)a -
1710 (u8 *)m) - attr_size);
1711 /* Adjust @m to reflect the change in used space. */
1712 m->bytes_in_use = cpu_to_le32(new_muse);
1713 /* Adjust @a to reflect the new size. */
1714 if (new_size >= offsetof(struct attr_record, length) + sizeof(a->length))
1715 a->length = cpu_to_le32(new_size);
1716 }
1717 return 0;
1718 }
1719
1720 /*
1721 * ntfs_resident_attr_value_resize - resize the value of a resident attribute
1722 * @m: mft record containing attribute record
1723 * @a: attribute record whose value to resize
1724 * @new_size: new size in bytes to which to resize the attribute value of @a
1725 *
1726 * Resize the value of the attribute @a in the mft record @m to @new_size bytes.
1727 * If the value is made bigger, the newly allocated space is cleared.
1728 */
ntfs_resident_attr_value_resize(struct mft_record * m,struct attr_record * a,const u32 new_size)1729 int ntfs_resident_attr_value_resize(struct mft_record *m, struct attr_record *a,
1730 const u32 new_size)
1731 {
1732 u32 old_size;
1733
1734 /* Resize the resident part of the attribute record. */
1735 if (ntfs_attr_record_resize(m, a,
1736 le16_to_cpu(a->data.resident.value_offset) + new_size))
1737 return -ENOSPC;
1738 /*
1739 * The resize succeeded! If we made the attribute value bigger, clear
1740 * the area between the old size and @new_size.
1741 */
1742 old_size = le32_to_cpu(a->data.resident.value_length);
1743 if (new_size > old_size)
1744 memset((u8 *)a + le16_to_cpu(a->data.resident.value_offset) +
1745 old_size, 0, new_size - old_size);
1746 /* Finally update the length of the attribute value. */
1747 a->data.resident.value_length = cpu_to_le32(new_size);
1748 return 0;
1749 }
1750
1751 /*
1752 * ntfs_attr_make_non_resident - convert a resident to a non-resident attribute
1753 * @ni: ntfs inode describing the attribute to convert
1754 * @data_size: size of the resident data to copy to the non-resident attribute
1755 *
1756 * Convert the resident ntfs attribute described by the ntfs inode @ni to a
1757 * non-resident one.
1758 *
1759 * @data_size must be equal to the attribute value size. This is needed since
1760 * we need to know the size before we can map the mft record and our callers
1761 * always know it. The reason we cannot simply read the size from the vfs
1762 * inode i_size is that this is not necessarily uptodate. This happens when
1763 * ntfs_attr_make_non_resident() is called in the ->truncate call path(s).
1764 */
ntfs_attr_make_non_resident(struct ntfs_inode * ni,const u32 data_size)1765 int ntfs_attr_make_non_resident(struct ntfs_inode *ni, const u32 data_size)
1766 {
1767 s64 new_size;
1768 struct inode *vi = VFS_I(ni);
1769 struct ntfs_volume *vol = ni->vol;
1770 struct ntfs_inode *base_ni;
1771 struct mft_record *m;
1772 struct attr_record *a;
1773 struct ntfs_attr_search_ctx *ctx;
1774 struct folio *folio;
1775 struct runlist_element *rl;
1776 unsigned long flags;
1777 int mp_size, mp_ofs, name_ofs, arec_size, err, err2;
1778 u32 attr_size;
1779 u8 old_res_attr_flags;
1780
1781 if (NInoNonResident(ni)) {
1782 ntfs_warning(vol->sb,
1783 "Trying to make non-resident attribute non-resident. Aborting...\n");
1784 return -EINVAL;
1785 }
1786
1787 /* Check that the attribute is allowed to be non-resident. */
1788 err = ntfs_attr_can_be_non_resident(vol, ni->type);
1789 if (unlikely(err)) {
1790 if (err == -EPERM)
1791 ntfs_debug("Attribute is not allowed to be non-resident.");
1792 else
1793 ntfs_debug("Attribute not defined on the NTFS volume!");
1794 return err;
1795 }
1796
1797 if (NInoEncrypted(ni))
1798 return -EIO;
1799
1800 if (!NInoAttr(ni))
1801 base_ni = ni;
1802 else
1803 base_ni = ni->ext.base_ntfs_ino;
1804 m = map_mft_record(base_ni);
1805 if (IS_ERR(m)) {
1806 err = PTR_ERR(m);
1807 m = NULL;
1808 ctx = NULL;
1809 goto err_out;
1810 }
1811 ctx = ntfs_attr_get_search_ctx(base_ni, m);
1812 if (unlikely(!ctx)) {
1813 err = -ENOMEM;
1814 goto err_out;
1815 }
1816 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1817 CASE_SENSITIVE, 0, NULL, 0, ctx);
1818 if (unlikely(err)) {
1819 if (err == -ENOENT)
1820 err = -EIO;
1821 goto err_out;
1822 }
1823 m = ctx->mrec;
1824 a = ctx->attr;
1825
1826 /*
1827 * The size needs to be aligned to a cluster boundary for allocation
1828 * purposes.
1829 */
1830 new_size = (data_size + vol->cluster_size - 1) &
1831 ~(vol->cluster_size - 1);
1832 if (new_size > 0) {
1833 if ((a->flags & ATTR_COMPRESSION_MASK) == ATTR_IS_COMPRESSED) {
1834 /* must allocate full compression blocks */
1835 new_size =
1836 ((new_size - 1) |
1837 ((1L << (STANDARD_COMPRESSION_UNIT +
1838 vol->cluster_size_bits)) - 1)) + 1;
1839 }
1840
1841 /*
1842 * Will need folio later and since folio lock nests
1843 * outside all ntfs locks, we need to get the folio now.
1844 */
1845 folio = __filemap_get_folio(vi->i_mapping, 0,
1846 FGP_CREAT | FGP_LOCK,
1847 mapping_gfp_mask(vi->i_mapping));
1848 if (IS_ERR(folio)) {
1849 err = -ENOMEM;
1850 goto err_out;
1851 }
1852
1853 /* Start by allocating clusters to hold the attribute value. */
1854 rl = ntfs_cluster_alloc(vol, 0,
1855 ntfs_bytes_to_cluster(vol, new_size),
1856 -1, DATA_ZONE, true, false, false);
1857 if (IS_ERR(rl)) {
1858 err = PTR_ERR(rl);
1859 ntfs_debug("Failed to allocate cluster%s, error code %i.",
1860 ntfs_bytes_to_cluster(vol, new_size) > 1 ? "s" : "",
1861 err);
1862 goto folio_err_out;
1863 }
1864 } else {
1865 rl = NULL;
1866 folio = NULL;
1867 }
1868
1869 down_write(&ni->runlist.lock);
1870 /* Determine the size of the mapping pairs array. */
1871 mp_size = ntfs_get_size_for_mapping_pairs(vol, rl, 0, -1, -1);
1872 if (unlikely(mp_size < 0)) {
1873 err = mp_size;
1874 ntfs_debug("Failed to get size for mapping pairs array, error code %i.\n", err);
1875 goto rl_err_out;
1876 }
1877
1878 if (NInoNonResident(ni) || a->non_resident) {
1879 err = -EIO;
1880 goto rl_err_out;
1881 }
1882
1883 /*
1884 * Calculate new offsets for the name and the mapping pairs array.
1885 */
1886 if (NInoSparse(ni) || NInoCompressed(ni))
1887 name_ofs = (offsetof(struct attr_record,
1888 data.non_resident.compressed_size) +
1889 sizeof(a->data.non_resident.compressed_size) +
1890 7) & ~7;
1891 else
1892 name_ofs = (offsetof(struct attr_record,
1893 data.non_resident.compressed_size) + 7) & ~7;
1894 mp_ofs = (name_ofs + a->name_length * sizeof(__le16) + 7) & ~7;
1895 /*
1896 * Determine the size of the resident part of the now non-resident
1897 * attribute record.
1898 */
1899 arec_size = (mp_ofs + mp_size + 7) & ~7;
1900 /*
1901 * If the folio is not uptodate bring it uptodate by copying from the
1902 * attribute value.
1903 */
1904 attr_size = le32_to_cpu(a->data.resident.value_length);
1905 WARN_ON(attr_size != data_size);
1906 if (folio && !folio_test_uptodate(folio)) {
1907 folio_fill_tail(folio, 0, (u8 *)a +
1908 le16_to_cpu(a->data.resident.value_offset),
1909 attr_size);
1910 folio_mark_uptodate(folio);
1911 }
1912
1913 /* Backup the attribute flag. */
1914 old_res_attr_flags = a->data.resident.flags;
1915 /* Resize the resident part of the attribute record. */
1916 err = ntfs_attr_record_resize(m, a, arec_size);
1917 if (unlikely(err))
1918 goto rl_err_out;
1919
1920 /*
1921 * Convert the resident part of the attribute record to describe a
1922 * non-resident attribute.
1923 */
1924 a->non_resident = 1;
1925 /* Move the attribute name if it exists and update the offset. */
1926 if (a->name_length)
1927 memmove((u8 *)a + name_ofs, (u8 *)a + le16_to_cpu(a->name_offset),
1928 a->name_length * sizeof(__le16));
1929 a->name_offset = cpu_to_le16(name_ofs);
1930 /* Setup the fields specific to non-resident attributes. */
1931 a->data.non_resident.lowest_vcn = 0;
1932 a->data.non_resident.highest_vcn =
1933 cpu_to_le64(ntfs_bytes_to_cluster(vol, new_size - 1));
1934 a->data.non_resident.mapping_pairs_offset = cpu_to_le16(mp_ofs);
1935 memset(&a->data.non_resident.reserved, 0,
1936 sizeof(a->data.non_resident.reserved));
1937 a->data.non_resident.allocated_size = cpu_to_le64(new_size);
1938 a->data.non_resident.data_size =
1939 a->data.non_resident.initialized_size =
1940 cpu_to_le64(attr_size);
1941 if (NInoSparse(ni) || NInoCompressed(ni)) {
1942 a->data.non_resident.compression_unit = 0;
1943 if (NInoCompressed(ni) || vol->major_ver < 3)
1944 a->data.non_resident.compression_unit = 4;
1945 a->data.non_resident.compressed_size =
1946 a->data.non_resident.allocated_size;
1947 } else
1948 a->data.non_resident.compression_unit = 0;
1949 /* Generate the mapping pairs array into the attribute record. */
1950 err = ntfs_mapping_pairs_build(vol, (u8 *)a + mp_ofs,
1951 arec_size - mp_ofs, rl, 0, -1, NULL, NULL, NULL);
1952 if (unlikely(err)) {
1953 ntfs_error(vol->sb, "Failed to build mapping pairs, error code %i.",
1954 err);
1955 goto undo_err_out;
1956 }
1957
1958 /* Setup the in-memory attribute structure to be non-resident. */
1959 ni->runlist.rl = rl;
1960 if (rl) {
1961 for (ni->runlist.count = 1; rl->length != 0; rl++)
1962 ni->runlist.count++;
1963 } else
1964 ni->runlist.count = 0;
1965 write_lock_irqsave(&ni->size_lock, flags);
1966 ni->allocated_size = new_size;
1967 if (NInoSparse(ni) || NInoCompressed(ni)) {
1968 ni->itype.compressed.size = ni->allocated_size;
1969 if (a->data.non_resident.compression_unit) {
1970 ni->itype.compressed.block_size = 1U <<
1971 (a->data.non_resident.compression_unit +
1972 vol->cluster_size_bits);
1973 ni->itype.compressed.block_size_bits =
1974 ffs(ni->itype.compressed.block_size) -
1975 1;
1976 ni->itype.compressed.block_clusters = 1U <<
1977 a->data.non_resident.compression_unit;
1978 } else {
1979 ni->itype.compressed.block_size = 0;
1980 ni->itype.compressed.block_size_bits = 0;
1981 ni->itype.compressed.block_clusters = 0;
1982 }
1983 vi->i_blocks = ni->itype.compressed.size >> 9;
1984 } else
1985 vi->i_blocks = ni->allocated_size >> 9;
1986 write_unlock_irqrestore(&ni->size_lock, flags);
1987 /*
1988 * This needs to be last since the address space operations ->read_folio
1989 * and ->writepage can run concurrently with us as they are not
1990 * serialized on i_mutex. Note, we are not allowed to fail once we flip
1991 * this switch, which is another reason to do this last.
1992 */
1993 NInoSetNonResident(ni);
1994 NInoSetFullyMapped(ni);
1995 /* Mark the mft record dirty, so it gets written back. */
1996 mark_mft_record_dirty(ctx->ntfs_ino);
1997 ntfs_attr_put_search_ctx(ctx);
1998 unmap_mft_record(base_ni);
1999 up_write(&ni->runlist.lock);
2000 if (folio) {
2001 iomap_dirty_folio(vi->i_mapping, folio);
2002 folio_unlock(folio);
2003 folio_put(folio);
2004 }
2005 ntfs_debug("Done.");
2006 return 0;
2007 undo_err_out:
2008 /* Convert the attribute back into a resident attribute. */
2009 a->non_resident = 0;
2010 /* Move the attribute name if it exists and update the offset. */
2011 name_ofs = (offsetof(struct attr_record, data.resident.reserved) +
2012 sizeof(a->data.resident.reserved) + 7) & ~7;
2013 if (a->name_length)
2014 memmove((u8 *)a + name_ofs, (u8 *)a + le16_to_cpu(a->name_offset),
2015 a->name_length * sizeof(__le16));
2016 mp_ofs = (name_ofs + a->name_length * sizeof(__le16) + 7) & ~7;
2017 a->name_offset = cpu_to_le16(name_ofs);
2018 arec_size = (mp_ofs + attr_size + 7) & ~7;
2019 /* Resize the resident part of the attribute record. */
2020 err2 = ntfs_attr_record_resize(m, a, arec_size);
2021 if (unlikely(err2)) {
2022 /*
2023 * This cannot happen (well if memory corruption is at work it
2024 * could happen in theory), but deal with it as well as we can.
2025 * If the old size is too small, truncate the attribute,
2026 * otherwise simply give it a larger allocated size.
2027 */
2028 arec_size = le32_to_cpu(a->length);
2029 if ((mp_ofs + attr_size) > arec_size) {
2030 err2 = attr_size;
2031 attr_size = arec_size - mp_ofs;
2032 ntfs_error(vol->sb,
2033 "Failed to undo partial resident to non-resident attribute conversion. Truncating inode 0x%llx, attribute type 0x%x from %i bytes to %i bytes to maintain metadata consistency. THIS MEANS YOU ARE LOSING %i BYTES DATA FROM THIS %s.",
2034 ni->mft_no,
2035 (unsigned int)le32_to_cpu(ni->type),
2036 err2, attr_size, err2 - attr_size,
2037 ((ni->type == AT_DATA) &&
2038 !ni->name_len) ? "FILE" : "ATTRIBUTE");
2039 write_lock_irqsave(&ni->size_lock, flags);
2040 ni->initialized_size = attr_size;
2041 i_size_write(vi, attr_size);
2042 write_unlock_irqrestore(&ni->size_lock, flags);
2043 }
2044 }
2045 /* Setup the fields specific to resident attributes. */
2046 a->data.resident.value_length = cpu_to_le32(attr_size);
2047 a->data.resident.value_offset = cpu_to_le16(mp_ofs);
2048 a->data.resident.flags = old_res_attr_flags;
2049 memset(&a->data.resident.reserved, 0,
2050 sizeof(a->data.resident.reserved));
2051 /* Copy the data from folio back to the attribute value. */
2052 if (folio)
2053 memcpy_from_folio((u8 *)a + mp_ofs, folio, 0, attr_size);
2054 /* Setup the allocated size in the ntfs inode in case it changed. */
2055 write_lock_irqsave(&ni->size_lock, flags);
2056 ni->allocated_size = arec_size - mp_ofs;
2057 write_unlock_irqrestore(&ni->size_lock, flags);
2058 /* Mark the mft record dirty, so it gets written back. */
2059 mark_mft_record_dirty(ctx->ntfs_ino);
2060 rl_err_out:
2061 up_write(&ni->runlist.lock);
2062 if (rl) {
2063 if (ntfs_cluster_free_from_rl(vol, rl) < 0) {
2064 ntfs_error(vol->sb,
2065 "Failed to release allocated cluster(s) in error code path. Run chkdsk to recover the lost cluster(s).");
2066 NVolSetErrors(vol);
2067 }
2068 kvfree(rl);
2069 folio_err_out:
2070 folio_unlock(folio);
2071 folio_put(folio);
2072 }
2073 err_out:
2074 if (ctx)
2075 ntfs_attr_put_search_ctx(ctx);
2076 if (m)
2077 unmap_mft_record(base_ni);
2078 ni->runlist.rl = NULL;
2079
2080 if (err == -EINVAL)
2081 err = -EIO;
2082 return err;
2083 }
2084
2085 /*
2086 * ntfs_attr_set - fill (a part of) an attribute with a byte
2087 * @ni: ntfs inode describing the attribute to fill
2088 * @ofs: offset inside the attribute at which to start to fill
2089 * @cnt: number of bytes to fill
2090 * @val: the unsigned 8-bit value with which to fill the attribute
2091 *
2092 * Fill @cnt bytes of the attribute described by the ntfs inode @ni starting at
2093 * byte offset @ofs inside the attribute with the constant byte @val.
2094 *
2095 * This function is effectively like memset() applied to an ntfs attribute.
2096 * Note thie function actually only operates on the page cache pages belonging
2097 * to the ntfs attribute and it marks them dirty after doing the memset().
2098 * Thus it relies on the vm dirty page write code paths to cause the modified
2099 * pages to be written to the mft record/disk.
2100 */
ntfs_attr_set(struct ntfs_inode * ni,s64 ofs,s64 cnt,const u8 val)2101 int ntfs_attr_set(struct ntfs_inode *ni, s64 ofs, s64 cnt, const u8 val)
2102 {
2103 struct address_space *mapping = VFS_I(ni)->i_mapping;
2104 struct folio *folio;
2105 pgoff_t index;
2106 u8 *addr;
2107 unsigned long offset;
2108 size_t attr_len;
2109 int ret = 0;
2110
2111 index = ofs >> PAGE_SHIFT;
2112 while (cnt) {
2113 folio = read_mapping_folio(mapping, index, NULL);
2114 if (IS_ERR(folio)) {
2115 ret = PTR_ERR(folio);
2116 ntfs_error(VFS_I(ni)->i_sb, "Failed to read a page %lu for attr %#x: %ld",
2117 index, ni->type, PTR_ERR(folio));
2118 break;
2119 }
2120
2121 offset = offset_in_folio(folio, ofs);
2122 attr_len = min_t(size_t, (size_t)cnt, folio_size(folio) - offset);
2123
2124 folio_lock(folio);
2125 addr = kmap_local_folio(folio, offset);
2126 memset(addr, val, attr_len);
2127 kunmap_local(addr);
2128
2129 folio_mark_dirty(folio);
2130 folio_unlock(folio);
2131 folio_put(folio);
2132
2133 ofs += attr_len;
2134 cnt -= attr_len;
2135 index++;
2136 cond_resched();
2137 }
2138
2139 return ret;
2140 }
2141
ntfs_attr_set_initialized_size(struct ntfs_inode * ni,loff_t new_size)2142 int ntfs_attr_set_initialized_size(struct ntfs_inode *ni, loff_t new_size)
2143 {
2144 struct ntfs_attr_search_ctx *ctx;
2145 int err = 0;
2146
2147 if (!NInoNonResident(ni))
2148 return -EINVAL;
2149
2150 ctx = ntfs_attr_get_search_ctx(ni, NULL);
2151 if (!ctx)
2152 return -ENOMEM;
2153
2154 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
2155 CASE_SENSITIVE, 0, NULL, 0, ctx);
2156 if (err)
2157 goto out_ctx;
2158
2159 ctx->attr->data.non_resident.initialized_size = cpu_to_le64(new_size);
2160 ni->initialized_size = new_size;
2161 mark_mft_record_dirty(ctx->ntfs_ino);
2162 out_ctx:
2163 ntfs_attr_put_search_ctx(ctx);
2164 return err;
2165 }
2166
2167 /*
2168 * ntfs_make_room_for_attr - make room for an attribute inside an mft record
2169 * @m: mft record
2170 * @pos: position at which to make space
2171 * @size: byte size to make available at this position
2172 *
2173 * @pos points to the attribute in front of which we want to make space.
2174 */
ntfs_make_room_for_attr(struct mft_record * m,u8 * pos,u32 size)2175 static int ntfs_make_room_for_attr(struct mft_record *m, u8 *pos, u32 size)
2176 {
2177 u32 biu;
2178
2179 ntfs_debug("Entering for pos 0x%x, size %u.\n",
2180 (int)(pos - (u8 *)m), (unsigned int) size);
2181
2182 /* Make size 8-byte alignment. */
2183 size = (size + 7) & ~7;
2184
2185 /* Rigorous consistency checks. */
2186 if (!m || !pos || pos < (u8 *)m) {
2187 pr_err("%s: pos=%p m=%p\n", __func__, pos, m);
2188 return -EINVAL;
2189 }
2190
2191 /* The -8 is for the attribute terminator. */
2192 if (pos - (u8 *)m > (int)le32_to_cpu(m->bytes_in_use) - 8)
2193 return -EINVAL;
2194 /* Nothing to do. */
2195 if (!size)
2196 return 0;
2197
2198 biu = le32_to_cpu(m->bytes_in_use);
2199 /* Do we have enough space? */
2200 if (biu + size > le32_to_cpu(m->bytes_allocated) ||
2201 pos + size > (u8 *)m + le32_to_cpu(m->bytes_allocated)) {
2202 ntfs_debug("No enough space in the MFT record\n");
2203 return -ENOSPC;
2204 }
2205 /* Move everything after pos to pos + size. */
2206 memmove(pos + size, pos, biu - (pos - (u8 *)m));
2207 /* Update mft record. */
2208 m->bytes_in_use = cpu_to_le32(biu + size);
2209 return 0;
2210 }
2211
2212 /*
2213 * ntfs_resident_attr_record_add - add resident attribute to inode
2214 * @ni: opened ntfs inode to which MFT record add attribute
2215 * @type: type of the new attribute
2216 * @name: name of the new attribute
2217 * @name_len: name length of the new attribute
2218 * @val: value of the new attribute
2219 * @size: size of new attribute (length of @val, if @val != NULL)
2220 * @flags: flags of the new attribute
2221 */
ntfs_resident_attr_record_add(struct ntfs_inode * ni,__le32 type,__le16 * name,u8 name_len,u8 * val,u32 size,__le16 flags)2222 int ntfs_resident_attr_record_add(struct ntfs_inode *ni, __le32 type,
2223 __le16 *name, u8 name_len, u8 *val, u32 size,
2224 __le16 flags)
2225 {
2226 struct ntfs_attr_search_ctx *ctx;
2227 u32 length;
2228 struct attr_record *a;
2229 struct mft_record *m;
2230 int err, offset;
2231 struct ntfs_inode *base_ni;
2232
2233 if (!ni || (!name && name_len))
2234 return -EINVAL;
2235
2236 ntfs_debug("Entering for inode 0x%llx, attr 0x%x, flags 0x%x.\n",
2237 (long long) ni->mft_no, (unsigned int) le32_to_cpu(type),
2238 (unsigned int) le16_to_cpu(flags));
2239
2240 err = ntfs_attr_can_be_resident(ni->vol, type);
2241 if (err) {
2242 if (err == -EPERM)
2243 ntfs_debug("Attribute can't be resident.\n");
2244 else
2245 ntfs_debug("ntfs_attr_can_be_resident failed.\n");
2246 return err;
2247 }
2248
2249 /* Locate place where record should be. */
2250 ctx = ntfs_attr_get_search_ctx(ni, NULL);
2251 if (!ctx) {
2252 ntfs_error(ni->vol->sb, "%s: Failed to get search context",
2253 __func__);
2254 return -ENOMEM;
2255 }
2256 /*
2257 * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for
2258 * attribute in @ni->mrec, not any extent inode in case if @ni is base
2259 * file record.
2260 */
2261 err = ntfs_attr_find(type, name, name_len, CASE_SENSITIVE, val, size, ctx);
2262 if (!err) {
2263 err = -EEXIST;
2264 ntfs_debug("Attribute already present.\n");
2265 goto put_err_out;
2266 }
2267 if (err != -ENOENT) {
2268 err = -EIO;
2269 goto put_err_out;
2270 }
2271 a = ctx->attr;
2272 m = ctx->mrec;
2273
2274 /* Make room for attribute. */
2275 length = offsetof(struct attr_record, data.resident.reserved) +
2276 sizeof(a->data.resident.reserved) +
2277 ((name_len * sizeof(__le16) + 7) & ~7) +
2278 ((size + 7) & ~7);
2279 err = ntfs_make_room_for_attr(ctx->mrec, (u8 *) ctx->attr, length);
2280 if (err) {
2281 ntfs_debug("Failed to make room for attribute.\n");
2282 goto put_err_out;
2283 }
2284
2285 /* Setup record fields. */
2286 offset = ((u8 *)a - (u8 *)m);
2287 a->type = type;
2288 a->length = cpu_to_le32(length);
2289 a->non_resident = 0;
2290 a->name_length = name_len;
2291 a->name_offset =
2292 name_len ? cpu_to_le16((offsetof(struct attr_record, data.resident.reserved) +
2293 sizeof(a->data.resident.reserved))) : cpu_to_le16(0);
2294
2295 a->flags = flags;
2296 a->instance = m->next_attr_instance;
2297 a->data.resident.value_length = cpu_to_le32(size);
2298 a->data.resident.value_offset = cpu_to_le16(length - ((size + 7) & ~7));
2299 if (val)
2300 memcpy((u8 *)a + le16_to_cpu(a->data.resident.value_offset), val, size);
2301 else
2302 memset((u8 *)a + le16_to_cpu(a->data.resident.value_offset), 0, size);
2303 if (type == AT_FILE_NAME)
2304 a->data.resident.flags = RESIDENT_ATTR_IS_INDEXED;
2305 else
2306 a->data.resident.flags = 0;
2307 if (name_len)
2308 memcpy((u8 *)a + le16_to_cpu(a->name_offset),
2309 name, sizeof(__le16) * name_len);
2310 m->next_attr_instance =
2311 cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff);
2312 if (ni->nr_extents == -1)
2313 base_ni = ni->ext.base_ntfs_ino;
2314 else
2315 base_ni = ni;
2316 if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) {
2317 err = ntfs_attrlist_entry_add(ni, a);
2318 if (err) {
2319 ntfs_attr_record_resize(m, a, 0);
2320 mark_mft_record_dirty(ctx->ntfs_ino);
2321 ntfs_debug("Failed add attribute entry to ATTRIBUTE_LIST.\n");
2322 goto put_err_out;
2323 }
2324 }
2325 mark_mft_record_dirty(ni);
2326 ntfs_attr_put_search_ctx(ctx);
2327 return offset;
2328 put_err_out:
2329 ntfs_attr_put_search_ctx(ctx);
2330 return -EIO;
2331 }
2332
2333 /*
2334 * ntfs_non_resident_attr_record_add - add extent of non-resident attribute
2335 * @ni: opened ntfs inode to which MFT record add attribute
2336 * @type: type of the new attribute extent
2337 * @name: name of the new attribute extent
2338 * @name_len: name length of the new attribute extent
2339 * @lowest_vcn: lowest vcn of the new attribute extent
2340 * @dataruns_size: dataruns size of the new attribute extent
2341 * @flags: flags of the new attribute extent
2342 */
ntfs_non_resident_attr_record_add(struct ntfs_inode * ni,__le32 type,__le16 * name,u8 name_len,s64 lowest_vcn,int dataruns_size,__le16 flags)2343 static int ntfs_non_resident_attr_record_add(struct ntfs_inode *ni, __le32 type,
2344 __le16 *name, u8 name_len, s64 lowest_vcn, int dataruns_size,
2345 __le16 flags)
2346 {
2347 struct ntfs_attr_search_ctx *ctx;
2348 u32 length;
2349 struct attr_record *a;
2350 struct mft_record *m;
2351 struct ntfs_inode *base_ni;
2352 int err, offset;
2353
2354 if (!ni || dataruns_size <= 0 || (!name && name_len))
2355 return -EINVAL;
2356
2357 ntfs_debug("Entering for inode 0x%llx, attr 0x%x, lowest_vcn %lld, dataruns_size %d, flags 0x%x.\n",
2358 (long long) ni->mft_no, (unsigned int) le32_to_cpu(type),
2359 (long long) lowest_vcn, dataruns_size,
2360 (unsigned int) le16_to_cpu(flags));
2361
2362 err = ntfs_attr_can_be_non_resident(ni->vol, type);
2363 if (err) {
2364 if (err == -EPERM)
2365 pr_err("Attribute can't be non resident\n");
2366 else
2367 pr_err("ntfs_attr_can_be_non_resident failed\n");
2368 return err;
2369 }
2370
2371 /* Locate place where record should be. */
2372 ctx = ntfs_attr_get_search_ctx(ni, NULL);
2373 if (!ctx) {
2374 pr_err("%s: Failed to get search context\n", __func__);
2375 return -ENOMEM;
2376 }
2377 /*
2378 * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for
2379 * attribute in @ni->mrec, not any extent inode in case if @ni is base
2380 * file record.
2381 */
2382 err = ntfs_attr_find(type, name, name_len, CASE_SENSITIVE, NULL, 0, ctx);
2383 if (!err) {
2384 err = -EEXIST;
2385 pr_err("Attribute 0x%x already present\n", type);
2386 goto put_err_out;
2387 }
2388 if (err != -ENOENT) {
2389 pr_err("ntfs_attr_find failed\n");
2390 err = -EIO;
2391 goto put_err_out;
2392 }
2393 a = ctx->attr;
2394 m = ctx->mrec;
2395
2396 /* Make room for attribute. */
2397 dataruns_size = (dataruns_size + 7) & ~7;
2398 length = offsetof(struct attr_record, data.non_resident.compressed_size) +
2399 ((sizeof(__le16) * name_len + 7) & ~7) + dataruns_size +
2400 ((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ?
2401 sizeof(a->data.non_resident.compressed_size) : 0);
2402 err = ntfs_make_room_for_attr(ctx->mrec, (u8 *) ctx->attr, length);
2403 if (err) {
2404 pr_err("Failed to make room for attribute\n");
2405 goto put_err_out;
2406 }
2407
2408 /* Setup record fields. */
2409 a->type = type;
2410 a->length = cpu_to_le32(length);
2411 a->non_resident = 1;
2412 a->name_length = name_len;
2413 a->name_offset = cpu_to_le16(offsetof(struct attr_record,
2414 data.non_resident.compressed_size) +
2415 ((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ?
2416 sizeof(a->data.non_resident.compressed_size) : 0));
2417 a->flags = flags;
2418 a->instance = m->next_attr_instance;
2419 a->data.non_resident.lowest_vcn = cpu_to_le64(lowest_vcn);
2420 a->data.non_resident.mapping_pairs_offset = cpu_to_le16(length - dataruns_size);
2421 a->data.non_resident.compression_unit =
2422 (flags & ATTR_IS_COMPRESSED) ? STANDARD_COMPRESSION_UNIT : 0;
2423 /* If @lowest_vcn == 0, than setup empty attribute. */
2424 if (!lowest_vcn) {
2425 a->data.non_resident.highest_vcn = cpu_to_le64(-1);
2426 a->data.non_resident.allocated_size = 0;
2427 a->data.non_resident.data_size = 0;
2428 a->data.non_resident.initialized_size = 0;
2429 /* Set empty mapping pairs. */
2430 *((u8 *)a + le16_to_cpu(a->data.non_resident.mapping_pairs_offset)) = 0;
2431 }
2432 if (name_len)
2433 memcpy((u8 *)a + le16_to_cpu(a->name_offset),
2434 name, sizeof(__le16) * name_len);
2435 m->next_attr_instance =
2436 cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff);
2437 if (ni->nr_extents == -1)
2438 base_ni = ni->ext.base_ntfs_ino;
2439 else
2440 base_ni = ni;
2441 if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) {
2442 err = ntfs_attrlist_entry_add(ni, a);
2443 if (err) {
2444 pr_err("Failed add attr entry to attrlist\n");
2445 ntfs_attr_record_resize(m, a, 0);
2446 goto put_err_out;
2447 }
2448 }
2449 mark_mft_record_dirty(ni);
2450 /*
2451 * Locate offset from start of the MFT record where new attribute is
2452 * placed. We need relookup it, because record maybe moved during
2453 * update of attribute list.
2454 */
2455 ntfs_attr_reinit_search_ctx(ctx);
2456 err = ntfs_attr_lookup(type, name, name_len, CASE_SENSITIVE,
2457 lowest_vcn, NULL, 0, ctx);
2458 if (err) {
2459 pr_err("%s: attribute lookup failed\n", __func__);
2460 ntfs_attr_put_search_ctx(ctx);
2461 return err;
2462
2463 }
2464 offset = (u8 *)ctx->attr - (u8 *)ctx->mrec;
2465 ntfs_attr_put_search_ctx(ctx);
2466 return offset;
2467 put_err_out:
2468 ntfs_attr_put_search_ctx(ctx);
2469 return -1;
2470 }
2471
2472 /*
2473 * ntfs_attr_record_rm - remove attribute extent
2474 * @ctx: search context describing the attribute which should be removed
2475 *
2476 * If this function succeed, user should reinit search context if he/she wants
2477 * use it anymore.
2478 */
ntfs_attr_record_rm(struct ntfs_attr_search_ctx * ctx)2479 int ntfs_attr_record_rm(struct ntfs_attr_search_ctx *ctx)
2480 {
2481 struct ntfs_inode *base_ni, *ni;
2482 __le32 type;
2483 int err;
2484
2485 if (!ctx || !ctx->ntfs_ino || !ctx->mrec || !ctx->attr)
2486 return -EINVAL;
2487
2488 ntfs_debug("Entering for inode 0x%llx, attr 0x%x.\n",
2489 (long long) ctx->ntfs_ino->mft_no,
2490 (unsigned int) le32_to_cpu(ctx->attr->type));
2491 type = ctx->attr->type;
2492 ni = ctx->ntfs_ino;
2493 if (ctx->base_ntfs_ino)
2494 base_ni = ctx->base_ntfs_ino;
2495 else
2496 base_ni = ctx->ntfs_ino;
2497
2498 /* Remove attribute itself. */
2499 if (ntfs_attr_record_resize(ctx->mrec, ctx->attr, 0)) {
2500 ntfs_debug("Couldn't remove attribute record. Bug or damaged MFT record.\n");
2501 return -EIO;
2502 }
2503 mark_mft_record_dirty(ni);
2504
2505 /*
2506 * Remove record from $ATTRIBUTE_LIST if present and we don't want
2507 * delete $ATTRIBUTE_LIST itself.
2508 */
2509 if (NInoAttrList(base_ni) && type != AT_ATTRIBUTE_LIST) {
2510 err = ntfs_attrlist_entry_rm(ctx);
2511 if (err) {
2512 ntfs_debug("Couldn't delete record from $ATTRIBUTE_LIST.\n");
2513 return err;
2514 }
2515 }
2516
2517 /* Post $ATTRIBUTE_LIST delete setup. */
2518 if (type == AT_ATTRIBUTE_LIST) {
2519 if (NInoAttrList(base_ni) && base_ni->attr_list)
2520 kvfree(base_ni->attr_list);
2521 base_ni->attr_list = NULL;
2522 NInoClearAttrList(base_ni);
2523 }
2524
2525 /* Free MFT record, if it doesn't contain attributes. */
2526 if (le32_to_cpu(ctx->mrec->bytes_in_use) -
2527 le16_to_cpu(ctx->mrec->attrs_offset) == 8) {
2528 if (ntfs_mft_record_free(ni->vol, ni)) {
2529 ntfs_debug("Couldn't free MFT record.\n");
2530 return -EIO;
2531 }
2532 /* Remove done if we freed base inode. */
2533 if (ni == base_ni)
2534 return 0;
2535 ntfs_inode_close(ni);
2536 ctx->ntfs_ino = ni = NULL;
2537 }
2538
2539 if (type == AT_ATTRIBUTE_LIST || !NInoAttrList(base_ni))
2540 return 0;
2541
2542 /* Remove attribute list if we don't need it any more. */
2543 if (!ntfs_attrlist_need(base_ni)) {
2544 struct ntfs_attr na;
2545 struct inode *attr_vi;
2546
2547 ntfs_attr_reinit_search_ctx(ctx);
2548 if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, NULL, 0, CASE_SENSITIVE,
2549 0, NULL, 0, ctx)) {
2550 ntfs_debug("Couldn't find attribute list. Succeed anyway.\n");
2551 return 0;
2552 }
2553 /* Deallocate clusters. */
2554 if (ctx->attr->non_resident) {
2555 struct runlist_element *al_rl;
2556 size_t new_rl_count;
2557
2558 al_rl = ntfs_mapping_pairs_decompress(base_ni->vol,
2559 ctx->attr, NULL, &new_rl_count);
2560 if (IS_ERR(al_rl)) {
2561 ntfs_debug("Couldn't decompress attribute list runlist. Succeed anyway.\n");
2562 return 0;
2563 }
2564 if (ntfs_cluster_free_from_rl(base_ni->vol, al_rl))
2565 ntfs_debug("Leaking clusters! Run chkdsk. Couldn't free clusters from attribute list runlist.\n");
2566 kvfree(al_rl);
2567 }
2568 /* Remove attribute record itself. */
2569 if (ntfs_attr_record_rm(ctx)) {
2570 ntfs_debug("Couldn't remove attribute list. Succeed anyway.\n");
2571 return 0;
2572 }
2573
2574 na.mft_no = VFS_I(base_ni)->i_ino;
2575 na.type = AT_ATTRIBUTE_LIST;
2576 na.name = NULL;
2577 na.name_len = 0;
2578
2579 attr_vi = ilookup5(VFS_I(base_ni)->i_sb, VFS_I(base_ni)->i_ino,
2580 ntfs_test_inode, &na);
2581 if (attr_vi) {
2582 clear_nlink(attr_vi);
2583 iput(attr_vi);
2584 }
2585
2586 }
2587 return 0;
2588 }
2589
2590 /*
2591 * ntfs_attr_add - add attribute to inode
2592 * @ni: opened ntfs inode to which add attribute
2593 * @type: type of the new attribute
2594 * @name: name in unicode of the new attribute
2595 * @name_len: name length in unicode characters of the new attribute
2596 * @val: value of new attribute
2597 * @size: size of the new attribute / length of @val (if specified)
2598 *
2599 * @val should always be specified for always resident attributes (eg. FILE_NAME
2600 * attribute), for attributes that can become non-resident @val can be NULL
2601 * (eg. DATA attribute). @size can be specified even if @val is NULL, in this
2602 * case data size will be equal to @size and initialized size will be equal
2603 * to 0.
2604 *
2605 * If inode haven't got enough space to add attribute, add attribute to one of
2606 * it extents, if no extents present or no one of them have enough space, than
2607 * allocate new extent and add attribute to it.
2608 *
2609 * If on one of this steps attribute list is needed but not present, than it is
2610 * added transparently to caller. So, this function should not be called with
2611 * @type == AT_ATTRIBUTE_LIST, if you really need to add attribute list call
2612 * ntfs_inode_add_attrlist instead.
2613 *
2614 * On success return 0. On error return -1 with errno set to the error code.
2615 */
ntfs_attr_add(struct ntfs_inode * ni,__le32 type,__le16 * name,u8 name_len,u8 * val,s64 size)2616 int ntfs_attr_add(struct ntfs_inode *ni, __le32 type,
2617 __le16 *name, u8 name_len, u8 *val, s64 size)
2618 {
2619 struct super_block *sb;
2620 u32 attr_rec_size;
2621 int err, i, offset;
2622 bool is_resident;
2623 bool can_be_non_resident = false;
2624 struct ntfs_inode *attr_ni;
2625 struct inode *attr_vi;
2626 struct mft_record *ni_mrec;
2627
2628 if (!ni || size < 0 || type == AT_ATTRIBUTE_LIST)
2629 return -EINVAL;
2630
2631 ntfs_debug("Entering for inode 0x%llx, attr %x, size %lld.\n",
2632 (long long) ni->mft_no, type, size);
2633
2634 if (ni->nr_extents == -1)
2635 ni = ni->ext.base_ntfs_ino;
2636
2637 /* Check the attribute type and the size. */
2638 err = ntfs_attr_size_bounds_check(ni->vol, type, size);
2639 if (err) {
2640 if (err == -ENOENT)
2641 err = -EIO;
2642 return err;
2643 }
2644
2645 sb = ni->vol->sb;
2646 /* Sanity checks for always resident attributes. */
2647 err = ntfs_attr_can_be_non_resident(ni->vol, type);
2648 if (err) {
2649 if (err != -EPERM) {
2650 ntfs_error(sb, "ntfs_attr_can_be_non_resident failed");
2651 goto err_out;
2652 }
2653 /* @val is mandatory. */
2654 if (!val) {
2655 ntfs_error(sb,
2656 "val is mandatory for always resident attributes");
2657 return -EINVAL;
2658 }
2659 if (size > ni->vol->mft_record_size) {
2660 ntfs_error(sb, "Attribute is too big");
2661 return -ERANGE;
2662 }
2663 } else
2664 can_be_non_resident = true;
2665
2666 /*
2667 * Determine resident or not will be new attribute. We add 8 to size in
2668 * non resident case for mapping pairs.
2669 */
2670 err = ntfs_attr_can_be_resident(ni->vol, type);
2671 if (!err) {
2672 is_resident = true;
2673 } else {
2674 if (err != -EPERM) {
2675 ntfs_error(sb, "ntfs_attr_can_be_resident failed");
2676 goto err_out;
2677 }
2678 is_resident = false;
2679 }
2680
2681 /* Calculate attribute record size. */
2682 if (is_resident)
2683 attr_rec_size = offsetof(struct attr_record, data.resident.reserved) +
2684 1 +
2685 ((name_len * sizeof(__le16) + 7) & ~7) +
2686 ((size + 7) & ~7);
2687 else
2688 attr_rec_size = offsetof(struct attr_record, data.non_resident.compressed_size) +
2689 ((name_len * sizeof(__le16) + 7) & ~7) + 8;
2690
2691 /*
2692 * If we have enough free space for the new attribute in the base MFT
2693 * record, then add attribute to it.
2694 */
2695 retry:
2696 ni_mrec = map_mft_record(ni);
2697 if (IS_ERR(ni_mrec)) {
2698 err = -EIO;
2699 goto err_out;
2700 }
2701
2702 if (le32_to_cpu(ni_mrec->bytes_allocated) -
2703 le32_to_cpu(ni_mrec->bytes_in_use) >= attr_rec_size) {
2704 attr_ni = ni;
2705 unmap_mft_record(ni);
2706 goto add_attr_record;
2707 }
2708 unmap_mft_record(ni);
2709
2710 /* Try to add to extent inodes. */
2711 err = ntfs_inode_attach_all_extents(ni);
2712 if (err) {
2713 ntfs_error(sb, "Failed to attach all extents to inode");
2714 goto err_out;
2715 }
2716
2717 for (i = 0; i < ni->nr_extents; i++) {
2718 attr_ni = ni->ext.extent_ntfs_inos[i];
2719 ni_mrec = map_mft_record(attr_ni);
2720 if (IS_ERR(ni_mrec)) {
2721 err = -EIO;
2722 goto err_out;
2723 }
2724
2725 if (le32_to_cpu(ni_mrec->bytes_allocated) -
2726 le32_to_cpu(ni_mrec->bytes_in_use) >=
2727 attr_rec_size) {
2728 unmap_mft_record(attr_ni);
2729 goto add_attr_record;
2730 }
2731 unmap_mft_record(attr_ni);
2732 }
2733
2734 /* There is no extent that contain enough space for new attribute. */
2735 if (!NInoAttrList(ni)) {
2736 /* Add attribute list not present, add it and retry. */
2737 err = ntfs_inode_add_attrlist(ni);
2738 if (err) {
2739 ntfs_error(sb, "Failed to add attribute list");
2740 goto err_out;
2741 }
2742 goto retry;
2743 }
2744
2745 attr_ni = NULL;
2746 /* Allocate new extent. */
2747 err = ntfs_mft_record_alloc(ni->vol, 0, &attr_ni, ni, NULL);
2748 if (err) {
2749 ntfs_error(sb, "Failed to allocate extent record");
2750 goto err_out;
2751 }
2752 unmap_mft_record(attr_ni);
2753
2754 add_attr_record:
2755 if (is_resident) {
2756 /* Add resident attribute. */
2757 offset = ntfs_resident_attr_record_add(attr_ni, type, name,
2758 name_len, val, size, 0);
2759 if (offset < 0) {
2760 if (offset == -ENOSPC && can_be_non_resident)
2761 goto add_non_resident;
2762 err = offset;
2763 ntfs_error(sb, "Failed to add resident attribute");
2764 goto free_err_out;
2765 }
2766 return 0;
2767 }
2768
2769 add_non_resident:
2770 /* Add non resident attribute. */
2771 offset = ntfs_non_resident_attr_record_add(attr_ni, type, name,
2772 name_len, 0, 8, 0);
2773 if (offset < 0) {
2774 err = offset;
2775 ntfs_error(sb, "Failed to add non resident attribute");
2776 goto free_err_out;
2777 }
2778
2779 /* If @size == 0, we are done. */
2780 if (!size)
2781 return 0;
2782
2783 /* Open new attribute and resize it. */
2784 attr_vi = ntfs_attr_iget(VFS_I(ni), type, name, name_len);
2785 if (IS_ERR(attr_vi)) {
2786 err = PTR_ERR(attr_vi);
2787 ntfs_error(sb, "Failed to open just added attribute");
2788 goto rm_attr_err_out;
2789 }
2790 attr_ni = NTFS_I(attr_vi);
2791
2792 /* Resize and set attribute value. */
2793 if (ntfs_attr_truncate(attr_ni, size) ||
2794 (val && (ntfs_inode_attr_pwrite(attr_vi, 0, size, val, false) != size))) {
2795 err = -EIO;
2796 ntfs_error(sb, "Failed to initialize just added attribute");
2797 if (ntfs_attr_rm(attr_ni))
2798 ntfs_error(sb, "Failed to remove just added attribute");
2799 iput(attr_vi);
2800 goto err_out;
2801 }
2802 iput(attr_vi);
2803 return 0;
2804
2805 rm_attr_err_out:
2806 /* Remove just added attribute. */
2807 ni_mrec = map_mft_record(attr_ni);
2808 if (!IS_ERR(ni_mrec)) {
2809 if (ntfs_attr_record_resize(ni_mrec,
2810 (struct attr_record *)((u8 *)ni_mrec + offset), 0))
2811 ntfs_error(sb, "Failed to remove just added attribute #2");
2812 unmap_mft_record(attr_ni);
2813 } else
2814 pr_err("EIO when try to remove new added attr\n");
2815
2816 free_err_out:
2817 /* Free MFT record, if it doesn't contain attributes. */
2818 ni_mrec = map_mft_record(attr_ni);
2819 if (!IS_ERR(ni_mrec)) {
2820 int attr_size;
2821
2822 attr_size = le32_to_cpu(ni_mrec->bytes_in_use) -
2823 le16_to_cpu(ni_mrec->attrs_offset);
2824 unmap_mft_record(attr_ni);
2825 if (attr_size == 8) {
2826 if (ntfs_mft_record_free(attr_ni->vol, attr_ni))
2827 ntfs_error(sb, "Failed to free MFT record");
2828 if (attr_ni->nr_extents < 0)
2829 ntfs_inode_close(attr_ni);
2830 }
2831 } else
2832 pr_err("EIO when testing mft record is free-able\n");
2833
2834 err_out:
2835 return err;
2836 }
2837
2838 /*
2839 * __ntfs_attr_init - primary initialization of an ntfs attribute structure
2840 * @ni: ntfs attribute inode to initialize
2841 * @ni: ntfs inode with which to initialize the ntfs attribute
2842 * @type: attribute type
2843 * @name: attribute name in little endian Unicode or NULL
2844 * @name_len: length of attribute @name in Unicode characters (if @name given)
2845 *
2846 * Initialize the ntfs attribute @na with @ni, @type, @name, and @name_len.
2847 */
__ntfs_attr_init(struct ntfs_inode * ni,const __le32 type,__le16 * name,const u32 name_len)2848 static void __ntfs_attr_init(struct ntfs_inode *ni,
2849 const __le32 type, __le16 *name, const u32 name_len)
2850 {
2851 ni->runlist.rl = NULL;
2852 ni->type = type;
2853 ni->name = name;
2854 if (name)
2855 ni->name_len = name_len;
2856 else
2857 ni->name_len = 0;
2858 }
2859
2860 /*
2861 * ntfs_attr_init - initialize an ntfs_attr with data sizes and status
2862 * @ni: ntfs inode to initialize
2863 * @non_resident: true if attribute is non-resident
2864 * @compressed: true if attribute is compressed
2865 * @encrypted: true if attribute is encrypted
2866 * @sparse: true if attribute is sparse
2867 * @allocated_size: allocated size of the attribute
2868 * @data_size: actual data size of the attribute
2869 * @initialized_size: initialized size of the attribute
2870 * @compressed_size: compressed size (if compressed or sparse)
2871 * @compression_unit: compression unit size (log2 of clusters)
2872 *
2873 * Final initialization for an ntfs attribute.
2874 */
ntfs_attr_init(struct ntfs_inode * ni,const bool non_resident,const bool compressed,const bool encrypted,const bool sparse,const s64 allocated_size,const s64 data_size,const s64 initialized_size,const s64 compressed_size,const u8 compression_unit)2875 static void ntfs_attr_init(struct ntfs_inode *ni, const bool non_resident,
2876 const bool compressed, const bool encrypted, const bool sparse,
2877 const s64 allocated_size, const s64 data_size,
2878 const s64 initialized_size, const s64 compressed_size,
2879 const u8 compression_unit)
2880 {
2881 if (non_resident)
2882 NInoSetNonResident(ni);
2883 if (compressed) {
2884 NInoSetCompressed(ni);
2885 ni->flags |= FILE_ATTR_COMPRESSED;
2886 }
2887 if (encrypted) {
2888 NInoSetEncrypted(ni);
2889 ni->flags |= FILE_ATTR_ENCRYPTED;
2890 }
2891 if (sparse) {
2892 NInoSetSparse(ni);
2893 ni->flags |= FILE_ATTR_SPARSE_FILE;
2894 }
2895 ni->allocated_size = allocated_size;
2896 ni->data_size = data_size;
2897 ni->initialized_size = initialized_size;
2898 if (compressed || sparse) {
2899 struct ntfs_volume *vol = ni->vol;
2900
2901 ni->itype.compressed.size = compressed_size;
2902 ni->itype.compressed.block_clusters = 1 << compression_unit;
2903 ni->itype.compressed.block_size = 1 << (compression_unit +
2904 vol->cluster_size_bits);
2905 ni->itype.compressed.block_size_bits = ffs(
2906 ni->itype.compressed.block_size) - 1;
2907 }
2908 }
2909
2910 /*
2911 * ntfs_attr_open - open an ntfs attribute for access
2912 * @ni: open ntfs inode in which the ntfs attribute resides
2913 * @type: attribute type
2914 * @name: attribute name in little endian Unicode or AT_UNNAMED or NULL
2915 * @name_len: length of attribute @name in Unicode characters (if @name given)
2916 */
ntfs_attr_open(struct ntfs_inode * ni,const __le32 type,__le16 * name,u32 name_len)2917 int ntfs_attr_open(struct ntfs_inode *ni, const __le32 type,
2918 __le16 *name, u32 name_len)
2919 {
2920 struct ntfs_attr_search_ctx *ctx;
2921 __le16 *newname = NULL;
2922 struct attr_record *a;
2923 bool cs;
2924 struct ntfs_inode *base_ni;
2925 int err;
2926
2927 ntfs_debug("Entering for inode %lld, attr 0x%x.\n",
2928 (unsigned long long)ni->mft_no, type);
2929
2930 if (!ni || !ni->vol)
2931 return -EINVAL;
2932
2933 if (NInoAttr(ni))
2934 base_ni = ni->ext.base_ntfs_ino;
2935 else
2936 base_ni = ni;
2937
2938 if (name && name != AT_UNNAMED && name != I30) {
2939 name = ntfs_ucsndup(name, name_len);
2940 if (!name) {
2941 err = -ENOMEM;
2942 goto err_out;
2943 }
2944 newname = name;
2945 }
2946
2947 ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
2948 if (!ctx) {
2949 err = -ENOMEM;
2950 pr_err("%s: Failed to get search context\n", __func__);
2951 goto err_out;
2952 }
2953
2954 err = ntfs_attr_lookup(type, name, name_len, 0, 0, NULL, 0, ctx);
2955 if (err)
2956 goto put_err_out;
2957
2958 a = ctx->attr;
2959
2960 if (!name) {
2961 if (a->name_length) {
2962 name = ntfs_ucsndup((__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
2963 a->name_length);
2964 if (!name)
2965 goto put_err_out;
2966 newname = name;
2967 name_len = a->name_length;
2968 } else {
2969 name = AT_UNNAMED;
2970 name_len = 0;
2971 }
2972 }
2973
2974 __ntfs_attr_init(ni, type, name, name_len);
2975
2976 /*
2977 * Wipe the flags in case they are not zero for an attribute list
2978 * attribute. Windows does not complain about invalid flags and chkdsk
2979 * does not detect or fix them so we need to cope with it, too.
2980 */
2981 if (type == AT_ATTRIBUTE_LIST)
2982 a->flags = 0;
2983
2984 if ((type == AT_DATA) &&
2985 (a->non_resident ? !a->data.non_resident.initialized_size :
2986 !a->data.resident.value_length)) {
2987 /*
2988 * Define/redefine the compression state if stream is
2989 * empty, based on the compression mark on parent
2990 * directory (for unnamed data streams) or on current
2991 * inode (for named data streams). The compression mark
2992 * may change any time, the compression state can only
2993 * change when stream is wiped out.
2994 *
2995 * Also prevent compression on NTFS version < 3.0
2996 * or cluster size > 4K or compression is disabled
2997 */
2998 a->flags &= ~ATTR_COMPRESSION_MASK;
2999 if (NInoCompressed(ni)
3000 && (ni->vol->major_ver >= 3)
3001 && NVolCompression(ni->vol)
3002 && (ni->vol->cluster_size <= MAX_COMPRESSION_CLUSTER_SIZE))
3003 a->flags |= ATTR_IS_COMPRESSED;
3004 }
3005
3006 cs = a->flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE);
3007
3008 if (ni->type == AT_DATA && ni->name == AT_UNNAMED &&
3009 ((!(a->flags & ATTR_IS_COMPRESSED) != !NInoCompressed(ni)) ||
3010 (!(a->flags & ATTR_IS_SPARSE) != !NInoSparse(ni)) ||
3011 (!(a->flags & ATTR_IS_ENCRYPTED) != !NInoEncrypted(ni)))) {
3012 err = -EIO;
3013 pr_err("Inode %lld has corrupt attribute flags (0x%x <> 0x%x)\n",
3014 (unsigned long long)ni->mft_no,
3015 a->flags, ni->flags);
3016 goto put_err_out;
3017 }
3018
3019 if (a->non_resident) {
3020 if (((a->flags & ATTR_COMPRESSION_MASK) || a->data.non_resident.compression_unit) &&
3021 (ni->vol->major_ver < 3)) {
3022 err = -EIO;
3023 pr_err("Compressed inode %lld not allowed on NTFS %d.%d\n",
3024 (unsigned long long)ni->mft_no,
3025 ni->vol->major_ver,
3026 ni->vol->major_ver);
3027 goto put_err_out;
3028 }
3029
3030 if ((a->flags & ATTR_IS_COMPRESSED) && !a->data.non_resident.compression_unit) {
3031 err = -EIO;
3032 pr_err("Compressed inode %lld attr 0x%x has no compression unit\n",
3033 (unsigned long long)ni->mft_no, type);
3034 goto put_err_out;
3035 }
3036 if ((a->flags & ATTR_COMPRESSION_MASK) &&
3037 (a->data.non_resident.compression_unit != STANDARD_COMPRESSION_UNIT)) {
3038 err = -EIO;
3039 pr_err("Compressed inode %lld attr 0x%lx has an unsupported compression unit %d\n",
3040 (unsigned long long)ni->mft_no,
3041 (long)le32_to_cpu(type),
3042 (int)a->data.non_resident.compression_unit);
3043 goto put_err_out;
3044 }
3045 ntfs_attr_init(ni, true, a->flags & ATTR_IS_COMPRESSED,
3046 a->flags & ATTR_IS_ENCRYPTED,
3047 a->flags & ATTR_IS_SPARSE,
3048 le64_to_cpu(a->data.non_resident.allocated_size),
3049 le64_to_cpu(a->data.non_resident.data_size),
3050 le64_to_cpu(a->data.non_resident.initialized_size),
3051 cs ? le64_to_cpu(a->data.non_resident.compressed_size) : 0,
3052 cs ? a->data.non_resident.compression_unit : 0);
3053 } else {
3054 s64 l = le32_to_cpu(a->data.resident.value_length);
3055
3056 ntfs_attr_init(ni, false, a->flags & ATTR_IS_COMPRESSED,
3057 a->flags & ATTR_IS_ENCRYPTED,
3058 a->flags & ATTR_IS_SPARSE, (l + 7) & ~7, l, l,
3059 cs ? (l + 7) & ~7 : 0, 0);
3060 }
3061 ntfs_attr_put_search_ctx(ctx);
3062 out:
3063 ntfs_debug("\n");
3064 return err;
3065
3066 put_err_out:
3067 ntfs_attr_put_search_ctx(ctx);
3068 err_out:
3069 kfree(newname);
3070 goto out;
3071 }
3072
3073 /*
3074 * ntfs_attr_close - free an ntfs attribute structure
3075 * @ni: ntfs inode to free
3076 *
3077 * Release all memory associated with the ntfs attribute @na and then release
3078 * @na itself.
3079 */
ntfs_attr_close(struct ntfs_inode * ni)3080 void ntfs_attr_close(struct ntfs_inode *ni)
3081 {
3082 if (NInoNonResident(ni) && ni->runlist.rl)
3083 kvfree(ni->runlist.rl);
3084 /* Don't release if using an internal constant. */
3085 if (ni->name != AT_UNNAMED && ni->name != I30)
3086 kfree(ni->name);
3087 }
3088
3089 /*
3090 * ntfs_attr_map_whole_runlist - map the whole runlist of an ntfs attribute
3091 * @ni: ntfs inode for which to map the runlist
3092 *
3093 * Map the whole runlist of the ntfs attribute @na. For an attribute made up
3094 * of only one attribute extent this is the same as calling
3095 * ntfs_map_runlist(ni, 0) but for an attribute with multiple extents this
3096 * will map the runlist fragments from each of the extents thus giving access
3097 * to the entirety of the disk allocation of an attribute.
3098 */
ntfs_attr_map_whole_runlist(struct ntfs_inode * ni)3099 int ntfs_attr_map_whole_runlist(struct ntfs_inode *ni)
3100 {
3101 s64 next_vcn, last_vcn, highest_vcn;
3102 struct ntfs_attr_search_ctx *ctx;
3103 struct ntfs_volume *vol = ni->vol;
3104 struct super_block *sb = vol->sb;
3105 struct attr_record *a;
3106 int err;
3107 struct ntfs_inode *base_ni;
3108 int not_mapped;
3109 size_t new_rl_count;
3110
3111 ntfs_debug("Entering for inode 0x%llx, attr 0x%x.\n",
3112 (unsigned long long)ni->mft_no, ni->type);
3113
3114 if (NInoFullyMapped(ni) && ni->runlist.rl)
3115 return 0;
3116
3117 if (NInoAttr(ni))
3118 base_ni = ni->ext.base_ntfs_ino;
3119 else
3120 base_ni = ni;
3121
3122 ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
3123 if (!ctx) {
3124 ntfs_error(sb, "%s: Failed to get search context", __func__);
3125 return -ENOMEM;
3126 }
3127
3128 /* Map all attribute extents one by one. */
3129 next_vcn = last_vcn = highest_vcn = 0;
3130 a = NULL;
3131 while (1) {
3132 struct runlist_element *rl;
3133
3134 not_mapped = 0;
3135 if (ntfs_rl_vcn_to_lcn(ni->runlist.rl, next_vcn) == LCN_RL_NOT_MAPPED)
3136 not_mapped = 1;
3137
3138 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
3139 CASE_SENSITIVE, next_vcn, NULL, 0, ctx);
3140 if (err)
3141 break;
3142
3143 a = ctx->attr;
3144
3145 if (not_mapped) {
3146 /* Decode the runlist. */
3147 rl = ntfs_mapping_pairs_decompress(ni->vol, a, &ni->runlist,
3148 &new_rl_count);
3149 if (IS_ERR(rl)) {
3150 err = PTR_ERR(rl);
3151 goto err_out;
3152 }
3153 ni->runlist.rl = rl;
3154 ni->runlist.count = new_rl_count;
3155 }
3156
3157 /* Are we in the first extent? */
3158 if (!next_vcn) {
3159 if (a->data.non_resident.lowest_vcn) {
3160 err = -EIO;
3161 ntfs_error(sb,
3162 "First extent of inode %llu attribute has non-zero lowest_vcn",
3163 (unsigned long long)ni->mft_no);
3164 goto err_out;
3165 }
3166 /* Get the last vcn in the attribute. */
3167 last_vcn = ntfs_bytes_to_cluster(vol,
3168 le64_to_cpu(a->data.non_resident.allocated_size));
3169 }
3170
3171 /* Get the lowest vcn for the next extent. */
3172 highest_vcn = le64_to_cpu(a->data.non_resident.highest_vcn);
3173 next_vcn = highest_vcn + 1;
3174
3175 /* Only one extent or error, which we catch below. */
3176 if (next_vcn <= 0) {
3177 err = -ENOENT;
3178 break;
3179 }
3180
3181 /* Avoid endless loops due to corruption. */
3182 if (next_vcn < le64_to_cpu(a->data.non_resident.lowest_vcn)) {
3183 err = -EIO;
3184 ntfs_error(sb, "Inode %llu has corrupt attribute list",
3185 (unsigned long long)ni->mft_no);
3186 goto err_out;
3187 }
3188 }
3189 if (!a) {
3190 ntfs_error(sb, "Couldn't find attribute for runlist mapping");
3191 goto err_out;
3192 }
3193 if (not_mapped && highest_vcn && highest_vcn != last_vcn - 1) {
3194 err = -EIO;
3195 ntfs_error(sb,
3196 "Failed to load full runlist: inode: %llu highest_vcn: 0x%llx last_vcn: 0x%llx",
3197 (unsigned long long)ni->mft_no,
3198 (long long)highest_vcn, (long long)last_vcn);
3199 goto err_out;
3200 }
3201 ntfs_attr_put_search_ctx(ctx);
3202 if (err == -ENOENT) {
3203 NInoSetFullyMapped(ni);
3204 return 0;
3205 }
3206
3207 return err;
3208
3209 err_out:
3210 ntfs_attr_put_search_ctx(ctx);
3211 return err;
3212 }
3213
3214 /*
3215 * ntfs_attr_record_move_to - move attribute record to target inode
3216 * @ctx: attribute search context describing the attribute record
3217 * @ni: opened ntfs inode to which move attribute record
3218 */
ntfs_attr_record_move_to(struct ntfs_attr_search_ctx * ctx,struct ntfs_inode * ni)3219 int ntfs_attr_record_move_to(struct ntfs_attr_search_ctx *ctx, struct ntfs_inode *ni)
3220 {
3221 struct ntfs_attr_search_ctx *nctx;
3222 struct attr_record *a;
3223 int err;
3224 struct mft_record *ni_mrec;
3225 struct super_block *sb;
3226
3227 if (!ctx || !ctx->attr || !ctx->ntfs_ino || !ni) {
3228 ntfs_debug("Invalid arguments passed.\n");
3229 return -EINVAL;
3230 }
3231
3232 sb = ni->vol->sb;
3233 ntfs_debug("Entering for ctx->attr->type 0x%x, ctx->ntfs_ino->mft_no 0x%llx, ni->mft_no 0x%llx.\n",
3234 (unsigned int) le32_to_cpu(ctx->attr->type),
3235 (long long) ctx->ntfs_ino->mft_no,
3236 (long long) ni->mft_no);
3237
3238 if (ctx->ntfs_ino == ni)
3239 return 0;
3240
3241 if (!ctx->al_entry) {
3242 ntfs_debug("Inode should contain attribute list to use this function.\n");
3243 return -EINVAL;
3244 }
3245
3246 /* Find place in MFT record where attribute will be moved. */
3247 a = ctx->attr;
3248 nctx = ntfs_attr_get_search_ctx(ni, NULL);
3249 if (!nctx) {
3250 ntfs_error(sb, "%s: Failed to get search context", __func__);
3251 return -ENOMEM;
3252 }
3253
3254 /*
3255 * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for
3256 * attribute in @ni->mrec, not any extent inode in case if @ni is base
3257 * file record.
3258 */
3259 err = ntfs_attr_find(a->type, (__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
3260 a->name_length, CASE_SENSITIVE, NULL,
3261 0, nctx);
3262 if (!err) {
3263 ntfs_debug("Attribute of such type, with same name already present in this MFT record.\n");
3264 err = -EEXIST;
3265 goto put_err_out;
3266 }
3267 if (err != -ENOENT) {
3268 ntfs_debug("Attribute lookup failed.\n");
3269 goto put_err_out;
3270 }
3271
3272 /* Make space and move attribute. */
3273 ni_mrec = map_mft_record(ni);
3274 if (IS_ERR(ni_mrec)) {
3275 err = -EIO;
3276 goto put_err_out;
3277 }
3278
3279 err = ntfs_make_room_for_attr(ni_mrec, (u8 *) nctx->attr,
3280 le32_to_cpu(a->length));
3281 if (err) {
3282 ntfs_debug("Couldn't make space for attribute.\n");
3283 unmap_mft_record(ni);
3284 goto put_err_out;
3285 }
3286 memcpy(nctx->attr, a, le32_to_cpu(a->length));
3287 nctx->attr->instance = nctx->mrec->next_attr_instance;
3288 nctx->mrec->next_attr_instance =
3289 cpu_to_le16((le16_to_cpu(nctx->mrec->next_attr_instance) + 1) & 0xffff);
3290 ntfs_attr_record_resize(ctx->mrec, a, 0);
3291 mark_mft_record_dirty(ctx->ntfs_ino);
3292 mark_mft_record_dirty(ni);
3293
3294 /* Update attribute list. */
3295 ctx->al_entry->mft_reference =
3296 MK_LE_MREF(ni->mft_no, le16_to_cpu(ni_mrec->sequence_number));
3297 ctx->al_entry->instance = nctx->attr->instance;
3298 unmap_mft_record(ni);
3299 put_err_out:
3300 ntfs_attr_put_search_ctx(nctx);
3301 return err;
3302 }
3303
3304 /*
3305 * ntfs_attr_record_move_away - move away attribute record from it's mft record
3306 * @ctx: attribute search context describing the attribute record
3307 * @extra: minimum amount of free space in the new holder of record
3308 */
ntfs_attr_record_move_away(struct ntfs_attr_search_ctx * ctx,int extra)3309 int ntfs_attr_record_move_away(struct ntfs_attr_search_ctx *ctx, int extra)
3310 {
3311 struct ntfs_inode *base_ni, *ni = NULL;
3312 struct mft_record *m;
3313 int i, err;
3314 struct super_block *sb;
3315
3316 if (!ctx || !ctx->attr || !ctx->ntfs_ino || extra < 0)
3317 return -EINVAL;
3318
3319 ntfs_debug("Entering for attr 0x%x, inode %llu\n",
3320 (unsigned int) le32_to_cpu(ctx->attr->type),
3321 (unsigned long long)ctx->ntfs_ino->mft_no);
3322
3323 if (ctx->ntfs_ino->nr_extents == -1)
3324 base_ni = ctx->base_ntfs_ino;
3325 else
3326 base_ni = ctx->ntfs_ino;
3327
3328 sb = ctx->ntfs_ino->vol->sb;
3329 if (!NInoAttrList(base_ni)) {
3330 ntfs_error(sb, "Inode %llu has no attrlist",
3331 (unsigned long long)base_ni->mft_no);
3332 return -EINVAL;
3333 }
3334
3335 err = ntfs_inode_attach_all_extents(ctx->ntfs_ino);
3336 if (err) {
3337 ntfs_error(sb, "Couldn't attach extents, inode=%llu",
3338 (unsigned long long)base_ni->mft_no);
3339 return err;
3340 }
3341
3342 mutex_lock(&base_ni->extent_lock);
3343 /* Walk through all extents and try to move attribute to them. */
3344 for (i = 0; i < base_ni->nr_extents; i++) {
3345 ni = base_ni->ext.extent_ntfs_inos[i];
3346
3347 if (ctx->ntfs_ino->mft_no == ni->mft_no)
3348 continue;
3349 m = map_mft_record(ni);
3350 if (IS_ERR(m)) {
3351 ntfs_error(sb, "Can not map mft record for mft_no %lld",
3352 (unsigned long long)ni->mft_no);
3353 mutex_unlock(&base_ni->extent_lock);
3354 return -EIO;
3355 }
3356 if (le32_to_cpu(m->bytes_allocated) -
3357 le32_to_cpu(m->bytes_in_use) < le32_to_cpu(ctx->attr->length) + extra) {
3358 unmap_mft_record(ni);
3359 continue;
3360 }
3361 unmap_mft_record(ni);
3362
3363 /*
3364 * ntfs_attr_record_move_to can fail if extent with other lowest
3365 * s64 already present in inode we trying move record to. So,
3366 * do not return error.
3367 */
3368 if (!ntfs_attr_record_move_to(ctx, ni)) {
3369 mutex_unlock(&base_ni->extent_lock);
3370 return 0;
3371 }
3372 }
3373 mutex_unlock(&base_ni->extent_lock);
3374
3375 /*
3376 * Failed to move attribute to one of the current extents, so allocate
3377 * new extent and move attribute to it.
3378 */
3379 ni = NULL;
3380 err = ntfs_mft_record_alloc(base_ni->vol, 0, &ni, base_ni, NULL);
3381 if (err) {
3382 ntfs_error(sb, "Couldn't allocate MFT record, err : %d", err);
3383 return err;
3384 }
3385 unmap_mft_record(ni);
3386
3387 err = ntfs_attr_record_move_to(ctx, ni);
3388 if (err)
3389 ntfs_error(sb, "Couldn't move attribute to MFT record");
3390
3391 return err;
3392 }
3393
3394 /*
3395 * If we are in the first extent, then set/clean sparse bit,
3396 * update allocated and compressed size.
3397 */
ntfs_attr_update_meta(struct attr_record * a,struct ntfs_inode * ni,struct mft_record * m,struct ntfs_attr_search_ctx * ctx)3398 static int ntfs_attr_update_meta(struct attr_record *a, struct ntfs_inode *ni,
3399 struct mft_record *m, struct ntfs_attr_search_ctx *ctx)
3400 {
3401 int sparse, err = 0;
3402 struct ntfs_inode *base_ni;
3403 struct super_block *sb = ni->vol->sb;
3404
3405 ntfs_debug("Entering for inode 0x%llx, attr 0x%x\n",
3406 (unsigned long long)ni->mft_no, ni->type);
3407
3408 if (NInoAttr(ni))
3409 base_ni = ni->ext.base_ntfs_ino;
3410 else
3411 base_ni = ni;
3412
3413 if (a->data.non_resident.lowest_vcn)
3414 goto out;
3415
3416 a->data.non_resident.allocated_size = cpu_to_le64(ni->allocated_size);
3417
3418 sparse = ntfs_rl_sparse(ni->runlist.rl);
3419 if (sparse < 0) {
3420 err = -EIO;
3421 goto out;
3422 }
3423
3424 /* Attribute become sparse. */
3425 if (sparse && !(a->flags & (ATTR_IS_SPARSE | ATTR_IS_COMPRESSED))) {
3426 /*
3427 * Move attribute to another mft record, if attribute is too
3428 * small to add compressed_size field to it and we have no
3429 * free space in the current mft record.
3430 */
3431 if ((le32_to_cpu(a->length) -
3432 le16_to_cpu(a->data.non_resident.mapping_pairs_offset) == 8) &&
3433 !(le32_to_cpu(m->bytes_allocated) - le32_to_cpu(m->bytes_in_use))) {
3434
3435 if (!NInoAttrList(base_ni)) {
3436 err = ntfs_inode_add_attrlist(base_ni);
3437 if (err)
3438 goto out;
3439 err = -EAGAIN;
3440 goto out;
3441 }
3442 err = ntfs_attr_record_move_away(ctx, 8);
3443 if (err) {
3444 ntfs_error(sb, "Failed to move attribute");
3445 goto out;
3446 }
3447
3448 err = ntfs_attrlist_update(base_ni);
3449 if (err)
3450 goto out;
3451 err = -EAGAIN;
3452 goto out;
3453 }
3454 if (!(le32_to_cpu(a->length) -
3455 le16_to_cpu(a->data.non_resident.mapping_pairs_offset))) {
3456 err = -EIO;
3457 ntfs_error(sb, "Mapping pairs space is 0");
3458 goto out;
3459 }
3460
3461 NInoSetSparse(ni);
3462 ni->flags |= FILE_ATTR_SPARSE_FILE;
3463 a->flags |= ATTR_IS_SPARSE;
3464 a->data.non_resident.compression_unit = 0;
3465
3466 memmove((u8 *)a + le16_to_cpu(a->name_offset) + 8,
3467 (u8 *)a + le16_to_cpu(a->name_offset),
3468 a->name_length * sizeof(__le16));
3469
3470 a->name_offset = cpu_to_le16(le16_to_cpu(a->name_offset) + 8);
3471
3472 a->data.non_resident.mapping_pairs_offset =
3473 cpu_to_le16(le16_to_cpu(a->data.non_resident.mapping_pairs_offset) + 8);
3474 }
3475
3476 /* Attribute no longer sparse. */
3477 if (!sparse && (a->flags & ATTR_IS_SPARSE) &&
3478 !(a->flags & ATTR_IS_COMPRESSED)) {
3479 NInoClearSparse(ni);
3480 ni->flags &= ~FILE_ATTR_SPARSE_FILE;
3481 a->flags &= ~ATTR_IS_SPARSE;
3482 a->data.non_resident.compression_unit = 0;
3483
3484 memmove((u8 *)a + le16_to_cpu(a->name_offset) - 8,
3485 (u8 *)a + le16_to_cpu(a->name_offset),
3486 a->name_length * sizeof(__le16));
3487
3488 if (le16_to_cpu(a->name_offset) >= 8)
3489 a->name_offset = cpu_to_le16(le16_to_cpu(a->name_offset) - 8);
3490
3491 a->data.non_resident.mapping_pairs_offset =
3492 cpu_to_le16(le16_to_cpu(a->data.non_resident.mapping_pairs_offset) - 8);
3493 }
3494
3495 /* Update compressed size if required. */
3496 if (NInoFullyMapped(ni) && (sparse || NInoCompressed(ni))) {
3497 s64 new_compr_size;
3498
3499 new_compr_size = ntfs_rl_get_compressed_size(ni->vol, ni->runlist.rl);
3500 if (new_compr_size < 0) {
3501 err = new_compr_size;
3502 goto out;
3503 }
3504
3505 ni->itype.compressed.size = new_compr_size;
3506 a->data.non_resident.compressed_size = cpu_to_le64(new_compr_size);
3507 }
3508
3509 if (NInoSparse(ni) || NInoCompressed(ni))
3510 VFS_I(base_ni)->i_blocks = ni->itype.compressed.size >> 9;
3511 else
3512 VFS_I(base_ni)->i_blocks = ni->allocated_size >> 9;
3513 /*
3514 * Set FILE_NAME dirty flag, to update sparse bit and
3515 * allocated size in the index.
3516 */
3517 if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
3518 NInoSetFileNameDirty(ni);
3519 out:
3520 return err;
3521 }
3522
3523 #define NTFS_VCN_DELETE_MARK -2
3524 /*
3525 * ntfs_attr_update_mapping_pairs - update mapping pairs for ntfs attribute
3526 * @ni: non-resident ntfs inode for which we need update
3527 * @from_vcn: update runlist starting this VCN
3528 *
3529 * Build mapping pairs from @na->rl and write them to the disk. Also, this
3530 * function updates sparse bit, allocated and compressed size (allocates/frees
3531 * space for this field if required).
3532 *
3533 * @na->allocated_size should be set to correct value for the new runlist before
3534 * call to this function. Vice-versa @na->compressed_size will be calculated and
3535 * set to correct value during this function.
3536 */
ntfs_attr_update_mapping_pairs(struct ntfs_inode * ni,s64 from_vcn)3537 int ntfs_attr_update_mapping_pairs(struct ntfs_inode *ni, s64 from_vcn)
3538 {
3539 struct ntfs_attr_search_ctx *ctx;
3540 struct ntfs_inode *base_ni;
3541 struct mft_record *m;
3542 struct attr_record *a;
3543 s64 stop_vcn;
3544 int err = 0, mp_size, cur_max_mp_size, exp_max_mp_size;
3545 bool finished_build;
3546 bool first_updated = false;
3547 struct super_block *sb;
3548 struct runlist_element *start_rl;
3549 unsigned int de_cluster_count = 0;
3550
3551 retry:
3552 if (!ni || !ni->runlist.rl)
3553 return -EINVAL;
3554
3555 ntfs_debug("Entering for inode %llu, attr 0x%x\n",
3556 (unsigned long long)ni->mft_no, ni->type);
3557
3558 sb = ni->vol->sb;
3559 if (!NInoNonResident(ni)) {
3560 ntfs_error(sb, "%s: resident attribute", __func__);
3561 return -EINVAL;
3562 }
3563
3564 if (ni->nr_extents == -1)
3565 base_ni = ni->ext.base_ntfs_ino;
3566 else
3567 base_ni = ni;
3568
3569 ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
3570 if (!ctx) {
3571 ntfs_error(sb, "%s: Failed to get search context", __func__);
3572 return -ENOMEM;
3573 }
3574
3575 /* Fill attribute records with new mapping pairs. */
3576 stop_vcn = 0;
3577 finished_build = false;
3578 start_rl = ni->runlist.rl;
3579 while (!(err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
3580 CASE_SENSITIVE, from_vcn, NULL, 0, ctx))) {
3581 unsigned int de_cnt = 0;
3582
3583 a = ctx->attr;
3584 m = ctx->mrec;
3585 if (!a->data.non_resident.lowest_vcn)
3586 first_updated = true;
3587
3588 /*
3589 * If runlist is updating not from the beginning, then set
3590 * @stop_vcn properly, i.e. to the lowest vcn of record that
3591 * contain @from_vcn. Also we do not need @from_vcn anymore,
3592 * set it to 0 to make ntfs_attr_lookup enumerate attributes.
3593 */
3594 if (from_vcn) {
3595 s64 first_lcn;
3596
3597 stop_vcn = le64_to_cpu(a->data.non_resident.lowest_vcn);
3598 from_vcn = 0;
3599 /*
3600 * Check whether the first run we need to update is
3601 * the last run in runlist, if so, then deallocate
3602 * all attrubute extents starting this one.
3603 */
3604 first_lcn = ntfs_rl_vcn_to_lcn(ni->runlist.rl, stop_vcn);
3605 if (first_lcn == LCN_EINVAL) {
3606 err = -EIO;
3607 ntfs_error(sb, "Bad runlist");
3608 goto put_err_out;
3609 }
3610 if (first_lcn == LCN_ENOENT ||
3611 first_lcn == LCN_RL_NOT_MAPPED)
3612 finished_build = true;
3613 }
3614
3615 /*
3616 * Check whether we finished mapping pairs build, if so mark
3617 * extent as need to delete (by setting highest vcn to
3618 * NTFS_VCN_DELETE_MARK (-2), we shall check it later and
3619 * delete extent) and continue search.
3620 */
3621 if (finished_build) {
3622 ntfs_debug("Mark attr 0x%x for delete in inode 0x%llx.\n",
3623 (unsigned int)le32_to_cpu(a->type), ctx->ntfs_ino->mft_no);
3624 a->data.non_resident.highest_vcn = cpu_to_le64(NTFS_VCN_DELETE_MARK);
3625 mark_mft_record_dirty(ctx->ntfs_ino);
3626 continue;
3627 }
3628
3629 err = ntfs_attr_update_meta(a, ni, m, ctx);
3630 if (err < 0) {
3631 if (err == -EAGAIN) {
3632 ntfs_attr_put_search_ctx(ctx);
3633 goto retry;
3634 }
3635 goto put_err_out;
3636 }
3637
3638 /*
3639 * Determine maximum possible length of mapping pairs,
3640 * if we shall *not* expand space for mapping pairs.
3641 */
3642 cur_max_mp_size = le32_to_cpu(a->length) -
3643 le16_to_cpu(a->data.non_resident.mapping_pairs_offset);
3644 /*
3645 * Determine maximum possible length of mapping pairs in the
3646 * current mft record, if we shall expand space for mapping
3647 * pairs.
3648 */
3649 exp_max_mp_size = le32_to_cpu(m->bytes_allocated) -
3650 le32_to_cpu(m->bytes_in_use) + cur_max_mp_size;
3651
3652 /* Get the size for the rest of mapping pairs array. */
3653 mp_size = ntfs_get_size_for_mapping_pairs(ni->vol, start_rl,
3654 stop_vcn, -1, exp_max_mp_size);
3655 if (mp_size <= 0) {
3656 err = mp_size;
3657 ntfs_error(sb, "%s: get MP size failed", __func__);
3658 goto put_err_out;
3659 }
3660 /* Test mapping pairs for fitting in the current mft record. */
3661 if (mp_size > exp_max_mp_size) {
3662 /*
3663 * Mapping pairs of $ATTRIBUTE_LIST attribute must fit
3664 * in the base mft record. Try to move out other
3665 * attributes and try again.
3666 */
3667 if (ni->type == AT_ATTRIBUTE_LIST) {
3668 ntfs_attr_put_search_ctx(ctx);
3669 if (ntfs_inode_free_space(base_ni, mp_size -
3670 cur_max_mp_size)) {
3671 ntfs_debug("Attribute list is too big. Defragment the volume\n");
3672 return -ENOSPC;
3673 }
3674 if (ntfs_attrlist_update(base_ni))
3675 return -EIO;
3676 goto retry;
3677 }
3678
3679 /* Add attribute list if it isn't present, and retry. */
3680 if (!NInoAttrList(base_ni)) {
3681 ntfs_attr_put_search_ctx(ctx);
3682 if (ntfs_inode_add_attrlist(base_ni)) {
3683 ntfs_error(sb, "Can not add attrlist");
3684 return -EIO;
3685 }
3686 goto retry;
3687 }
3688
3689 /*
3690 * Set mapping pairs size to maximum possible for this
3691 * mft record. We shall write the rest of mapping pairs
3692 * to another MFT records.
3693 */
3694 mp_size = exp_max_mp_size;
3695 }
3696
3697 /* Change space for mapping pairs if we need it. */
3698 if (((mp_size + 7) & ~7) != cur_max_mp_size) {
3699 if (ntfs_attr_record_resize(m, a,
3700 le16_to_cpu(a->data.non_resident.mapping_pairs_offset) +
3701 mp_size)) {
3702 err = -EIO;
3703 ntfs_error(sb, "Failed to resize attribute");
3704 goto put_err_out;
3705 }
3706 }
3707
3708 /* Update lowest vcn. */
3709 a->data.non_resident.lowest_vcn = cpu_to_le64(stop_vcn);
3710 mark_mft_record_dirty(ctx->ntfs_ino);
3711 if ((ctx->ntfs_ino->nr_extents == -1 || NInoAttrList(ctx->ntfs_ino)) &&
3712 ctx->attr->type != AT_ATTRIBUTE_LIST) {
3713 ctx->al_entry->lowest_vcn = cpu_to_le64(stop_vcn);
3714 err = ntfs_attrlist_update(base_ni);
3715 if (err)
3716 goto put_err_out;
3717 }
3718
3719 /*
3720 * Generate the new mapping pairs array directly into the
3721 * correct destination, i.e. the attribute record itself.
3722 */
3723 err = ntfs_mapping_pairs_build(ni->vol,
3724 (u8 *)a + le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
3725 mp_size, start_rl, stop_vcn, -1, &stop_vcn, &start_rl, &de_cnt);
3726 if (!err)
3727 finished_build = true;
3728 if (!finished_build && err != -ENOSPC) {
3729 ntfs_error(sb, "Failed to build mapping pairs");
3730 goto put_err_out;
3731 }
3732 a->data.non_resident.highest_vcn = cpu_to_le64(stop_vcn - 1);
3733 mark_mft_record_dirty(ctx->ntfs_ino);
3734 de_cluster_count += de_cnt;
3735 }
3736
3737 /* Check whether error occurred. */
3738 if (err && err != -ENOENT) {
3739 ntfs_error(sb, "%s: Attribute lookup failed", __func__);
3740 goto put_err_out;
3741 }
3742
3743 /*
3744 * If the base extent was skipped in the above process,
3745 * we still may have to update the sizes.
3746 */
3747 if (!first_updated) {
3748 ntfs_attr_reinit_search_ctx(ctx);
3749 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
3750 CASE_SENSITIVE, 0, NULL, 0, ctx);
3751 if (!err) {
3752 a = ctx->attr;
3753 a->data.non_resident.allocated_size = cpu_to_le64(ni->allocated_size);
3754 if (NInoCompressed(ni) || NInoSparse(ni))
3755 a->data.non_resident.compressed_size =
3756 cpu_to_le64(ni->itype.compressed.size);
3757 /* Updating sizes taints the extent holding the attr */
3758 if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
3759 NInoSetFileNameDirty(ni);
3760 mark_mft_record_dirty(ctx->ntfs_ino);
3761 } else {
3762 ntfs_error(sb, "Failed to update sizes in base extent\n");
3763 goto put_err_out;
3764 }
3765 }
3766
3767 /* Deallocate not used attribute extents and return with success. */
3768 if (finished_build) {
3769 ntfs_attr_reinit_search_ctx(ctx);
3770 ntfs_debug("Deallocate marked extents.\n");
3771 while (!(err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
3772 CASE_SENSITIVE, 0, NULL, 0, ctx))) {
3773 if (le64_to_cpu(ctx->attr->data.non_resident.highest_vcn) !=
3774 NTFS_VCN_DELETE_MARK)
3775 continue;
3776 /* Remove unused attribute record. */
3777 err = ntfs_attr_record_rm(ctx);
3778 if (err) {
3779 ntfs_error(sb, "Could not remove unused attr");
3780 goto put_err_out;
3781 }
3782 ntfs_attr_reinit_search_ctx(ctx);
3783 }
3784 if (err && err != -ENOENT) {
3785 ntfs_error(sb, "%s: Attr lookup failed", __func__);
3786 goto put_err_out;
3787 }
3788 ntfs_debug("Deallocate done.\n");
3789 ntfs_attr_put_search_ctx(ctx);
3790 goto out;
3791 }
3792 ntfs_attr_put_search_ctx(ctx);
3793 ctx = NULL;
3794
3795 /* Allocate new MFT records for the rest of mapping pairs. */
3796 while (1) {
3797 struct ntfs_inode *ext_ni = NULL;
3798 unsigned int de_cnt = 0;
3799
3800 /* Allocate new mft record. */
3801 err = ntfs_mft_record_alloc(ni->vol, 0, &ext_ni, base_ni, NULL);
3802 if (err) {
3803 ntfs_error(sb, "Failed to allocate extent record");
3804 goto put_err_out;
3805 }
3806 unmap_mft_record(ext_ni);
3807
3808 m = map_mft_record(ext_ni);
3809 if (IS_ERR(m)) {
3810 ntfs_error(sb, "Could not map new MFT record");
3811 if (ntfs_mft_record_free(ni->vol, ext_ni))
3812 ntfs_error(sb, "Could not free MFT record");
3813 ntfs_inode_close(ext_ni);
3814 err = -ENOMEM;
3815 ext_ni = NULL;
3816 goto put_err_out;
3817 }
3818 /*
3819 * If mapping size exceed available space, set them to
3820 * possible maximum.
3821 */
3822 cur_max_mp_size = le32_to_cpu(m->bytes_allocated) -
3823 le32_to_cpu(m->bytes_in_use) -
3824 (sizeof(struct attr_record) +
3825 ((NInoCompressed(ni) || NInoSparse(ni)) ?
3826 sizeof(a->data.non_resident.compressed_size) : 0)) -
3827 ((sizeof(__le16) * ni->name_len + 7) & ~7);
3828
3829 /* Calculate size of rest mapping pairs. */
3830 mp_size = ntfs_get_size_for_mapping_pairs(ni->vol,
3831 start_rl, stop_vcn, -1, cur_max_mp_size);
3832 if (mp_size <= 0) {
3833 unmap_mft_record(ext_ni);
3834 ntfs_inode_close(ext_ni);
3835 err = mp_size;
3836 ntfs_error(sb, "%s: get mp size failed", __func__);
3837 goto put_err_out;
3838 }
3839
3840 if (mp_size > cur_max_mp_size)
3841 mp_size = cur_max_mp_size;
3842 /* Add attribute extent to new record. */
3843 err = ntfs_non_resident_attr_record_add(ext_ni, ni->type,
3844 ni->name, ni->name_len, stop_vcn, mp_size, 0);
3845 if (err < 0) {
3846 ntfs_error(sb, "Could not add attribute extent");
3847 unmap_mft_record(ext_ni);
3848 if (ntfs_mft_record_free(ni->vol, ext_ni))
3849 ntfs_error(sb, "Could not free MFT record");
3850 ntfs_inode_close(ext_ni);
3851 goto put_err_out;
3852 }
3853 a = (struct attr_record *)((u8 *)m + err);
3854
3855 err = ntfs_mapping_pairs_build(ni->vol, (u8 *)a +
3856 le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
3857 mp_size, start_rl, stop_vcn, -1, &stop_vcn, &start_rl,
3858 &de_cnt);
3859 if (err < 0 && err != -ENOSPC) {
3860 ntfs_error(sb, "Failed to build MP");
3861 unmap_mft_record(ext_ni);
3862 if (ntfs_mft_record_free(ni->vol, ext_ni))
3863 ntfs_error(sb, "Couldn't free MFT record");
3864 goto put_err_out;
3865 }
3866 a->data.non_resident.highest_vcn = cpu_to_le64(stop_vcn - 1);
3867 mark_mft_record_dirty(ext_ni);
3868 unmap_mft_record(ext_ni);
3869
3870 de_cluster_count += de_cnt;
3871 /* All mapping pairs has been written. */
3872 if (!err)
3873 break;
3874 }
3875 out:
3876 if (from_vcn == 0)
3877 ni->i_dealloc_clusters = de_cluster_count;
3878 return 0;
3879
3880 put_err_out:
3881 if (ctx)
3882 ntfs_attr_put_search_ctx(ctx);
3883 return err;
3884 }
3885
3886 /*
3887 * ntfs_attr_make_resident - convert a non-resident to a resident attribute
3888 * @ni: open ntfs attribute to make resident
3889 * @ctx: ntfs search context describing the attribute
3890 *
3891 * Convert a non-resident ntfs attribute to a resident one.
3892 */
ntfs_attr_make_resident(struct ntfs_inode * ni,struct ntfs_attr_search_ctx * ctx)3893 static int ntfs_attr_make_resident(struct ntfs_inode *ni, struct ntfs_attr_search_ctx *ctx)
3894 {
3895 struct ntfs_volume *vol = ni->vol;
3896 struct super_block *sb = vol->sb;
3897 struct attr_record *a = ctx->attr;
3898 int name_ofs, val_ofs, err;
3899 s64 arec_size;
3900
3901 ntfs_debug("Entering for inode 0x%llx, attr 0x%x.\n",
3902 (unsigned long long)ni->mft_no, ni->type);
3903
3904 /* Should be called for the first extent of the attribute. */
3905 if (le64_to_cpu(a->data.non_resident.lowest_vcn)) {
3906 ntfs_debug("Eeek! Should be called for the first extent of the attribute. Aborting...\n");
3907 return -EINVAL;
3908 }
3909
3910 /* Some preliminary sanity checking. */
3911 if (!NInoNonResident(ni)) {
3912 ntfs_debug("Eeek! Trying to make resident attribute resident. Aborting...\n");
3913 return -EINVAL;
3914 }
3915
3916 /* Make sure this is not $MFT/$BITMAP or Windows will not boot! */
3917 if (ni->type == AT_BITMAP && ni->mft_no == FILE_MFT)
3918 return -EPERM;
3919
3920 /* Check that the attribute is allowed to be resident. */
3921 err = ntfs_attr_can_be_resident(vol, ni->type);
3922 if (err)
3923 return err;
3924
3925 if (NInoCompressed(ni) || NInoEncrypted(ni)) {
3926 ntfs_debug("Making compressed or encrypted files resident is not implemented yet.\n");
3927 return -EOPNOTSUPP;
3928 }
3929
3930 /* Work out offsets into and size of the resident attribute. */
3931 name_ofs = 24; /* = sizeof(resident_struct attr_record); */
3932 val_ofs = (name_ofs + a->name_length * sizeof(__le16) + 7) & ~7;
3933 arec_size = (val_ofs + ni->data_size + 7) & ~7;
3934
3935 /* Sanity check the size before we start modifying the attribute. */
3936 if (le32_to_cpu(ctx->mrec->bytes_in_use) - le32_to_cpu(a->length) +
3937 arec_size > le32_to_cpu(ctx->mrec->bytes_allocated)) {
3938 ntfs_debug("Not enough space to make attribute resident\n");
3939 return -ENOSPC;
3940 }
3941
3942 /* Read and cache the whole runlist if not already done. */
3943 err = ntfs_attr_map_whole_runlist(ni);
3944 if (err)
3945 return err;
3946
3947 /* Move the attribute name if it exists and update the offset. */
3948 if (a->name_length) {
3949 memmove((u8 *)a + name_ofs, (u8 *)a + le16_to_cpu(a->name_offset),
3950 a->name_length * sizeof(__le16));
3951 }
3952 a->name_offset = cpu_to_le16(name_ofs);
3953
3954 /* Resize the resident part of the attribute record. */
3955 if (ntfs_attr_record_resize(ctx->mrec, a, arec_size) < 0) {
3956 /*
3957 * Bug, because ntfs_attr_record_resize should not fail (we
3958 * already checked that attribute fits MFT record).
3959 */
3960 ntfs_error(ctx->ntfs_ino->vol->sb, "BUG! Failed to resize attribute record. ");
3961 return -EIO;
3962 }
3963
3964 /* Convert the attribute record to describe a resident attribute. */
3965 a->non_resident = 0;
3966 a->flags = 0;
3967 a->data.resident.value_length = cpu_to_le32(ni->data_size);
3968 a->data.resident.value_offset = cpu_to_le16(val_ofs);
3969 /*
3970 * File names cannot be non-resident so we would never see this here
3971 * but at least it serves as a reminder that there may be attributes
3972 * for which we do need to set this flag. (AIA)
3973 */
3974 if (a->type == AT_FILE_NAME)
3975 a->data.resident.flags = RESIDENT_ATTR_IS_INDEXED;
3976 else
3977 a->data.resident.flags = 0;
3978 a->data.resident.reserved = 0;
3979
3980 /*
3981 * Deallocate clusters from the runlist.
3982 *
3983 * NOTE: We can use ntfs_cluster_free() because we have already mapped
3984 * the whole run list and thus it doesn't matter that the attribute
3985 * record is in a transiently corrupted state at this moment in time.
3986 */
3987 err = ntfs_cluster_free(ni, 0, -1, ctx);
3988 if (err) {
3989 ntfs_error(sb, "Eeek! Failed to release allocated clusters");
3990 ntfs_debug("Ignoring error and leaving behind wasted clusters.\n");
3991 }
3992
3993 /* Throw away the now unused runlist. */
3994 kvfree(ni->runlist.rl);
3995 ni->runlist.rl = NULL;
3996 ni->runlist.count = 0;
3997 /* Update in-memory struct ntfs_attr. */
3998 NInoClearNonResident(ni);
3999 NInoClearCompressed(ni);
4000 ni->flags &= ~FILE_ATTR_COMPRESSED;
4001 NInoClearSparse(ni);
4002 ni->flags &= ~FILE_ATTR_SPARSE_FILE;
4003 NInoClearEncrypted(ni);
4004 ni->flags &= ~FILE_ATTR_ENCRYPTED;
4005 ni->initialized_size = ni->data_size;
4006 ni->allocated_size = ni->itype.compressed.size = (ni->data_size + 7) & ~7;
4007 ni->itype.compressed.block_size = 0;
4008 ni->itype.compressed.block_size_bits = ni->itype.compressed.block_clusters = 0;
4009 return 0;
4010 }
4011
4012 /*
4013 * ntfs_non_resident_attr_shrink - shrink a non-resident, open ntfs attribute
4014 * @ni: non-resident ntfs attribute to shrink
4015 * @newsize: new size (in bytes) to which to shrink the attribute
4016 *
4017 * Reduce the size of a non-resident, open ntfs attribute @na to @newsize bytes.
4018 */
ntfs_non_resident_attr_shrink(struct ntfs_inode * ni,const s64 newsize)4019 static int ntfs_non_resident_attr_shrink(struct ntfs_inode *ni, const s64 newsize)
4020 {
4021 struct ntfs_volume *vol;
4022 struct ntfs_attr_search_ctx *ctx;
4023 s64 first_free_vcn;
4024 s64 nr_freed_clusters;
4025 int err;
4026 struct ntfs_inode *base_ni;
4027
4028 ntfs_debug("Inode 0x%llx attr 0x%x new size %lld\n",
4029 (unsigned long long)ni->mft_no, ni->type, (long long)newsize);
4030
4031 vol = ni->vol;
4032
4033 if (NInoAttr(ni))
4034 base_ni = ni->ext.base_ntfs_ino;
4035 else
4036 base_ni = ni;
4037
4038 /*
4039 * Check the attribute type and the corresponding minimum size
4040 * against @newsize and fail if @newsize is too small.
4041 */
4042 err = ntfs_attr_size_bounds_check(vol, ni->type, newsize);
4043 if (err) {
4044 if (err == -ERANGE)
4045 ntfs_debug("Eeek! Size bounds check failed. Aborting...\n");
4046 else if (err == -ENOENT)
4047 err = -EIO;
4048 return err;
4049 }
4050
4051 /* The first cluster outside the new allocation. */
4052 if (NInoCompressed(ni))
4053 /*
4054 * For compressed files we must keep full compressions blocks,
4055 * but currently we do not decompress/recompress the last
4056 * block to truncate the data, so we may leave more allocated
4057 * clusters than really needed.
4058 */
4059 first_free_vcn = ntfs_bytes_to_cluster(vol,
4060 ((newsize - 1) | (ni->itype.compressed.block_size - 1)) + 1);
4061 else
4062 first_free_vcn =
4063 ntfs_bytes_to_cluster(vol, newsize + vol->cluster_size - 1);
4064
4065 if (first_free_vcn < 0)
4066 return -EINVAL;
4067 /*
4068 * Compare the new allocation with the old one and only deallocate
4069 * clusters if there is a change.
4070 */
4071 if (ntfs_bytes_to_cluster(vol, ni->allocated_size) != first_free_vcn) {
4072 struct ntfs_attr_search_ctx *ctx;
4073
4074 err = ntfs_attr_map_whole_runlist(ni);
4075 if (err) {
4076 ntfs_debug("Eeek! ntfs_attr_map_whole_runlist failed.\n");
4077 return err;
4078 }
4079
4080 ctx = ntfs_attr_get_search_ctx(ni, NULL);
4081 if (!ctx) {
4082 ntfs_error(vol->sb, "%s: Failed to get search context", __func__);
4083 return -ENOMEM;
4084 }
4085
4086 /* Deallocate all clusters starting with the first free one. */
4087 nr_freed_clusters = ntfs_cluster_free(ni, first_free_vcn, -1, ctx);
4088 if (nr_freed_clusters < 0) {
4089 ntfs_debug("Eeek! Freeing of clusters failed. Aborting...\n");
4090 ntfs_attr_put_search_ctx(ctx);
4091 return (int)nr_freed_clusters;
4092 }
4093 ntfs_attr_put_search_ctx(ctx);
4094
4095 /* Truncate the runlist itself. */
4096 if (ntfs_rl_truncate_nolock(vol, &ni->runlist, first_free_vcn)) {
4097 /*
4098 * Failed to truncate the runlist, so just throw it
4099 * away, it will be mapped afresh on next use.
4100 */
4101 kvfree(ni->runlist.rl);
4102 ni->runlist.rl = NULL;
4103 ntfs_error(vol->sb, "Eeek! Run list truncation failed.\n");
4104 return -EIO;
4105 }
4106
4107 /* Prepare to mapping pairs update. */
4108 ni->allocated_size = ntfs_cluster_to_bytes(vol, first_free_vcn);
4109
4110 if (NInoSparse(ni) || NInoCompressed(ni)) {
4111 if (nr_freed_clusters) {
4112 ni->itype.compressed.size -=
4113 ntfs_cluster_to_bytes(vol, nr_freed_clusters);
4114 VFS_I(base_ni)->i_blocks = ni->itype.compressed.size >> 9;
4115 }
4116 } else
4117 VFS_I(base_ni)->i_blocks = ni->allocated_size >> 9;
4118
4119 /* Write mapping pairs for new runlist. */
4120 err = ntfs_attr_update_mapping_pairs(ni, 0 /*first_free_vcn*/);
4121 if (err) {
4122 ntfs_debug("Eeek! Mapping pairs update failed. Leaving inconstant metadata. Run chkdsk.\n");
4123 return err;
4124 }
4125 }
4126
4127 /* Get the first attribute record. */
4128 ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
4129 if (!ctx) {
4130 ntfs_error(vol->sb, "%s: Failed to get search context", __func__);
4131 return -ENOMEM;
4132 }
4133
4134 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len, CASE_SENSITIVE,
4135 0, NULL, 0, ctx);
4136 if (err) {
4137 if (err == -ENOENT)
4138 err = -EIO;
4139 ntfs_debug("Eeek! Lookup of first attribute extent failed. Leaving inconstant metadata.\n");
4140 goto put_err_out;
4141 }
4142
4143 /* Update data and initialized size. */
4144 ni->data_size = newsize;
4145 ctx->attr->data.non_resident.data_size = cpu_to_le64(newsize);
4146 if (newsize < ni->initialized_size) {
4147 ni->initialized_size = newsize;
4148 ctx->attr->data.non_resident.initialized_size = cpu_to_le64(newsize);
4149 }
4150 /* Update data size in the index. */
4151 if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
4152 NInoSetFileNameDirty(ni);
4153
4154 /* If the attribute now has zero size, make it resident. */
4155 if (!newsize && !NInoEncrypted(ni) && !NInoCompressed(ni)) {
4156 err = ntfs_attr_make_resident(ni, ctx);
4157 if (err) {
4158 /* If couldn't make resident, just continue. */
4159 if (err != -EPERM)
4160 ntfs_error(ni->vol->sb,
4161 "Failed to make attribute resident. Leaving as is...\n");
4162 }
4163 }
4164
4165 /* Set the inode dirty so it is written out later. */
4166 mark_mft_record_dirty(ctx->ntfs_ino);
4167 /* Done! */
4168 ntfs_attr_put_search_ctx(ctx);
4169 return 0;
4170 put_err_out:
4171 ntfs_attr_put_search_ctx(ctx);
4172 return err;
4173 }
4174
4175 /*
4176 * ntfs_non_resident_attr_expand - expand a non-resident, open ntfs attribute
4177 * @ni: non-resident ntfs attribute to expand
4178 * @prealloc_size: preallocation size (in bytes) to which to expand the attribute
4179 * @newsize: new size (in bytes) to which to expand the attribute
4180 * @holes: how to create a hole if expanding
4181 * @need_lock: whether mrec lock is needed or not
4182 *
4183 * Expand the size of a non-resident, open ntfs attribute @na to @newsize bytes,
4184 * by allocating new clusters.
4185 */
ntfs_non_resident_attr_expand(struct ntfs_inode * ni,const s64 newsize,const s64 prealloc_size,unsigned int holes,bool need_lock)4186 static int ntfs_non_resident_attr_expand(struct ntfs_inode *ni, const s64 newsize,
4187 const s64 prealloc_size, unsigned int holes, bool need_lock)
4188 {
4189 s64 lcn_seek_from;
4190 s64 first_free_vcn;
4191 struct ntfs_volume *vol;
4192 struct ntfs_attr_search_ctx *ctx = NULL;
4193 struct runlist_element *rl, *rln;
4194 s64 org_alloc_size, org_compressed_size;
4195 int err, err2;
4196 struct ntfs_inode *base_ni;
4197 struct super_block *sb = ni->vol->sb;
4198 size_t new_rl_count;
4199
4200 ntfs_debug("Inode 0x%llx, attr 0x%x, new size %lld old size %lld\n",
4201 (unsigned long long)ni->mft_no, ni->type,
4202 (long long)newsize, (long long)ni->data_size);
4203
4204 vol = ni->vol;
4205
4206 if (NInoAttr(ni))
4207 base_ni = ni->ext.base_ntfs_ino;
4208 else
4209 base_ni = ni;
4210
4211 /*
4212 * Check the attribute type and the corresponding maximum size
4213 * against @newsize and fail if @newsize is too big.
4214 */
4215 err = ntfs_attr_size_bounds_check(vol, ni->type, newsize);
4216 if (err < 0) {
4217 ntfs_error(sb, "%s: bounds check failed", __func__);
4218 return err;
4219 }
4220
4221 /* Save for future use. */
4222 org_alloc_size = ni->allocated_size;
4223 org_compressed_size = ni->itype.compressed.size;
4224
4225 /* The first cluster outside the new allocation. */
4226 if (prealloc_size)
4227 first_free_vcn =
4228 ntfs_bytes_to_cluster(vol, prealloc_size + vol->cluster_size - 1);
4229 else
4230 first_free_vcn =
4231 ntfs_bytes_to_cluster(vol, newsize + vol->cluster_size - 1);
4232 if (first_free_vcn < 0)
4233 return -EFBIG;
4234
4235 /*
4236 * Compare the new allocation with the old one and only allocate
4237 * clusters if there is a change.
4238 */
4239 if (ntfs_bytes_to_cluster(vol, ni->allocated_size) < first_free_vcn) {
4240 err = ntfs_attr_map_whole_runlist(ni);
4241 if (err) {
4242 ntfs_error(sb, "ntfs_attr_map_whole_runlist failed");
4243 return err;
4244 }
4245
4246 /*
4247 * If we extend $DATA attribute on NTFS 3+ volume, we can add
4248 * sparse runs instead of real allocation of clusters.
4249 */
4250 if ((ni->type == AT_DATA && (vol->major_ver >= 3 || !NInoSparseDisabled(ni))) &&
4251 (holes != HOLES_NO)) {
4252 if (NInoCompressed(ni)) {
4253 int last = 0, i = 0;
4254 s64 alloc_size;
4255 u64 more_entries = round_up(first_free_vcn -
4256 ntfs_bytes_to_cluster(vol, ni->allocated_size),
4257 ni->itype.compressed.block_clusters);
4258
4259 do_div(more_entries, ni->itype.compressed.block_clusters);
4260
4261 while (ni->runlist.rl[last].length)
4262 last++;
4263
4264 rl = ntfs_rl_realloc(ni->runlist.rl, last + 1,
4265 last + more_entries + 1);
4266 if (IS_ERR(rl)) {
4267 err = -ENOMEM;
4268 goto put_err_out;
4269 }
4270
4271 alloc_size = ni->allocated_size;
4272 while (i++ < more_entries) {
4273 rl[last].vcn = ntfs_bytes_to_cluster(vol,
4274 round_up(alloc_size, vol->cluster_size));
4275 rl[last].length = ni->itype.compressed.block_clusters -
4276 (rl[last].vcn &
4277 (ni->itype.compressed.block_clusters - 1));
4278 rl[last].lcn = LCN_HOLE;
4279 last++;
4280 alloc_size += ni->itype.compressed.block_size;
4281 }
4282
4283 rl[last].vcn = first_free_vcn;
4284 rl[last].lcn = LCN_ENOENT;
4285 rl[last].length = 0;
4286
4287 ni->runlist.rl = rl;
4288 ni->runlist.count += more_entries;
4289 } else {
4290 rl = kmalloc(sizeof(struct runlist_element) * 2, GFP_NOFS);
4291 if (!rl) {
4292 err = -ENOMEM;
4293 goto put_err_out;
4294 }
4295
4296 rl[0].vcn = ntfs_bytes_to_cluster(vol, ni->allocated_size);
4297 rl[0].lcn = LCN_HOLE;
4298 rl[0].length = first_free_vcn -
4299 ntfs_bytes_to_cluster(vol, ni->allocated_size);
4300 rl[1].vcn = first_free_vcn;
4301 rl[1].lcn = LCN_ENOENT;
4302 rl[1].length = 0;
4303 }
4304 } else {
4305 /*
4306 * Determine first after last LCN of attribute.
4307 * We will start seek clusters from this LCN to avoid
4308 * fragmentation. If there are no valid LCNs in the
4309 * attribute let the cluster allocator choose the
4310 * starting LCN.
4311 */
4312 lcn_seek_from = -1;
4313 if (ni->runlist.rl->length) {
4314 /* Seek to the last run list element. */
4315 for (rl = ni->runlist.rl; (rl + 1)->length; rl++)
4316 ;
4317 /*
4318 * If the last LCN is a hole or similar seek
4319 * back to last valid LCN.
4320 */
4321 while (rl->lcn < 0 && rl != ni->runlist.rl)
4322 rl--;
4323 /*
4324 * Only set lcn_seek_from it the LCN is valid.
4325 */
4326 if (rl->lcn >= 0)
4327 lcn_seek_from = rl->lcn + rl->length;
4328 }
4329
4330 rl = ntfs_cluster_alloc(vol,
4331 ntfs_bytes_to_cluster(vol, ni->allocated_size),
4332 first_free_vcn -
4333 ntfs_bytes_to_cluster(vol, ni->allocated_size),
4334 lcn_seek_from, DATA_ZONE, false, false, false);
4335 if (IS_ERR(rl)) {
4336 ntfs_debug("Cluster allocation failed (%lld)",
4337 (long long)first_free_vcn -
4338 ntfs_bytes_to_cluster(vol, ni->allocated_size));
4339 return PTR_ERR(rl);
4340 }
4341 }
4342
4343 if (!NInoCompressed(ni)) {
4344 /* Append new clusters to attribute runlist. */
4345 rln = ntfs_runlists_merge(&ni->runlist, rl, 0, &new_rl_count);
4346 if (IS_ERR(rln)) {
4347 /* Failed, free just allocated clusters. */
4348 ntfs_error(sb, "Run list merge failed");
4349 ntfs_cluster_free_from_rl(vol, rl);
4350 kvfree(rl);
4351 return -EIO;
4352 }
4353 ni->runlist.rl = rln;
4354 ni->runlist.count = new_rl_count;
4355 }
4356
4357 /* Prepare to mapping pairs update. */
4358 ni->allocated_size = ntfs_cluster_to_bytes(vol, first_free_vcn);
4359 err = ntfs_attr_update_mapping_pairs(ni, 0);
4360 if (err) {
4361 ntfs_debug("Mapping pairs update failed");
4362 goto rollback;
4363 }
4364 }
4365
4366 ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
4367 if (!ctx) {
4368 err = -ENOMEM;
4369 if (ni->allocated_size == org_alloc_size)
4370 return err;
4371 goto rollback;
4372 }
4373
4374 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len, CASE_SENSITIVE,
4375 0, NULL, 0, ctx);
4376 if (err) {
4377 if (err == -ENOENT)
4378 err = -EIO;
4379 if (ni->allocated_size != org_alloc_size)
4380 goto rollback;
4381 goto put_err_out;
4382 }
4383
4384 /* Update data size. */
4385 ni->data_size = newsize;
4386 ctx->attr->data.non_resident.data_size = cpu_to_le64(newsize);
4387 /* Update data size in the index. */
4388 if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
4389 NInoSetFileNameDirty(ni);
4390 /* Set the inode dirty so it is written out later. */
4391 mark_mft_record_dirty(ctx->ntfs_ino);
4392 /* Done! */
4393 ntfs_attr_put_search_ctx(ctx);
4394 return 0;
4395 rollback:
4396 /* Free allocated clusters. */
4397 err2 = ntfs_cluster_free(ni, ntfs_bytes_to_cluster(vol, org_alloc_size),
4398 -1, ctx);
4399 if (err2)
4400 ntfs_debug("Leaking clusters");
4401
4402 /* Now, truncate the runlist itself. */
4403 if (need_lock)
4404 down_write(&ni->runlist.lock);
4405 err2 = ntfs_rl_truncate_nolock(vol, &ni->runlist,
4406 ntfs_bytes_to_cluster(vol, org_alloc_size));
4407 if (need_lock)
4408 up_write(&ni->runlist.lock);
4409 if (err2) {
4410 /*
4411 * Failed to truncate the runlist, so just throw it away, it
4412 * will be mapped afresh on next use.
4413 */
4414 kvfree(ni->runlist.rl);
4415 ni->runlist.rl = NULL;
4416 ntfs_error(sb, "Couldn't truncate runlist. Rollback failed");
4417 } else {
4418 /* Prepare to mapping pairs update. */
4419 ni->allocated_size = org_alloc_size;
4420 /* Restore mapping pairs. */
4421 if (need_lock)
4422 down_read(&ni->runlist.lock);
4423 if (ntfs_attr_update_mapping_pairs(ni, 0))
4424 ntfs_error(sb, "Failed to restore old mapping pairs");
4425 if (need_lock)
4426 up_read(&ni->runlist.lock);
4427
4428 if (NInoSparse(ni) || NInoCompressed(ni)) {
4429 ni->itype.compressed.size = org_compressed_size;
4430 VFS_I(base_ni)->i_blocks = ni->itype.compressed.size >> 9;
4431 } else
4432 VFS_I(base_ni)->i_blocks = ni->allocated_size >> 9;
4433 }
4434 if (ctx)
4435 ntfs_attr_put_search_ctx(ctx);
4436 return err;
4437 put_err_out:
4438 if (ctx)
4439 ntfs_attr_put_search_ctx(ctx);
4440 return err;
4441 }
4442
4443 /*
4444 * ntfs_resident_attr_resize - resize a resident, open ntfs attribute
4445 * @attr_ni: resident ntfs inode to resize
4446 * @newsize: new size (in bytes) to which to resize the attribute
4447 * @prealloc_size: preallocation size (in bytes) to which to resize the attribute
4448 * @holes: flags indicating how to handle holes
4449 *
4450 * Change the size of a resident, open ntfs attribute @na to @newsize bytes.
4451 */
ntfs_resident_attr_resize(struct ntfs_inode * attr_ni,const s64 newsize,const s64 prealloc_size,unsigned int holes)4452 static int ntfs_resident_attr_resize(struct ntfs_inode *attr_ni, const s64 newsize,
4453 const s64 prealloc_size, unsigned int holes)
4454 {
4455 struct ntfs_attr_search_ctx *ctx;
4456 struct ntfs_volume *vol = attr_ni->vol;
4457 struct super_block *sb = vol->sb;
4458 int err = -EIO;
4459 struct ntfs_inode *base_ni, *ext_ni = NULL;
4460
4461 attr_resize_again:
4462 ntfs_debug("Inode 0x%llx attr 0x%x new size %lld\n",
4463 (unsigned long long)attr_ni->mft_no, attr_ni->type,
4464 (long long)newsize);
4465
4466 if (NInoAttr(attr_ni))
4467 base_ni = attr_ni->ext.base_ntfs_ino;
4468 else
4469 base_ni = attr_ni;
4470
4471 /* Get the attribute record that needs modification. */
4472 ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
4473 if (!ctx) {
4474 ntfs_error(sb, "%s: Failed to get search context", __func__);
4475 return -ENOMEM;
4476 }
4477
4478 err = ntfs_attr_lookup(attr_ni->type, attr_ni->name, attr_ni->name_len,
4479 0, 0, NULL, 0, ctx);
4480 if (err) {
4481 ntfs_error(sb, "ntfs_attr_lookup failed");
4482 goto put_err_out;
4483 }
4484
4485 /*
4486 * Check the attribute type and the corresponding minimum and maximum
4487 * sizes against @newsize and fail if @newsize is out of bounds.
4488 */
4489 err = ntfs_attr_size_bounds_check(vol, attr_ni->type, newsize);
4490 if (err) {
4491 if (err == -ENOENT)
4492 err = -EIO;
4493 ntfs_debug("%s: bounds check failed", __func__);
4494 goto put_err_out;
4495 }
4496 /*
4497 * If @newsize is bigger than the mft record we need to make the
4498 * attribute non-resident if the attribute type supports it. If it is
4499 * smaller we can go ahead and attempt the resize.
4500 */
4501 if (newsize < vol->mft_record_size) {
4502 /* Perform the resize of the attribute record. */
4503 err = ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr,
4504 newsize);
4505 if (!err) {
4506 /* Update attribute size everywhere. */
4507 attr_ni->data_size = attr_ni->initialized_size = newsize;
4508 attr_ni->allocated_size = (newsize + 7) & ~7;
4509 if (NInoCompressed(attr_ni) || NInoSparse(attr_ni))
4510 attr_ni->itype.compressed.size = attr_ni->allocated_size;
4511 if (attr_ni->type == AT_DATA && attr_ni->name == AT_UNNAMED)
4512 NInoSetFileNameDirty(attr_ni);
4513 goto resize_done;
4514 }
4515
4516 /* Prefer AT_INDEX_ALLOCATION instead of AT_ATTRIBUTE_LIST */
4517 if (err == -ENOSPC && ctx->attr->type == AT_INDEX_ROOT)
4518 goto put_err_out;
4519
4520 }
4521 /* There is not enough space in the mft record to perform the resize. */
4522
4523 /* Make the attribute non-resident if possible. */
4524 err = ntfs_attr_make_non_resident(attr_ni,
4525 le32_to_cpu(ctx->attr->data.resident.value_length));
4526 if (!err) {
4527 mark_mft_record_dirty(ctx->ntfs_ino);
4528 ntfs_attr_put_search_ctx(ctx);
4529 /* Resize non-resident attribute */
4530 return ntfs_non_resident_attr_expand(attr_ni, newsize, prealloc_size, holes, true);
4531 } else if (err != -ENOSPC && err != -EPERM) {
4532 ntfs_error(sb, "Failed to make attribute non-resident");
4533 goto put_err_out;
4534 }
4535
4536 /* Try to make other attributes non-resident and retry each time. */
4537 ntfs_attr_reinit_search_ctx(ctx);
4538 while (!(err = ntfs_attr_lookup(AT_UNUSED, NULL, 0, 0, 0, NULL, 0, ctx))) {
4539 struct inode *tvi;
4540 struct attr_record *a;
4541
4542 a = ctx->attr;
4543 if (a->non_resident || a->type == AT_ATTRIBUTE_LIST)
4544 continue;
4545
4546 if (ntfs_attr_can_be_non_resident(vol, a->type))
4547 continue;
4548
4549 /*
4550 * Check out whether convert is reasonable. Assume that mapping
4551 * pairs will take 8 bytes.
4552 */
4553 if (le32_to_cpu(a->length) <= (sizeof(struct attr_record) - sizeof(s64)) +
4554 ((a->name_length * sizeof(__le16) + 7) & ~7) + 8)
4555 continue;
4556
4557 if (a->type == AT_DATA)
4558 tvi = ntfs_iget(sb, base_ni->mft_no);
4559 else
4560 tvi = ntfs_attr_iget(VFS_I(base_ni), a->type,
4561 (__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
4562 a->name_length);
4563 if (IS_ERR(tvi)) {
4564 ntfs_error(sb, "Couldn't open attribute");
4565 continue;
4566 }
4567
4568 if (ntfs_attr_make_non_resident(NTFS_I(tvi),
4569 le32_to_cpu(ctx->attr->data.resident.value_length))) {
4570 iput(tvi);
4571 continue;
4572 }
4573
4574 mark_mft_record_dirty(ctx->ntfs_ino);
4575 iput(tvi);
4576 ntfs_attr_put_search_ctx(ctx);
4577 goto attr_resize_again;
4578 }
4579
4580 /* Check whether error occurred. */
4581 if (err != -ENOENT) {
4582 ntfs_error(sb, "%s: Attribute lookup failed 1", __func__);
4583 goto put_err_out;
4584 }
4585
4586 /*
4587 * The standard information and attribute list attributes can't be
4588 * moved out from the base MFT record, so try to move out others.
4589 */
4590 if (attr_ni->type == AT_STANDARD_INFORMATION ||
4591 attr_ni->type == AT_ATTRIBUTE_LIST) {
4592 ntfs_attr_put_search_ctx(ctx);
4593
4594 if (!NInoAttrList(base_ni)) {
4595 err = ntfs_inode_add_attrlist(base_ni);
4596 if (err)
4597 return err;
4598 }
4599
4600 err = ntfs_inode_free_space(base_ni, sizeof(struct attr_record));
4601 if (err) {
4602 err = -ENOSPC;
4603 ntfs_error(sb,
4604 "Couldn't free space in the MFT record to make attribute list non resident");
4605 return err;
4606 }
4607 err = ntfs_attrlist_update(base_ni);
4608 if (err)
4609 return err;
4610 goto attr_resize_again;
4611 }
4612
4613 /*
4614 * Move the attribute to a new mft record, creating an attribute list
4615 * attribute or modifying it if it is already present.
4616 */
4617
4618 /* Point search context back to attribute which we need resize. */
4619 ntfs_attr_reinit_search_ctx(ctx);
4620 err = ntfs_attr_lookup(attr_ni->type, attr_ni->name, attr_ni->name_len,
4621 CASE_SENSITIVE, 0, NULL, 0, ctx);
4622 if (err) {
4623 ntfs_error(sb, "%s: Attribute lookup failed 2", __func__);
4624 goto put_err_out;
4625 }
4626
4627 /*
4628 * Check whether attribute is already single in this MFT record.
4629 * 8 added for the attribute terminator.
4630 */
4631 if (le32_to_cpu(ctx->mrec->bytes_in_use) ==
4632 le16_to_cpu(ctx->mrec->attrs_offset) + le32_to_cpu(ctx->attr->length) + 8) {
4633 err = -ENOSPC;
4634 ntfs_debug("MFT record is filled with one attribute\n");
4635 goto put_err_out;
4636 }
4637
4638 /* Add attribute list if not present. */
4639 if (!NInoAttrList(base_ni)) {
4640 ntfs_attr_put_search_ctx(ctx);
4641 err = ntfs_inode_add_attrlist(base_ni);
4642 if (err)
4643 return err;
4644 goto attr_resize_again;
4645 }
4646
4647 /* Allocate new mft record. */
4648 err = ntfs_mft_record_alloc(base_ni->vol, 0, &ext_ni, base_ni, NULL);
4649 if (err) {
4650 ntfs_error(sb, "Couldn't allocate MFT record");
4651 goto put_err_out;
4652 }
4653 unmap_mft_record(ext_ni);
4654
4655 /* Move attribute to it. */
4656 err = ntfs_attr_record_move_to(ctx, ext_ni);
4657 if (err) {
4658 ntfs_error(sb, "Couldn't move attribute to new MFT record");
4659 err = -ENOMEM;
4660 goto put_err_out;
4661 }
4662
4663 err = ntfs_attrlist_update(base_ni);
4664 if (err < 0)
4665 goto put_err_out;
4666
4667 ntfs_attr_put_search_ctx(ctx);
4668 /* Try to perform resize once again. */
4669 goto attr_resize_again;
4670
4671 resize_done:
4672 /*
4673 * Set the inode (and its base inode if it exists) dirty so it is
4674 * written out later.
4675 */
4676 mark_mft_record_dirty(ctx->ntfs_ino);
4677 ntfs_attr_put_search_ctx(ctx);
4678 return 0;
4679
4680 put_err_out:
4681 ntfs_attr_put_search_ctx(ctx);
4682 return err;
4683 }
4684
__ntfs_attr_truncate_vfs(struct ntfs_inode * ni,const s64 newsize,const s64 i_size)4685 int __ntfs_attr_truncate_vfs(struct ntfs_inode *ni, const s64 newsize,
4686 const s64 i_size)
4687 {
4688 int err = 0;
4689
4690 if (newsize < 0 ||
4691 (ni->mft_no == FILE_MFT && ni->type == AT_DATA)) {
4692 ntfs_debug("Invalid arguments passed.\n");
4693 return -EINVAL;
4694 }
4695
4696 ntfs_debug("Entering for inode 0x%llx, attr 0x%x, size %lld\n",
4697 (unsigned long long)ni->mft_no, ni->type, newsize);
4698
4699 if (NInoNonResident(ni)) {
4700 if (newsize > i_size) {
4701 down_write(&ni->runlist.lock);
4702 err = ntfs_non_resident_attr_expand(ni, newsize, 0,
4703 NVolDisableSparse(ni->vol) ?
4704 HOLES_NO : HOLES_OK,
4705 false);
4706 up_write(&ni->runlist.lock);
4707 } else
4708 err = ntfs_non_resident_attr_shrink(ni, newsize);
4709 } else
4710 err = ntfs_resident_attr_resize(ni, newsize, 0,
4711 NVolDisableSparse(ni->vol) ?
4712 HOLES_NO : HOLES_OK);
4713 ntfs_debug("Return status %d\n", err);
4714 return err;
4715 }
4716
ntfs_attr_expand(struct ntfs_inode * ni,const s64 newsize,const s64 prealloc_size)4717 int ntfs_attr_expand(struct ntfs_inode *ni, const s64 newsize, const s64 prealloc_size)
4718 {
4719 int err = 0;
4720
4721 if (newsize < 0 ||
4722 (ni->mft_no == FILE_MFT && ni->type == AT_DATA)) {
4723 ntfs_debug("Invalid arguments passed.\n");
4724 return -EINVAL;
4725 }
4726
4727 ntfs_debug("Entering for inode 0x%llx, attr 0x%x, size %lld\n",
4728 (unsigned long long)ni->mft_no, ni->type, newsize);
4729
4730 if (ni->data_size == newsize) {
4731 ntfs_debug("Size is already ok\n");
4732 return 0;
4733 }
4734
4735 /*
4736 * Encrypted attributes are not supported. We return access denied,
4737 * which is what Windows NT4 does, too.
4738 */
4739 if (NInoEncrypted(ni)) {
4740 pr_err("Failed to truncate encrypted attribute\n");
4741 return -EACCES;
4742 }
4743
4744 if (NInoNonResident(ni)) {
4745 if (newsize > ni->data_size)
4746 err = ntfs_non_resident_attr_expand(ni, newsize, prealloc_size,
4747 NVolDisableSparse(ni->vol) ?
4748 HOLES_NO : HOLES_OK, true);
4749 } else
4750 err = ntfs_resident_attr_resize(ni, newsize, prealloc_size,
4751 NVolDisableSparse(ni->vol) ?
4752 HOLES_NO : HOLES_OK);
4753 if (!err)
4754 i_size_write(VFS_I(ni), newsize);
4755 ntfs_debug("Return status %d\n", err);
4756 return err;
4757 }
4758
4759 /*
4760 * ntfs_attr_truncate_i - resize an ntfs attribute
4761 * @ni: open ntfs inode to resize
4762 * @newsize: new size (in bytes) to which to resize the attribute
4763 * @holes: how to create a hole if expanding
4764 *
4765 * Change the size of an open ntfs attribute @na to @newsize bytes. If the
4766 * attribute is made bigger and the attribute is resident the newly
4767 * "allocated" space is cleared and if the attribute is non-resident the
4768 * newly allocated space is marked as not initialised and no real allocation
4769 * on disk is performed.
4770 */
ntfs_attr_truncate_i(struct ntfs_inode * ni,const s64 newsize,unsigned int holes)4771 int ntfs_attr_truncate_i(struct ntfs_inode *ni, const s64 newsize, unsigned int holes)
4772 {
4773 int err;
4774
4775 if (newsize < 0 ||
4776 (ni->mft_no == FILE_MFT && ni->type == AT_DATA)) {
4777 ntfs_debug("Invalid arguments passed.\n");
4778 return -EINVAL;
4779 }
4780
4781 ntfs_debug("Entering for inode 0x%llx, attr 0x%x, size %lld\n",
4782 (unsigned long long)ni->mft_no, ni->type, newsize);
4783
4784 if (ni->data_size == newsize) {
4785 ntfs_debug("Size is already ok\n");
4786 return 0;
4787 }
4788
4789 /*
4790 * Encrypted attributes are not supported. We return access denied,
4791 * which is what Windows NT4 does, too.
4792 */
4793 if (NInoEncrypted(ni)) {
4794 pr_err("Failed to truncate encrypted attribute\n");
4795 return -EACCES;
4796 }
4797
4798 if (NInoCompressed(ni)) {
4799 pr_err("Failed to truncate compressed attribute\n");
4800 return -EOPNOTSUPP;
4801 }
4802
4803 if (NInoNonResident(ni)) {
4804 if (newsize > ni->data_size)
4805 err = ntfs_non_resident_attr_expand(ni, newsize, 0, holes, true);
4806 else
4807 err = ntfs_non_resident_attr_shrink(ni, newsize);
4808 } else
4809 err = ntfs_resident_attr_resize(ni, newsize, 0, holes);
4810 ntfs_debug("Return status %d\n", err);
4811 return err;
4812 }
4813
4814 /*
4815 * Resize an attribute, creating a hole if relevant
4816 */
ntfs_attr_truncate(struct ntfs_inode * ni,const s64 newsize)4817 int ntfs_attr_truncate(struct ntfs_inode *ni, const s64 newsize)
4818 {
4819 return ntfs_attr_truncate_i(ni, newsize,
4820 NVolDisableSparse(ni->vol) ?
4821 HOLES_NO : HOLES_OK);
4822 }
4823
ntfs_attr_map_cluster(struct ntfs_inode * ni,s64 vcn_start,s64 * lcn_start,s64 * lcn_count,s64 max_clu_count,bool * balloc,bool update_mp,bool skip_holes)4824 int ntfs_attr_map_cluster(struct ntfs_inode *ni, s64 vcn_start, s64 *lcn_start,
4825 s64 *lcn_count, s64 max_clu_count, bool *balloc, bool update_mp,
4826 bool skip_holes)
4827 {
4828 struct ntfs_volume *vol = ni->vol;
4829 struct ntfs_attr_search_ctx *ctx;
4830 struct runlist_element *rl, *rlc;
4831 s64 vcn = vcn_start, lcn, clu_count;
4832 s64 lcn_seek_from = -1;
4833 int err = 0;
4834 size_t new_rl_count;
4835
4836 err = ntfs_attr_map_whole_runlist(ni);
4837 if (err)
4838 return err;
4839
4840 if (NInoAttr(ni))
4841 ctx = ntfs_attr_get_search_ctx(ni->ext.base_ntfs_ino, NULL);
4842 else
4843 ctx = ntfs_attr_get_search_ctx(ni, NULL);
4844 if (!ctx) {
4845 ntfs_error(vol->sb, "%s: Failed to get search context", __func__);
4846 return -ENOMEM;
4847 }
4848
4849 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
4850 CASE_SENSITIVE, vcn, NULL, 0, ctx);
4851 if (err) {
4852 ntfs_error(vol->sb,
4853 "ntfs_attr_lookup failed, ntfs inode(mft_no : %llu) type : 0x%x, err : %d",
4854 ni->mft_no, ni->type, err);
4855 goto out;
4856 }
4857
4858 rl = ntfs_attr_find_vcn_nolock(ni, vcn, ctx);
4859 if (IS_ERR(rl)) {
4860 ntfs_error(vol->sb, "Failed to find run after mapping runlist.");
4861 err = PTR_ERR(rl);
4862 goto out;
4863 }
4864
4865 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
4866 clu_count = min(max_clu_count, rl->length - (vcn - rl->vcn));
4867 if (lcn >= LCN_HOLE) {
4868 if (lcn > LCN_DELALLOC ||
4869 (lcn == LCN_HOLE && skip_holes)) {
4870 *lcn_start = lcn;
4871 *lcn_count = clu_count;
4872 *balloc = false;
4873 goto out;
4874 }
4875 } else {
4876 WARN_ON(lcn == LCN_RL_NOT_MAPPED);
4877 if (lcn == LCN_ENOENT)
4878 err = -ENOENT;
4879 else
4880 err = -EIO;
4881 goto out;
4882 }
4883
4884 /* Search backwards to find the best lcn to start seek from. */
4885 rlc = rl;
4886 while (rlc->vcn) {
4887 rlc--;
4888 if (rlc->lcn >= 0) {
4889 /*
4890 * avoid fragmenting a compressed file
4891 * Windows does not do that, and that may
4892 * not be desirable for files which can
4893 * be updated
4894 */
4895 if (NInoCompressed(ni))
4896 lcn_seek_from = rlc->lcn + rlc->length;
4897 else
4898 lcn_seek_from = rlc->lcn + (vcn - rlc->vcn);
4899 break;
4900 }
4901 }
4902
4903 if (lcn_seek_from == -1) {
4904 /* Backwards search failed, search forwards. */
4905 rlc = rl;
4906 while (rlc->length) {
4907 rlc++;
4908 if (rlc->lcn >= 0) {
4909 lcn_seek_from = rlc->lcn - (rlc->vcn - vcn);
4910 if (lcn_seek_from < -1)
4911 lcn_seek_from = -1;
4912 break;
4913 }
4914 }
4915 }
4916
4917 rlc = ntfs_cluster_alloc(vol, vcn, clu_count, lcn_seek_from, DATA_ZONE,
4918 false, true, true);
4919 if (IS_ERR(rlc)) {
4920 err = PTR_ERR(rlc);
4921 goto out;
4922 }
4923
4924 WARN_ON(rlc->vcn != vcn);
4925 lcn = rlc->lcn;
4926 clu_count = rlc->length;
4927
4928 rl = ntfs_runlists_merge(&ni->runlist, rlc, 0, &new_rl_count);
4929 if (IS_ERR(rl)) {
4930 ntfs_error(vol->sb, "Failed to merge runlists");
4931 err = PTR_ERR(rl);
4932 if (ntfs_cluster_free_from_rl(vol, rlc))
4933 ntfs_error(vol->sb, "Failed to free hot clusters.");
4934 kvfree(rlc);
4935 goto out;
4936 }
4937 ni->runlist.rl = rl;
4938 ni->runlist.count = new_rl_count;
4939
4940 if (!update_mp) {
4941 u64 free = atomic64_read(&vol->free_clusters) * 100;
4942
4943 do_div(free, vol->nr_clusters);
4944 if (free <= 5)
4945 update_mp = true;
4946 }
4947
4948 if (update_mp) {
4949 ntfs_attr_reinit_search_ctx(ctx);
4950 err = ntfs_attr_update_mapping_pairs(ni, 0);
4951 if (err) {
4952 int err2;
4953
4954 err2 = ntfs_cluster_free(ni, vcn, clu_count, ctx);
4955 if (err2 < 0)
4956 ntfs_error(vol->sb,
4957 "Failed to free cluster allocation. Leaving inconstant metadata.\n");
4958 goto out;
4959 }
4960 } else {
4961 VFS_I(ni)->i_blocks += clu_count << (vol->cluster_size_bits - 9);
4962 NInoSetRunlistDirty(ni);
4963 mark_mft_record_dirty(ni);
4964 }
4965
4966 *lcn_start = lcn;
4967 *lcn_count = clu_count;
4968 *balloc = true;
4969 out:
4970 ntfs_attr_put_search_ctx(ctx);
4971 return err;
4972 }
4973
4974 /*
4975 * ntfs_attr_rm - remove attribute from ntfs inode
4976 * @ni: opened ntfs attribute to delete
4977 *
4978 * Remove attribute and all it's extents from ntfs inode. If attribute was non
4979 * resident also free all clusters allocated by attribute.
4980 */
ntfs_attr_rm(struct ntfs_inode * ni)4981 int ntfs_attr_rm(struct ntfs_inode *ni)
4982 {
4983 struct ntfs_attr_search_ctx *ctx;
4984 int err = 0, ret = 0;
4985 struct ntfs_inode *base_ni;
4986 struct super_block *sb = ni->vol->sb;
4987
4988 if (NInoAttr(ni))
4989 base_ni = ni->ext.base_ntfs_ino;
4990 else
4991 base_ni = ni;
4992
4993 ntfs_debug("Entering for inode 0x%llx, attr 0x%x.\n",
4994 (long long) ni->mft_no, ni->type);
4995
4996 /* Free cluster allocation. */
4997 if (NInoNonResident(ni)) {
4998 struct ntfs_attr_search_ctx *ctx;
4999
5000 err = ntfs_attr_map_whole_runlist(ni);
5001 if (err)
5002 return err;
5003 ctx = ntfs_attr_get_search_ctx(ni, NULL);
5004 if (!ctx) {
5005 ntfs_error(sb, "%s: Failed to get search context", __func__);
5006 return -ENOMEM;
5007 }
5008
5009 ret = ntfs_cluster_free(ni, 0, -1, ctx);
5010 if (ret < 0)
5011 ntfs_error(sb,
5012 "Failed to free cluster allocation. Leaving inconstant metadata.\n");
5013 ntfs_attr_put_search_ctx(ctx);
5014 }
5015
5016 /* Search for attribute extents and remove them all. */
5017 ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
5018 if (!ctx) {
5019 ntfs_error(sb, "%s: Failed to get search context", __func__);
5020 return -ENOMEM;
5021 }
5022 while (!(err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
5023 CASE_SENSITIVE, 0, NULL, 0, ctx))) {
5024 err = ntfs_attr_record_rm(ctx);
5025 if (err) {
5026 ntfs_error(sb,
5027 "Failed to remove attribute extent. Leaving inconstant metadata.\n");
5028 ret = err;
5029 }
5030 ntfs_attr_reinit_search_ctx(ctx);
5031 }
5032 ntfs_attr_put_search_ctx(ctx);
5033 if (err != -ENOENT) {
5034 ntfs_error(sb, "Attribute lookup failed. Probably leaving inconstant metadata.\n");
5035 ret = err;
5036 }
5037
5038 return ret;
5039 }
5040
ntfs_attr_exist(struct ntfs_inode * ni,const __le32 type,__le16 * name,u32 name_len)5041 int ntfs_attr_exist(struct ntfs_inode *ni, const __le32 type, __le16 *name,
5042 u32 name_len)
5043 {
5044 struct ntfs_attr_search_ctx *ctx;
5045 int ret;
5046
5047 ntfs_debug("Entering\n");
5048
5049 ctx = ntfs_attr_get_search_ctx(ni, NULL);
5050 if (!ctx) {
5051 ntfs_error(ni->vol->sb, "%s: Failed to get search context",
5052 __func__);
5053 return 0;
5054 }
5055
5056 ret = ntfs_attr_lookup(type, name, name_len, CASE_SENSITIVE,
5057 0, NULL, 0, ctx);
5058 ntfs_attr_put_search_ctx(ctx);
5059
5060 return !ret;
5061 }
5062
ntfs_attr_remove(struct ntfs_inode * ni,const __le32 type,__le16 * name,u32 name_len)5063 int ntfs_attr_remove(struct ntfs_inode *ni, const __le32 type, __le16 *name,
5064 u32 name_len)
5065 {
5066 int err;
5067 struct inode *attr_vi;
5068 struct ntfs_inode *attr_ni;
5069
5070 ntfs_debug("Entering\n");
5071
5072 if (!ni)
5073 return -EINVAL;
5074
5075 attr_vi = ntfs_attr_iget(VFS_I(ni), type, name, name_len);
5076 if (IS_ERR(attr_vi)) {
5077 err = PTR_ERR(attr_vi);
5078 ntfs_error(ni->vol->sb, "Failed to open attribute 0x%02x of inode 0x%llx",
5079 type, (unsigned long long)ni->mft_no);
5080 return err;
5081 }
5082 attr_ni = NTFS_I(attr_vi);
5083
5084 err = ntfs_attr_rm(attr_ni);
5085 if (err)
5086 ntfs_error(ni->vol->sb, "Failed to remove attribute 0x%02x of inode 0x%llx",
5087 type, (unsigned long long)ni->mft_no);
5088 iput(attr_vi);
5089 return err;
5090 }
5091
5092 /*
5093 * ntfs_attr_readall - read the entire data from an ntfs attribute
5094 * @ni: open ntfs inode in which the ntfs attribute resides
5095 * @type: attribute type
5096 * @name: attribute name in little endian Unicode or AT_UNNAMED or NULL
5097 * @name_len: length of attribute @name in Unicode characters (if @name given)
5098 * @data_size: if non-NULL then store here the data size
5099 *
5100 * This function will read the entire content of an ntfs attribute.
5101 * If @name is AT_UNNAMED then look specifically for an unnamed attribute.
5102 * If @name is NULL then the attribute could be either named or not.
5103 * In both those cases @name_len is not used at all.
5104 *
5105 * On success a buffer is allocated with the content of the attribute
5106 * and which needs to be freed when it's not needed anymore. If the
5107 * @data_size parameter is non-NULL then the data size is set there.
5108 */
ntfs_attr_readall(struct ntfs_inode * ni,const __le32 type,__le16 * name,u32 name_len,s64 * data_size)5109 void *ntfs_attr_readall(struct ntfs_inode *ni, const __le32 type,
5110 __le16 *name, u32 name_len, s64 *data_size)
5111 {
5112 struct ntfs_inode *bmp_ni;
5113 struct inode *bmp_vi;
5114 void *data, *ret = NULL;
5115 s64 size;
5116 struct super_block *sb = ni->vol->sb;
5117
5118 ntfs_debug("Entering\n");
5119
5120 bmp_vi = ntfs_attr_iget(VFS_I(ni), type, name, name_len);
5121 if (IS_ERR(bmp_vi)) {
5122 ntfs_debug("ntfs_attr_iget failed");
5123 goto err_exit;
5124 }
5125 bmp_ni = NTFS_I(bmp_vi);
5126
5127 if (bmp_ni->data_size > NTFS_ATTR_READALL_MAX_SIZE &&
5128 (bmp_ni->type != AT_BITMAP ||
5129 bmp_ni->data_size > ((ni->vol->nr_clusters + 7) >> 3))) {
5130 ntfs_error(sb, "Invalid attribute data size");
5131 goto out;
5132 }
5133
5134 data = kvmalloc(bmp_ni->data_size, GFP_NOFS);
5135 if (!data)
5136 goto out;
5137
5138 size = ntfs_inode_attr_pread(VFS_I(bmp_ni), 0, bmp_ni->data_size,
5139 (u8 *)data);
5140 if (size != bmp_ni->data_size) {
5141 ntfs_error(sb, "ntfs_attr_pread failed");
5142 kvfree(data);
5143 goto out;
5144 }
5145 ret = data;
5146 if (data_size)
5147 *data_size = size;
5148 out:
5149 iput(bmp_vi);
5150 err_exit:
5151 ntfs_debug("\n");
5152 return ret;
5153 }
5154
ntfs_non_resident_attr_insert_range(struct ntfs_inode * ni,s64 start_vcn,s64 len)5155 int ntfs_non_resident_attr_insert_range(struct ntfs_inode *ni, s64 start_vcn, s64 len)
5156 {
5157 struct ntfs_volume *vol = ni->vol;
5158 struct runlist_element *hole_rl, *rl;
5159 struct ntfs_attr_search_ctx *ctx;
5160 int ret;
5161 size_t new_rl_count;
5162
5163 if (NInoAttr(ni) || ni->type != AT_DATA)
5164 return -EOPNOTSUPP;
5165 if (start_vcn > ntfs_bytes_to_cluster(vol, ni->allocated_size))
5166 return -EINVAL;
5167
5168 hole_rl = kmalloc(sizeof(*hole_rl) * 2, GFP_NOFS);
5169 if (!hole_rl)
5170 return -ENOMEM;
5171 hole_rl[0].vcn = start_vcn;
5172 hole_rl[0].lcn = LCN_HOLE;
5173 hole_rl[0].length = len;
5174 hole_rl[1].vcn = start_vcn + len;
5175 hole_rl[1].lcn = LCN_ENOENT;
5176 hole_rl[1].length = 0;
5177
5178 down_write(&ni->runlist.lock);
5179 ret = ntfs_attr_map_whole_runlist(ni);
5180 if (ret) {
5181 up_write(&ni->runlist.lock);
5182 return ret;
5183 }
5184
5185 rl = ntfs_rl_find_vcn_nolock(ni->runlist.rl, start_vcn);
5186 if (!rl) {
5187 up_write(&ni->runlist.lock);
5188 kfree(hole_rl);
5189 return -EIO;
5190 }
5191
5192 rl = ntfs_rl_insert_range(ni->runlist.rl, (int)ni->runlist.count,
5193 hole_rl, 1, &new_rl_count);
5194 if (IS_ERR(rl)) {
5195 up_write(&ni->runlist.lock);
5196 kfree(hole_rl);
5197 return PTR_ERR(rl);
5198 }
5199 ni->runlist.rl = rl;
5200 ni->runlist.count = new_rl_count;
5201
5202 ni->allocated_size += ntfs_cluster_to_bytes(vol, len);
5203 ni->data_size += ntfs_cluster_to_bytes(vol, len);
5204 if (ntfs_cluster_to_bytes(vol, start_vcn) < ni->initialized_size)
5205 ni->initialized_size += ntfs_cluster_to_bytes(vol, len);
5206 ret = ntfs_attr_update_mapping_pairs(ni, 0);
5207 up_write(&ni->runlist.lock);
5208 if (ret)
5209 return ret;
5210
5211 ctx = ntfs_attr_get_search_ctx(ni, NULL);
5212 if (!ctx) {
5213 ret = -ENOMEM;
5214 return ret;
5215 }
5216
5217 ret = ntfs_attr_lookup(ni->type, ni->name, ni->name_len, CASE_SENSITIVE,
5218 0, NULL, 0, ctx);
5219 if (ret) {
5220 ntfs_attr_put_search_ctx(ctx);
5221 return ret;
5222 }
5223
5224 ctx->attr->data.non_resident.data_size = cpu_to_le64(ni->data_size);
5225 ctx->attr->data.non_resident.initialized_size = cpu_to_le64(ni->initialized_size);
5226 if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
5227 NInoSetFileNameDirty(ni);
5228 mark_mft_record_dirty(ctx->ntfs_ino);
5229 ntfs_attr_put_search_ctx(ctx);
5230 return ret;
5231 }
5232
ntfs_non_resident_attr_collapse_range(struct ntfs_inode * ni,s64 start_vcn,s64 len)5233 int ntfs_non_resident_attr_collapse_range(struct ntfs_inode *ni, s64 start_vcn, s64 len)
5234 {
5235 struct ntfs_volume *vol = ni->vol;
5236 struct runlist_element *punch_rl, *rl;
5237 struct ntfs_attr_search_ctx *ctx = NULL;
5238 s64 end_vcn;
5239 int dst_cnt;
5240 int ret;
5241 size_t new_rl_cnt;
5242
5243 if (NInoAttr(ni) || ni->type != AT_DATA)
5244 return -EOPNOTSUPP;
5245
5246 end_vcn = ntfs_bytes_to_cluster(vol, ni->allocated_size);
5247 if (start_vcn >= end_vcn)
5248 return -EINVAL;
5249
5250 down_write(&ni->runlist.lock);
5251 ret = ntfs_attr_map_whole_runlist(ni);
5252 if (ret) {
5253 up_write(&ni->runlist.lock);
5254 return ret;
5255 }
5256
5257 len = min(len, end_vcn - start_vcn);
5258 for (rl = ni->runlist.rl, dst_cnt = 0; rl && rl->length; rl++)
5259 dst_cnt++;
5260 rl = ntfs_rl_find_vcn_nolock(ni->runlist.rl, start_vcn);
5261 if (!rl) {
5262 up_write(&ni->runlist.lock);
5263 return -EIO;
5264 }
5265
5266 rl = ntfs_rl_collapse_range(ni->runlist.rl, dst_cnt + 1,
5267 start_vcn, len, &punch_rl, &new_rl_cnt);
5268 if (IS_ERR(rl)) {
5269 up_write(&ni->runlist.lock);
5270 return PTR_ERR(rl);
5271 }
5272 ni->runlist.rl = rl;
5273 ni->runlist.count = new_rl_cnt;
5274
5275 ni->allocated_size -= ntfs_cluster_to_bytes(vol, len);
5276 if (ni->data_size > ntfs_cluster_to_bytes(vol, start_vcn)) {
5277 if (ni->data_size > ntfs_cluster_to_bytes(vol, (start_vcn + len)))
5278 ni->data_size -= ntfs_cluster_to_bytes(vol, len);
5279 else
5280 ni->data_size = ntfs_cluster_to_bytes(vol, start_vcn);
5281 }
5282 if (ni->initialized_size > ntfs_cluster_to_bytes(vol, start_vcn)) {
5283 if (ni->initialized_size >
5284 ntfs_cluster_to_bytes(vol, start_vcn + len))
5285 ni->initialized_size -= ntfs_cluster_to_bytes(vol, len);
5286 else
5287 ni->initialized_size = ntfs_cluster_to_bytes(vol, start_vcn);
5288 }
5289
5290 if (ni->allocated_size > 0) {
5291 ret = ntfs_attr_update_mapping_pairs(ni, 0);
5292 if (ret) {
5293 up_write(&ni->runlist.lock);
5294 goto out_rl;
5295 }
5296 }
5297 up_write(&ni->runlist.lock);
5298
5299 ctx = ntfs_attr_get_search_ctx(ni, NULL);
5300 if (!ctx) {
5301 ret = -ENOMEM;
5302 goto out_rl;
5303 }
5304
5305 ret = ntfs_attr_lookup(ni->type, ni->name, ni->name_len, CASE_SENSITIVE,
5306 0, NULL, 0, ctx);
5307 if (ret)
5308 goto out_ctx;
5309
5310 ctx->attr->data.non_resident.data_size = cpu_to_le64(ni->data_size);
5311 ctx->attr->data.non_resident.initialized_size = cpu_to_le64(ni->initialized_size);
5312 if (ni->allocated_size == 0)
5313 ntfs_attr_make_resident(ni, ctx);
5314 mark_mft_record_dirty(ctx->ntfs_ino);
5315
5316 ret = ntfs_cluster_free_from_rl(vol, punch_rl);
5317 if (ret)
5318 ntfs_error(vol->sb, "Freeing of clusters failed");
5319 out_ctx:
5320 if (ctx)
5321 ntfs_attr_put_search_ctx(ctx);
5322 out_rl:
5323 kvfree(punch_rl);
5324 mark_mft_record_dirty(ni);
5325 return ret;
5326 }
5327
ntfs_non_resident_attr_punch_hole(struct ntfs_inode * ni,s64 start_vcn,s64 len)5328 int ntfs_non_resident_attr_punch_hole(struct ntfs_inode *ni, s64 start_vcn, s64 len)
5329 {
5330 struct ntfs_volume *vol = ni->vol;
5331 struct runlist_element *punch_rl, *rl;
5332 s64 end_vcn;
5333 int dst_cnt;
5334 int ret;
5335 size_t new_rl_count;
5336
5337 if (NInoAttr(ni) || ni->type != AT_DATA)
5338 return -EOPNOTSUPP;
5339
5340 end_vcn = ntfs_bytes_to_cluster(vol, ni->allocated_size);
5341 if (start_vcn >= end_vcn)
5342 return -EINVAL;
5343
5344 down_write(&ni->runlist.lock);
5345 ret = ntfs_attr_map_whole_runlist(ni);
5346 if (ret) {
5347 up_write(&ni->runlist.lock);
5348 return ret;
5349 }
5350
5351 len = min(len, end_vcn - start_vcn + 1);
5352 for (rl = ni->runlist.rl, dst_cnt = 0; rl && rl->length; rl++)
5353 dst_cnt++;
5354 rl = ntfs_rl_find_vcn_nolock(ni->runlist.rl, start_vcn);
5355 if (!rl) {
5356 up_write(&ni->runlist.lock);
5357 return -EIO;
5358 }
5359
5360 rl = ntfs_rl_punch_hole(ni->runlist.rl, dst_cnt + 1,
5361 start_vcn, len, &punch_rl, &new_rl_count);
5362 if (IS_ERR(rl)) {
5363 up_write(&ni->runlist.lock);
5364 return PTR_ERR(rl);
5365 }
5366 ni->runlist.rl = rl;
5367 ni->runlist.count = new_rl_count;
5368
5369 ret = ntfs_attr_update_mapping_pairs(ni, 0);
5370 up_write(&ni->runlist.lock);
5371 if (ret) {
5372 kvfree(punch_rl);
5373 return ret;
5374 }
5375
5376 ret = ntfs_cluster_free_from_rl(vol, punch_rl);
5377 if (ret)
5378 ntfs_error(vol->sb, "Freeing of clusters failed");
5379
5380 kvfree(punch_rl);
5381 mark_mft_record_dirty(ni);
5382 return ret;
5383 }
5384
ntfs_attr_fallocate(struct ntfs_inode * ni,loff_t start,loff_t byte_len,bool keep_size)5385 int ntfs_attr_fallocate(struct ntfs_inode *ni, loff_t start, loff_t byte_len, bool keep_size)
5386 {
5387 struct ntfs_volume *vol = ni->vol;
5388 struct mft_record *mrec;
5389 struct ntfs_attr_search_ctx *ctx;
5390 s64 old_data_size;
5391 s64 vcn_start, vcn_end, vcn_uninit, vcn, try_alloc_cnt;
5392 s64 lcn, alloc_cnt;
5393 int err = 0;
5394 struct runlist_element *rl;
5395 bool balloc;
5396
5397 if (NInoAttr(ni) || ni->type != AT_DATA)
5398 return -EINVAL;
5399
5400 if (NInoNonResident(ni) && !NInoFullyMapped(ni)) {
5401 down_write(&ni->runlist.lock);
5402 err = ntfs_attr_map_whole_runlist(ni);
5403 up_write(&ni->runlist.lock);
5404 if (err)
5405 return err;
5406 }
5407
5408 mutex_lock_nested(&ni->mrec_lock, NTFS_INODE_MUTEX_NORMAL);
5409 mrec = map_mft_record(ni);
5410 if (IS_ERR(mrec)) {
5411 mutex_unlock(&ni->mrec_lock);
5412 return PTR_ERR(mrec);
5413 }
5414
5415 ctx = ntfs_attr_get_search_ctx(ni, mrec);
5416 if (!ctx) {
5417 err = -ENOMEM;
5418 goto out_unmap;
5419 }
5420
5421 err = ntfs_attr_lookup(AT_DATA, AT_UNNAMED, 0, 0, 0, NULL, 0, ctx);
5422 if (err) {
5423 err = -EIO;
5424 goto out_unmap;
5425 }
5426
5427 old_data_size = ni->data_size;
5428 if (start + byte_len > ni->data_size) {
5429 err = ntfs_attr_truncate(ni, start + byte_len);
5430 if (err)
5431 goto out_unmap;
5432 if (keep_size) {
5433 ntfs_attr_reinit_search_ctx(ctx);
5434 err = ntfs_attr_lookup(AT_DATA, AT_UNNAMED, 0, 0, 0, NULL, 0, ctx);
5435 if (err) {
5436 err = -EIO;
5437 goto out_unmap;
5438 }
5439 ni->data_size = old_data_size;
5440 if (NInoNonResident(ni))
5441 ctx->attr->data.non_resident.data_size =
5442 cpu_to_le64(old_data_size);
5443 else
5444 ctx->attr->data.resident.value_length =
5445 cpu_to_le32((u32)old_data_size);
5446 mark_mft_record_dirty(ni);
5447 }
5448 }
5449
5450 ntfs_attr_put_search_ctx(ctx);
5451 unmap_mft_record(ni);
5452 mutex_unlock(&ni->mrec_lock);
5453
5454 if (!NInoNonResident(ni))
5455 goto out;
5456
5457 vcn_start = (s64)ntfs_bytes_to_cluster(vol, start);
5458 vcn_end = (s64)ntfs_bytes_to_cluster(vol,
5459 round_up(start + byte_len, vol->cluster_size));
5460 vcn_uninit = (s64)ntfs_bytes_to_cluster(vol,
5461 round_up(ni->initialized_size, vol->cluster_size));
5462 vcn_uninit = min_t(s64, vcn_uninit, vcn_end);
5463
5464 /*
5465 * we have to allocate clusters for holes and delayed within initialized_size,
5466 * and zero out the clusters only for the holes.
5467 */
5468 vcn = vcn_start;
5469 while (vcn < vcn_uninit) {
5470 down_read(&ni->runlist.lock);
5471 rl = ntfs_attr_find_vcn_nolock(ni, vcn, NULL);
5472 up_read(&ni->runlist.lock);
5473 if (IS_ERR(rl)) {
5474 err = PTR_ERR(rl);
5475 goto out;
5476 }
5477
5478 if (rl->lcn > 0) {
5479 vcn += rl->length - (vcn - rl->vcn);
5480 } else if (rl->lcn == LCN_DELALLOC || rl->lcn == LCN_HOLE) {
5481 try_alloc_cnt = min(rl->length - (vcn - rl->vcn),
5482 vcn_uninit - vcn);
5483
5484 if (rl->lcn == LCN_DELALLOC) {
5485 vcn += try_alloc_cnt;
5486 continue;
5487 }
5488
5489 while (try_alloc_cnt > 0) {
5490 mutex_lock_nested(&ni->mrec_lock, NTFS_INODE_MUTEX_NORMAL);
5491 down_write(&ni->runlist.lock);
5492 err = ntfs_attr_map_cluster(ni, vcn, &lcn, &alloc_cnt,
5493 try_alloc_cnt, &balloc, false, false);
5494 up_write(&ni->runlist.lock);
5495 mutex_unlock(&ni->mrec_lock);
5496 if (err)
5497 goto out;
5498
5499 err = ntfs_dio_zero_range(VFS_I(ni),
5500 lcn << vol->cluster_size_bits,
5501 alloc_cnt << vol->cluster_size_bits);
5502 if (err > 0)
5503 goto out;
5504
5505 if (signal_pending(current))
5506 goto out;
5507
5508 vcn += alloc_cnt;
5509 try_alloc_cnt -= alloc_cnt;
5510 }
5511 } else {
5512 err = -EIO;
5513 goto out;
5514 }
5515 }
5516
5517 /* allocate clusters outside of initialized_size */
5518 try_alloc_cnt = vcn_end - vcn;
5519 while (try_alloc_cnt > 0) {
5520 mutex_lock_nested(&ni->mrec_lock, NTFS_INODE_MUTEX_NORMAL);
5521 down_write(&ni->runlist.lock);
5522 err = ntfs_attr_map_cluster(ni, vcn, &lcn, &alloc_cnt,
5523 try_alloc_cnt, &balloc, false, false);
5524 up_write(&ni->runlist.lock);
5525 mutex_unlock(&ni->mrec_lock);
5526 if (err || signal_pending(current))
5527 goto out;
5528
5529 vcn += alloc_cnt;
5530 try_alloc_cnt -= alloc_cnt;
5531 cond_resched();
5532 }
5533
5534 if (NInoRunlistDirty(ni)) {
5535 mutex_lock_nested(&ni->mrec_lock, NTFS_INODE_MUTEX_NORMAL);
5536 down_write(&ni->runlist.lock);
5537 err = ntfs_attr_update_mapping_pairs(ni, 0);
5538 if (err)
5539 ntfs_error(ni->vol->sb, "Updating mapping pairs failed");
5540 else
5541 NInoClearRunlistDirty(ni);
5542 up_write(&ni->runlist.lock);
5543 mutex_unlock(&ni->mrec_lock);
5544 }
5545 return err;
5546 out_unmap:
5547 if (ctx)
5548 ntfs_attr_put_search_ctx(ctx);
5549 unmap_mft_record(ni);
5550 mutex_unlock(&ni->mrec_lock);
5551 out:
5552 return err >= 0 ? 0 : err;
5553 }
5554