1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * NTFS kernel inode handling.
4 *
5 * Copyright (c) 2001-2014 Anton Altaparmakov and Tuxera Inc.
6 * Copyright (c) 2025 LG Electronics Co., Ltd.
7 */
8
9 #include <linux/writeback.h>
10 #include <linux/seq_file.h>
11
12 #include "lcnalloc.h"
13 #include "time.h"
14 #include "ntfs.h"
15 #include "index.h"
16 #include "attrlist.h"
17 #include "reparse.h"
18 #include "ea.h"
19 #include "attrib.h"
20 #include "iomap.h"
21 #include "object_id.h"
22
23 /*
24 * ntfs_test_inode - compare two (possibly fake) inodes for equality
25 * @vi: vfs inode which to test
26 * @data: data which is being tested with
27 *
28 * Compare the ntfs attribute embedded in the ntfs specific part of the vfs
29 * inode @vi for equality with the ntfs attribute @data.
30 *
31 * If searching for the normal file/directory inode, set @na->type to AT_UNUSED.
32 * @na->name and @na->name_len are then ignored.
33 *
34 * Return 1 if the attributes match and 0 if not.
35 *
36 * NOTE: This function runs with the inode_hash_lock spin lock held so it is not
37 * allowed to sleep.
38 */
ntfs_test_inode(struct inode * vi,void * data)39 int ntfs_test_inode(struct inode *vi, void *data)
40 {
41 struct ntfs_attr *na = data;
42 struct ntfs_inode *ni = NTFS_I(vi);
43
44 if (vi->i_ino != na->mft_no)
45 return 0;
46
47 /* If !NInoAttr(ni), @vi is a normal file or directory inode. */
48 if (likely(!NInoAttr(ni))) {
49 /* If not looking for a normal inode this is a mismatch. */
50 if (unlikely(na->type != AT_UNUSED))
51 return 0;
52 } else {
53 /* A fake inode describing an attribute. */
54 if (ni->type != na->type)
55 return 0;
56 if (ni->name_len != na->name_len)
57 return 0;
58 if (na->name_len && memcmp(ni->name, na->name,
59 na->name_len * sizeof(__le16)))
60 return 0;
61 if (!ni->ext.base_ntfs_ino)
62 return 0;
63 }
64
65 /* Match! */
66 return 1;
67 }
68
69 /*
70 * ntfs_init_locked_inode - initialize an inode
71 * @vi: vfs inode to initialize
72 * @data: data which to initialize @vi to
73 *
74 * Initialize the vfs inode @vi with the values from the ntfs attribute @data in
75 * order to enable ntfs_test_inode() to do its work.
76 *
77 * If initializing the normal file/directory inode, set @na->type to AT_UNUSED.
78 * In that case, @na->name and @na->name_len should be set to NULL and 0,
79 * respectively. Although that is not strictly necessary as
80 * ntfs_read_locked_inode() will fill them in later.
81 *
82 * Return 0 on success and error.
83 *
84 * NOTE: This function runs with the inode->i_lock spin lock held so it is not
85 * allowed to sleep. (Hence the GFP_ATOMIC allocation.)
86 */
ntfs_init_locked_inode(struct inode * vi,void * data)87 static int ntfs_init_locked_inode(struct inode *vi, void *data)
88 {
89 struct ntfs_attr *na = data;
90 struct ntfs_inode *ni = NTFS_I(vi);
91
92 vi->i_ino = (unsigned long)na->mft_no;
93
94 if (na->type == AT_INDEX_ALLOCATION)
95 NInoSetMstProtected(ni);
96 else
97 ni->type = na->type;
98
99 ni->name = na->name;
100 ni->name_len = na->name_len;
101 ni->folio = NULL;
102 atomic_set(&ni->count, 1);
103
104 /* If initializing a normal inode, we are done. */
105 if (likely(na->type == AT_UNUSED))
106 return 0;
107
108 /* It is a fake inode. */
109 NInoSetAttr(ni);
110
111 /*
112 * We have I30 global constant as an optimization as it is the name
113 * in >99.9% of named attributes! The other <0.1% incur a GFP_ATOMIC
114 * allocation but that is ok. And most attributes are unnamed anyway,
115 * thus the fraction of named attributes with name != I30 is actually
116 * absolutely tiny.
117 */
118 if (na->name_len && na->name != I30) {
119 unsigned int i;
120
121 i = na->name_len * sizeof(__le16);
122 ni->name = kmalloc(i + sizeof(__le16), GFP_ATOMIC);
123 if (!ni->name)
124 return -ENOMEM;
125 memcpy(ni->name, na->name, i);
126 ni->name[na->name_len] = 0;
127 }
128 return 0;
129 }
130
131 static int ntfs_read_locked_inode(struct inode *vi);
132 static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi);
133 static int ntfs_read_locked_index_inode(struct inode *base_vi,
134 struct inode *vi);
135
136 /*
137 * ntfs_iget - obtain a struct inode corresponding to a specific normal inode
138 * @sb: super block of mounted volume
139 * @mft_no: mft record number / inode number to obtain
140 *
141 * Obtain the struct inode corresponding to a specific normal inode (i.e. a
142 * file or directory).
143 *
144 * If the inode is in the cache, it is just returned with an increased
145 * reference count. Otherwise, a new struct inode is allocated and initialized,
146 * and finally ntfs_read_locked_inode() is called to read in the inode and
147 * fill in the remainder of the inode structure.
148 *
149 * Return the struct inode on success. Check the return value with IS_ERR() and
150 * if true, the function failed and the error code is obtained from PTR_ERR().
151 */
ntfs_iget(struct super_block * sb,u64 mft_no)152 struct inode *ntfs_iget(struct super_block *sb, u64 mft_no)
153 {
154 struct inode *vi;
155 int err;
156 struct ntfs_attr na;
157
158 na.mft_no = mft_no;
159 na.type = AT_UNUSED;
160 na.name = NULL;
161 na.name_len = 0;
162
163 vi = iget5_locked(sb, mft_no, ntfs_test_inode,
164 ntfs_init_locked_inode, &na);
165 if (unlikely(!vi))
166 return ERR_PTR(-ENOMEM);
167
168 err = 0;
169
170 /* If this is a freshly allocated inode, need to read it now. */
171 if (inode_state_read_once(vi) & I_NEW) {
172 err = ntfs_read_locked_inode(vi);
173 if (err) {
174 remove_inode_hash(vi);
175 discard_new_inode(vi);
176 } else
177 unlock_new_inode(vi);
178 }
179 /*
180 * There is no point in keeping bad inodes around. This also
181 * simplifies things in that we never need to check for bad inodes
182 * elsewhere.
183 */
184 if (unlikely(err))
185 vi = ERR_PTR(err);
186 return vi;
187 }
188
189 /*
190 * ntfs_attr_iget - obtain a struct inode corresponding to an attribute
191 * @base_vi: vfs base inode containing the attribute
192 * @type: attribute type
193 * @name: Unicode name of the attribute (NULL if unnamed)
194 * @name_len: length of @name in Unicode characters (0 if unnamed)
195 *
196 * Obtain the (fake) struct inode corresponding to the attribute specified by
197 * @type, @name, and @name_len, which is present in the base mft record
198 * specified by the vfs inode @base_vi.
199 *
200 * If the attribute inode is in the cache, it is just returned with an
201 * increased reference count. Otherwise, a new struct inode is allocated and
202 * initialized, and finally ntfs_read_locked_attr_inode() is called to read the
203 * attribute and fill in the inode structure.
204 *
205 * Note, for index allocation attributes, you need to use ntfs_index_iget()
206 * instead of ntfs_attr_iget() as working with indices is a lot more complex.
207 *
208 * Return the struct inode of the attribute inode on success. Check the return
209 * value with IS_ERR() and if true, the function failed and the error code is
210 * obtained from PTR_ERR().
211 */
ntfs_attr_iget(struct inode * base_vi,__le32 type,__le16 * name,u32 name_len)212 struct inode *ntfs_attr_iget(struct inode *base_vi, __le32 type,
213 __le16 *name, u32 name_len)
214 {
215 struct inode *vi;
216 int err;
217 struct ntfs_attr na;
218
219 /* Make sure no one calls ntfs_attr_iget() for indices. */
220 WARN_ON(type == AT_INDEX_ALLOCATION);
221
222 na.mft_no = base_vi->i_ino;
223 na.type = type;
224 na.name = name;
225 na.name_len = name_len;
226
227 vi = iget5_locked(base_vi->i_sb, na.mft_no, ntfs_test_inode,
228 ntfs_init_locked_inode, &na);
229 if (unlikely(!vi))
230 return ERR_PTR(-ENOMEM);
231 err = 0;
232
233 /* If this is a freshly allocated inode, need to read it now. */
234 if (inode_state_read_once(vi) & I_NEW) {
235 err = ntfs_read_locked_attr_inode(base_vi, vi);
236 if (err) {
237 remove_inode_hash(vi);
238 discard_new_inode(vi);
239 } else
240 unlock_new_inode(vi);
241 }
242 /*
243 * There is no point in keeping bad attribute inodes around. This also
244 * simplifies things in that we never need to check for bad attribute
245 * inodes elsewhere.
246 */
247 if (unlikely(err))
248 vi = ERR_PTR(err);
249 return vi;
250 }
251
252 /*
253 * ntfs_index_iget - obtain a struct inode corresponding to an index
254 * @base_vi: vfs base inode containing the index related attributes
255 * @name: Unicode name of the index
256 * @name_len: length of @name in Unicode characters
257 *
258 * Obtain the (fake) struct inode corresponding to the index specified by @name
259 * and @name_len, which is present in the base mft record specified by the vfs
260 * inode @base_vi.
261 *
262 * If the index inode is in the cache, it is just returned with an increased
263 * reference count. Otherwise, a new struct inode is allocated and
264 * initialized, and finally ntfs_read_locked_index_inode() is called to read
265 * the index related attributes and fill in the inode structure.
266 *
267 * Return the struct inode of the index inode on success. Check the return
268 * value with IS_ERR() and if true, the function failed and the error code is
269 * obtained from PTR_ERR().
270 */
ntfs_index_iget(struct inode * base_vi,__le16 * name,u32 name_len)271 struct inode *ntfs_index_iget(struct inode *base_vi, __le16 *name,
272 u32 name_len)
273 {
274 struct inode *vi;
275 int err;
276 struct ntfs_attr na;
277
278 na.mft_no = base_vi->i_ino;
279 na.type = AT_INDEX_ALLOCATION;
280 na.name = name;
281 na.name_len = name_len;
282
283 vi = iget5_locked(base_vi->i_sb, na.mft_no, ntfs_test_inode,
284 ntfs_init_locked_inode, &na);
285 if (unlikely(!vi))
286 return ERR_PTR(-ENOMEM);
287
288 err = 0;
289
290 /* If this is a freshly allocated inode, need to read it now. */
291 if (inode_state_read_once(vi) & I_NEW) {
292 err = ntfs_read_locked_index_inode(base_vi, vi);
293 if (err) {
294 remove_inode_hash(vi);
295 discard_new_inode(vi);
296 } else
297 unlock_new_inode(vi);
298 }
299 /*
300 * There is no point in keeping bad index inodes around. This also
301 * simplifies things in that we never need to check for bad index
302 * inodes elsewhere.
303 */
304 if (unlikely(err))
305 vi = ERR_PTR(err);
306 return vi;
307 }
308
ntfs_alloc_big_inode(struct super_block * sb)309 struct inode *ntfs_alloc_big_inode(struct super_block *sb)
310 {
311 struct ntfs_inode *ni;
312
313 ntfs_debug("Entering.");
314 ni = alloc_inode_sb(sb, ntfs_big_inode_cache, GFP_NOFS);
315 if (likely(ni != NULL)) {
316 ni->state = 0;
317 ni->type = 0;
318 ni->mft_no = 0;
319 return VFS_I(ni);
320 }
321 ntfs_error(sb, "Allocation of NTFS big inode structure failed.");
322 return NULL;
323 }
324
ntfs_free_big_inode(struct inode * inode)325 void ntfs_free_big_inode(struct inode *inode)
326 {
327 kmem_cache_free(ntfs_big_inode_cache, NTFS_I(inode));
328 }
329
ntfs_non_resident_dealloc_clusters(struct ntfs_inode * ni)330 static int ntfs_non_resident_dealloc_clusters(struct ntfs_inode *ni)
331 {
332 struct super_block *sb = ni->vol->sb;
333 struct ntfs_attr_search_ctx *actx;
334 int err = 0;
335
336 actx = ntfs_attr_get_search_ctx(ni, NULL);
337 if (!actx)
338 return -ENOMEM;
339 WARN_ON(actx->mrec->link_count != 0);
340
341 /**
342 * ntfs_truncate_vfs cannot be called in evict() context due
343 * to some limitations, which are the @ni vfs inode is marked
344 * with I_FREEING, and etc.
345 */
346 if (NInoRunlistDirty(ni)) {
347 err = ntfs_cluster_free_from_rl(ni->vol, ni->runlist.rl);
348 if (err)
349 ntfs_error(sb,
350 "Failed to free clusters. Leaving inconsistent metadata.\n");
351 }
352
353 while ((err = ntfs_attrs_walk(actx)) == 0) {
354 if (actx->attr->non_resident &&
355 (!NInoRunlistDirty(ni) || actx->attr->type != AT_DATA)) {
356 struct runlist_element *rl;
357 size_t new_rl_count;
358
359 rl = ntfs_mapping_pairs_decompress(ni->vol, actx->attr, NULL,
360 &new_rl_count);
361 if (IS_ERR(rl)) {
362 err = PTR_ERR(rl);
363 ntfs_error(sb,
364 "Failed to decompress runlist. Leaving inconsistent metadata.\n");
365 continue;
366 }
367
368 err = ntfs_cluster_free_from_rl(ni->vol, rl);
369 if (err)
370 ntfs_error(sb,
371 "Failed to free attribute clusters. Leaving inconsistent metadata.\n");
372 kvfree(rl);
373 }
374 }
375
376 ntfs_release_dirty_clusters(ni->vol, ni->i_dealloc_clusters);
377 ntfs_attr_put_search_ctx(actx);
378 return err;
379 }
380
ntfs_drop_big_inode(struct inode * inode)381 int ntfs_drop_big_inode(struct inode *inode)
382 {
383 struct ntfs_inode *ni = NTFS_I(inode);
384
385 if (!inode_unhashed(inode) && inode_state_read_once(inode) & I_SYNC) {
386 if (ni->type == AT_DATA || ni->type == AT_INDEX_ALLOCATION) {
387 if (!inode->i_nlink) {
388 struct ntfs_inode *ni = NTFS_I(inode);
389
390 if (ni->data_size == 0)
391 return 0;
392
393 /* To avoid evict_inode call simultaneously */
394 atomic_inc(&inode->i_count);
395 spin_unlock(&inode->i_lock);
396
397 truncate_setsize(VFS_I(ni), 0);
398 ntfs_truncate_vfs(VFS_I(ni), 0, 1);
399
400 sb_start_intwrite(inode->i_sb);
401 i_size_write(inode, 0);
402 ni->allocated_size = ni->initialized_size = ni->data_size = 0;
403
404 truncate_inode_pages_final(inode->i_mapping);
405 sb_end_intwrite(inode->i_sb);
406
407 spin_lock(&inode->i_lock);
408 atomic_dec(&inode->i_count);
409 }
410 }
411 return 0;
412 }
413
414 return inode_generic_drop(inode);
415 }
416
ntfs_alloc_extent_inode(void)417 static inline struct ntfs_inode *ntfs_alloc_extent_inode(void)
418 {
419 struct ntfs_inode *ni;
420
421 ntfs_debug("Entering.");
422 ni = kmem_cache_alloc(ntfs_inode_cache, GFP_NOFS);
423 if (likely(ni != NULL)) {
424 ni->state = 0;
425 return ni;
426 }
427 ntfs_error(NULL, "Allocation of NTFS inode structure failed.");
428 return NULL;
429 }
430
ntfs_destroy_extent_inode(struct ntfs_inode * ni)431 static void ntfs_destroy_extent_inode(struct ntfs_inode *ni)
432 {
433 ntfs_debug("Entering.");
434
435 if (!atomic_dec_and_test(&ni->count))
436 WARN_ON(1);
437 if (ni->folio)
438 folio_put(ni->folio);
439 kfree(ni->mrec);
440 kmem_cache_free(ntfs_inode_cache, ni);
441 }
442
443 static struct lock_class_key attr_inode_mrec_lock_class;
444 static struct lock_class_key attr_list_inode_mrec_lock_class;
445
446 /*
447 * The attribute runlist lock has separate locking rules from the
448 * normal runlist lock, so split the two lock-classes:
449 */
450 static struct lock_class_key attr_list_rl_lock_class;
451
452 /*
453 * __ntfs_init_inode - initialize ntfs specific part of an inode
454 * @sb: super block of mounted volume
455 * @ni: freshly allocated ntfs inode which to initialize
456 *
457 * Initialize an ntfs inode to defaults.
458 *
459 * NOTE: ni->mft_no, ni->state, ni->type, ni->name, and ni->name_len are left
460 * untouched. Make sure to initialize them elsewhere.
461 */
__ntfs_init_inode(struct super_block * sb,struct ntfs_inode * ni)462 void __ntfs_init_inode(struct super_block *sb, struct ntfs_inode *ni)
463 {
464 ntfs_debug("Entering.");
465 rwlock_init(&ni->size_lock);
466 ni->initialized_size = ni->allocated_size = 0;
467 ni->seq_no = 0;
468 atomic_set(&ni->count, 1);
469 ni->vol = NTFS_SB(sb);
470 ntfs_init_runlist(&ni->runlist);
471 mutex_init(&ni->mrec_lock);
472 if (ni->type == AT_ATTRIBUTE_LIST) {
473 lockdep_set_class(&ni->mrec_lock,
474 &attr_list_inode_mrec_lock_class);
475 lockdep_set_class(&ni->runlist.lock,
476 &attr_list_rl_lock_class);
477 } else if (NInoAttr(ni)) {
478 lockdep_set_class(&ni->mrec_lock,
479 &attr_inode_mrec_lock_class);
480 }
481
482 ni->folio = NULL;
483 ni->folio_ofs = 0;
484 ni->mrec = NULL;
485 ni->attr_list_size = 0;
486 ni->attr_list = NULL;
487 ni->itype.index.block_size = 0;
488 ni->itype.index.vcn_size = 0;
489 ni->itype.index.collation_rule = 0;
490 ni->itype.index.block_size_bits = 0;
491 ni->itype.index.vcn_size_bits = 0;
492 mutex_init(&ni->extent_lock);
493 ni->nr_extents = 0;
494 ni->ext.base_ntfs_ino = NULL;
495 ni->flags = 0;
496 ni->mft_lcn[0] = LCN_RL_NOT_MAPPED;
497 ni->mft_lcn_count = 0;
498 ni->reparse_tag = 0;
499 ni->reparse_flags = 0;
500 ni->target = NULL;
501 ni->i_dealloc_clusters = 0;
502 }
503
504 /*
505 * Extent inodes get MFT-mapped in a nested way, while the base inode
506 * is still mapped. Teach this nesting to the lock validator by creating
507 * a separate class for nested inode's mrec_lock's:
508 */
509 static struct lock_class_key extent_inode_mrec_lock_key;
510
ntfs_new_extent_inode(struct super_block * sb,u64 mft_no)511 inline struct ntfs_inode *ntfs_new_extent_inode(struct super_block *sb,
512 u64 mft_no)
513 {
514 struct ntfs_inode *ni = ntfs_alloc_extent_inode();
515
516 ntfs_debug("Entering.");
517 if (likely(ni != NULL)) {
518 __ntfs_init_inode(sb, ni);
519 lockdep_set_class(&ni->mrec_lock, &extent_inode_mrec_lock_key);
520 ni->mft_no = mft_no;
521 ni->type = AT_UNUSED;
522 ni->name = NULL;
523 ni->name_len = 0;
524 }
525 return ni;
526 }
527
528 /*
529 * ntfs_is_extended_system_file - check if a file is in the $Extend directory
530 * @ctx: initialized attribute search context
531 *
532 * Search all file name attributes in the inode described by the attribute
533 * search context @ctx and check if any of the names are in the $Extend system
534 * directory.
535 *
536 * Return values:
537 * 3: file is $ObjId in $Extend directory
538 * 2: file is $Reparse in $Extend directory
539 * 1: file is in $Extend directory
540 * 0: file is not in $Extend directory
541 * -errno: failed to determine if the file is in the $Extend directory
542 */
ntfs_is_extended_system_file(struct ntfs_attr_search_ctx * ctx)543 static int ntfs_is_extended_system_file(struct ntfs_attr_search_ctx *ctx)
544 {
545 int nr_links, err;
546
547 /* Restart search. */
548 ntfs_attr_reinit_search_ctx(ctx);
549
550 /* Get number of hard links. */
551 nr_links = le16_to_cpu(ctx->mrec->link_count);
552
553 /* Loop through all hard links. */
554 while (!(err = ntfs_attr_lookup(AT_FILE_NAME, NULL, 0, 0, 0, NULL, 0,
555 ctx))) {
556 struct file_name_attr *file_name_attr;
557 struct attr_record *attr = ctx->attr;
558 u8 *p, *p2;
559
560 nr_links--;
561 /*
562 * Maximum sanity checking as we are called on an inode that
563 * we suspect might be corrupt.
564 */
565 p = (u8 *)attr + le32_to_cpu(attr->length);
566 if (p < (u8 *)ctx->mrec || (u8 *)p > (u8 *)ctx->mrec +
567 le32_to_cpu(ctx->mrec->bytes_in_use)) {
568 err_corrupt_attr:
569 ntfs_error(ctx->ntfs_ino->vol->sb,
570 "Corrupt file name attribute. You should run chkdsk.");
571 return -EIO;
572 }
573 if (attr->non_resident) {
574 ntfs_error(ctx->ntfs_ino->vol->sb,
575 "Non-resident file name. You should run chkdsk.");
576 return -EIO;
577 }
578 if (attr->flags) {
579 ntfs_error(ctx->ntfs_ino->vol->sb,
580 "File name with invalid flags. You should run chkdsk.");
581 return -EIO;
582 }
583 if (!(attr->data.resident.flags & RESIDENT_ATTR_IS_INDEXED)) {
584 ntfs_error(ctx->ntfs_ino->vol->sb,
585 "Unindexed file name. You should run chkdsk.");
586 return -EIO;
587 }
588 file_name_attr = (struct file_name_attr *)((u8 *)attr +
589 le16_to_cpu(attr->data.resident.value_offset));
590 p2 = (u8 *)file_name_attr + le32_to_cpu(attr->data.resident.value_length);
591 if (p2 < (u8 *)attr || p2 > p)
592 goto err_corrupt_attr;
593 /* This attribute is ok, but is it in the $Extend directory? */
594 if (MREF_LE(file_name_attr->parent_directory) == FILE_Extend) {
595 unsigned char *s;
596
597 s = ntfs_attr_name_get(ctx->ntfs_ino->vol,
598 file_name_attr->file_name,
599 file_name_attr->file_name_length);
600 if (!s)
601 return 1;
602 if (!strcmp("$Reparse", s)) {
603 ntfs_attr_name_free(&s);
604 return 2; /* it's reparse point file */
605 }
606 if (!strcmp("$ObjId", s)) {
607 ntfs_attr_name_free(&s);
608 return 3; /* it's object id file */
609 }
610 ntfs_attr_name_free(&s);
611 return 1; /* YES, it's an extended system file. */
612 }
613 }
614 if (unlikely(err != -ENOENT))
615 return err;
616 if (unlikely(nr_links)) {
617 ntfs_error(ctx->ntfs_ino->vol->sb,
618 "Inode hard link count doesn't match number of name attributes. You should run chkdsk.");
619 return -EIO;
620 }
621 return 0; /* NO, it is not an extended system file. */
622 }
623
624 static struct lock_class_key ntfs_dir_inval_lock_key;
625
ntfs_set_vfs_operations(struct inode * inode,mode_t mode,dev_t dev)626 void ntfs_set_vfs_operations(struct inode *inode, mode_t mode, dev_t dev)
627 {
628 if (S_ISDIR(mode)) {
629 if (!NInoAttr(NTFS_I(inode))) {
630 inode->i_op = &ntfs_dir_inode_ops;
631 inode->i_fop = &ntfs_dir_ops;
632 }
633 inode->i_mapping->a_ops = &ntfs_aops;
634 lockdep_set_class(&inode->i_mapping->invalidate_lock,
635 &ntfs_dir_inval_lock_key);
636 } else if (S_ISLNK(mode)) {
637 inode->i_op = &ntfs_symlink_inode_operations;
638 inode->i_mapping->a_ops = &ntfs_aops;
639 } else if (S_ISCHR(mode) || S_ISBLK(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
640 inode->i_op = &ntfs_special_inode_operations;
641 init_special_inode(inode, inode->i_mode, dev);
642 } else {
643 if (!NInoAttr(NTFS_I(inode))) {
644 inode->i_op = &ntfs_file_inode_ops;
645 inode->i_fop = &ntfs_file_ops;
646 }
647 if (inode->i_ino == FILE_MFT)
648 inode->i_mapping->a_ops = &ntfs_mft_aops;
649 else
650 inode->i_mapping->a_ops = &ntfs_aops;
651 }
652 }
653
654 /*
655 * ntfs_read_locked_inode - read an inode from its device
656 * @vi: inode to read
657 *
658 * ntfs_read_locked_inode() is called from ntfs_iget() to read the inode
659 * described by @vi into memory from the device.
660 *
661 * The only fields in @vi that we need to/can look at when the function is
662 * called are i_sb, pointing to the mounted device's super block, and i_ino,
663 * the number of the inode to load.
664 *
665 * ntfs_read_locked_inode() maps, pins and locks the mft record number i_ino
666 * for reading and sets up the necessary @vi fields as well as initializing
667 * the ntfs inode.
668 *
669 * Q: What locks are held when the function is called?
670 * A: i_state has I_NEW set, hence the inode is locked, also
671 * i_count is set to 1, so it is not going to go away
672 * i_flags is set to 0 and we have no business touching it. Only an ioctl()
673 * is allowed to write to them. We should of course be honouring them but
674 * we need to do that using the IS_* macros defined in include/linux/fs.h.
675 * In any case ntfs_read_locked_inode() has nothing to do with i_flags.
676 *
677 * Return 0 on success and -errno on error.
678 */
ntfs_read_locked_inode(struct inode * vi)679 static int ntfs_read_locked_inode(struct inode *vi)
680 {
681 struct ntfs_volume *vol = NTFS_SB(vi->i_sb);
682 struct ntfs_inode *ni = NTFS_I(vi);
683 struct mft_record *m;
684 struct attr_record *a;
685 struct standard_information *si;
686 struct ntfs_attr_search_ctx *ctx;
687 int err = 0;
688 __le16 *name = I30;
689 unsigned int name_len = 4, flags = 0;
690 int extend_sys = 0;
691 dev_t dev = 0;
692 bool has_lxmod = false;
693 bool vol_err = true;
694
695 ntfs_debug("Entering for i_ino 0x%llx.", ni->mft_no);
696
697 if (uid_valid(vol->uid)) {
698 vi->i_uid = vol->uid;
699 flags |= NTFS_VOL_UID;
700 } else
701 vi->i_uid = GLOBAL_ROOT_UID;
702
703 if (gid_valid(vol->gid)) {
704 vi->i_gid = vol->gid;
705 flags |= NTFS_VOL_GID;
706 } else
707 vi->i_gid = GLOBAL_ROOT_GID;
708
709 vi->i_mode = 0777;
710
711 /*
712 * Initialize the ntfs specific part of @vi special casing
713 * FILE_MFT which we need to do at mount time.
714 */
715 if (vi->i_ino != FILE_MFT)
716 ntfs_init_big_inode(vi);
717
718 m = map_mft_record(ni);
719 if (IS_ERR(m)) {
720 err = PTR_ERR(m);
721 goto err_out;
722 }
723
724 ctx = ntfs_attr_get_search_ctx(ni, m);
725 if (!ctx) {
726 err = -ENOMEM;
727 goto unm_err_out;
728 }
729
730 if (!(m->flags & MFT_RECORD_IN_USE)) {
731 err = -ENOENT;
732 vol_err = false;
733 goto unm_err_out;
734 }
735
736 if (m->base_mft_record) {
737 ntfs_error(vi->i_sb, "Inode is an extent inode!");
738 goto unm_err_out;
739 }
740
741 /* Transfer information from mft record into vfs and ntfs inodes. */
742 vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
743
744 if (le16_to_cpu(m->link_count) < 1) {
745 ntfs_error(vi->i_sb, "Inode link count is 0!");
746 goto unm_err_out;
747 }
748 set_nlink(vi, le16_to_cpu(m->link_count));
749
750 /* If read-only, no one gets write permissions. */
751 if (IS_RDONLY(vi))
752 vi->i_mode &= ~0222;
753
754 /*
755 * Find the standard information attribute in the mft record. At this
756 * stage we haven't setup the attribute list stuff yet, so this could
757 * in fact fail if the standard information is in an extent record, but
758 * I don't think this actually ever happens.
759 */
760 ntfs_attr_reinit_search_ctx(ctx);
761 err = ntfs_attr_lookup(AT_STANDARD_INFORMATION, NULL, 0, 0, 0, NULL, 0,
762 ctx);
763 if (unlikely(err)) {
764 if (err == -ENOENT)
765 ntfs_error(vi->i_sb, "$STANDARD_INFORMATION attribute is missing.");
766 goto unm_err_out;
767 }
768 a = ctx->attr;
769 /* Get the standard information attribute value. */
770 si = (struct standard_information *)((u8 *)a +
771 le16_to_cpu(a->data.resident.value_offset));
772
773 /* Transfer information from the standard information into vi. */
774 /*
775 * Note: The i_?times do not quite map perfectly onto the NTFS times,
776 * but they are close enough, and in the end it doesn't really matter
777 * that much...
778 */
779 /*
780 * mtime is the last change of the data within the file. Not changed
781 * when only metadata is changed, e.g. a rename doesn't affect mtime.
782 */
783 ni->i_crtime = ntfs2utc(si->creation_time);
784
785 inode_set_mtime_to_ts(vi, ntfs2utc(si->last_data_change_time));
786 /*
787 * ctime is the last change of the metadata of the file. This obviously
788 * always changes, when mtime is changed. ctime can be changed on its
789 * own, mtime is then not changed, e.g. when a file is renamed.
790 */
791 inode_set_ctime_to_ts(vi, ntfs2utc(si->last_mft_change_time));
792 /*
793 * Last access to the data within the file. Not changed during a rename
794 * for example but changed whenever the file is written to.
795 */
796 inode_set_atime_to_ts(vi, ntfs2utc(si->last_access_time));
797 ni->flags = si->file_attributes;
798
799 /* Find the attribute list attribute if present. */
800 ntfs_attr_reinit_search_ctx(ctx);
801 err = ntfs_attr_lookup(AT_ATTRIBUTE_LIST, NULL, 0, 0, 0, NULL, 0, ctx);
802 if (err) {
803 if (unlikely(err != -ENOENT)) {
804 ntfs_error(vi->i_sb, "Failed to lookup attribute list attribute.");
805 goto unm_err_out;
806 }
807 } else {
808 if (vi->i_ino == FILE_MFT)
809 goto skip_attr_list_load;
810 ntfs_debug("Attribute list found in inode 0x%llx.", ni->mft_no);
811 NInoSetAttrList(ni);
812 a = ctx->attr;
813 if (a->flags & ATTR_COMPRESSION_MASK) {
814 ntfs_error(vi->i_sb,
815 "Attribute list attribute is compressed.");
816 goto unm_err_out;
817 }
818 if (a->flags & ATTR_IS_ENCRYPTED ||
819 a->flags & ATTR_IS_SPARSE) {
820 if (a->non_resident) {
821 ntfs_error(vi->i_sb,
822 "Non-resident attribute list attribute is encrypted/sparse.");
823 goto unm_err_out;
824 }
825 ntfs_warning(vi->i_sb,
826 "Resident attribute list attribute in inode 0x%llx is marked encrypted/sparse which is not true. However, Windows allows this and chkdsk does not detect or correct it so we will just ignore the invalid flags and pretend they are not set.",
827 ni->mft_no);
828 }
829 /* Now allocate memory for the attribute list. */
830 ni->attr_list_size = (u32)ntfs_attr_size(a);
831 if (!ni->attr_list_size) {
832 ntfs_error(vi->i_sb, "Attr_list_size is zero");
833 goto unm_err_out;
834 }
835 ni->attr_list = kvzalloc(ni->attr_list_size, GFP_NOFS);
836 if (!ni->attr_list) {
837 ntfs_error(vi->i_sb,
838 "Not enough memory to allocate buffer for attribute list.");
839 err = -ENOMEM;
840 goto unm_err_out;
841 }
842 if (a->non_resident) {
843 NInoSetAttrListNonResident(ni);
844 if (a->data.non_resident.lowest_vcn) {
845 ntfs_error(vi->i_sb, "Attribute list has non zero lowest_vcn.");
846 goto unm_err_out;
847 }
848
849 /* Now load the attribute list. */
850 err = load_attribute_list(ni, ni->attr_list, ni->attr_list_size);
851 if (err) {
852 ntfs_error(vi->i_sb, "Failed to load attribute list attribute.");
853 goto unm_err_out;
854 }
855 } else /* if (!a->non_resident) */ {
856 /* Now copy the attribute list. */
857 memcpy(ni->attr_list, (u8 *)a + le16_to_cpu(
858 a->data.resident.value_offset),
859 le32_to_cpu(
860 a->data.resident.value_length));
861 /* A resident list is not validated on load; check it now. */
862 if (!ntfs_attr_list_is_valid(ni->attr_list,
863 ni->attr_list_size)) {
864 ntfs_error(vi->i_sb, "Corrupt attribute list.");
865 goto unm_err_out;
866 }
867 }
868 }
869 skip_attr_list_load:
870 err = ntfs_attr_lookup(AT_EA_INFORMATION, NULL, 0, 0, 0, NULL, 0, ctx);
871 if (!err) {
872 NInoSetHasEA(ni);
873 ntfs_ea_get_wsl_inode(vi, &dev, flags, &has_lxmod);
874 }
875
876 if (ni->flags & FILE_ATTR_REPARSE_POINT) {
877 unsigned int mode;
878
879 err = ntfs_parse_reparse(ni, &mode);
880 if (err)
881 goto unm_err_out;
882 if (mode)
883 vi->i_mode |= mode;
884 else {
885 vi->i_mode &= ~S_IFLNK;
886 if (m->flags & MFT_RECORD_IS_DIRECTORY)
887 vi->i_mode |= S_IFDIR;
888 else
889 vi->i_mode |= S_IFREG;
890 }
891 } else if (m->flags & MFT_RECORD_IS_DIRECTORY) {
892 vi->i_mode |= S_IFDIR;
893 } else {
894 vi->i_mode |= S_IFREG;
895 }
896
897 if (S_ISDIR(vi->i_mode)) {
898 /*
899 * Apply the directory permissions mask set in the mount options
900 * when no per-file WSL mode is present.
901 */
902 if (!has_lxmod)
903 vi->i_mode &= ~vol->dmask;
904 /* Things break without this kludge! */
905 if (vi->i_nlink > 1)
906 set_nlink(vi, 1);
907 } else {
908 /* Apply the file permissions mask when no WSL mode is present. */
909 if (!has_lxmod)
910 vi->i_mode &= ~vol->fmask;
911 }
912
913 /*
914 * If an attribute list is present we now have the attribute list value
915 * in ntfs_ino->attr_list and it is ntfs_ino->attr_list_size bytes.
916 */
917 if (m->flags & MFT_RECORD_IS_DIRECTORY) {
918 struct index_root *ir;
919
920 view_index_meta:
921 /* It is a directory, find index root attribute. */
922 ntfs_attr_reinit_search_ctx(ctx);
923 err = ntfs_attr_lookup(AT_INDEX_ROOT, name, name_len, CASE_SENSITIVE,
924 0, NULL, 0, ctx);
925 if (unlikely(err)) {
926 if (err == -ENOENT)
927 ntfs_error(vi->i_sb, "$INDEX_ROOT attribute is missing.");
928 goto unm_err_out;
929 }
930 a = ctx->attr;
931 /* Set up the state. */
932 if (unlikely(a->non_resident)) {
933 ntfs_error(vol->sb,
934 "$INDEX_ROOT attribute is not resident.");
935 goto unm_err_out;
936 }
937 /* Ensure the attribute name is placed before the value. */
938 if (unlikely(a->name_length && (le16_to_cpu(a->name_offset) >=
939 le16_to_cpu(a->data.resident.value_offset)))) {
940 ntfs_error(vol->sb,
941 "$INDEX_ROOT attribute name is placed after the attribute value.");
942 goto unm_err_out;
943 }
944 /*
945 * Compressed/encrypted index root just means that the newly
946 * created files in that directory should be created compressed/
947 * encrypted. However index root cannot be both compressed and
948 * encrypted.
949 */
950 if (a->flags & ATTR_COMPRESSION_MASK) {
951 NInoSetCompressed(ni);
952 ni->flags |= FILE_ATTR_COMPRESSED;
953 }
954 if (a->flags & ATTR_IS_ENCRYPTED) {
955 if (a->flags & ATTR_COMPRESSION_MASK) {
956 ntfs_error(vi->i_sb, "Found encrypted and compressed attribute.");
957 goto unm_err_out;
958 }
959 NInoSetEncrypted(ni);
960 ni->flags |= FILE_ATTR_ENCRYPTED;
961 }
962 if (a->flags & ATTR_IS_SPARSE) {
963 NInoSetSparse(ni);
964 ni->flags |= FILE_ATTR_SPARSE_FILE;
965 }
966 ir = (struct index_root *)((u8 *)a +
967 le16_to_cpu(a->data.resident.value_offset));
968 if (ntfs_index_root_inconsistent(ni->vol, a, ir, ni->mft_no) ||
969 ntfs_index_entries_inconsistent(ni->vol, &ir->index,
970 ir->collation_rule, ni->mft_no)) {
971 ntfs_error(vi->i_sb, "Directory index is corrupt.");
972 goto unm_err_out;
973 }
974
975 if (extend_sys) {
976 if (ir->type) {
977 ntfs_error(vi->i_sb, "Indexed attribute is not zero.");
978 goto unm_err_out;
979 }
980 } else {
981 if (ir->type != AT_FILE_NAME) {
982 ntfs_error(vi->i_sb, "Indexed attribute is not $FILE_NAME.");
983 goto unm_err_out;
984 }
985
986 if (ir->collation_rule != COLLATION_FILE_NAME) {
987 ntfs_error(vi->i_sb,
988 "Index collation rule is not COLLATION_FILE_NAME.");
989 goto unm_err_out;
990 }
991 }
992
993 ni->itype.index.collation_rule = ir->collation_rule;
994 ni->itype.index.block_size = le32_to_cpu(ir->index_block_size);
995 if (ni->itype.index.block_size &
996 (ni->itype.index.block_size - 1)) {
997 ntfs_error(vi->i_sb, "Index block size (%u) is not a power of two.",
998 ni->itype.index.block_size);
999 goto unm_err_out;
1000 }
1001 if (ni->itype.index.block_size > PAGE_SIZE) {
1002 ntfs_error(vi->i_sb,
1003 "Index block size (%u) > PAGE_SIZE (%ld) is not supported.",
1004 ni->itype.index.block_size,
1005 PAGE_SIZE);
1006 err = -EOPNOTSUPP;
1007 goto unm_err_out;
1008 }
1009 if (ni->itype.index.block_size < NTFS_BLOCK_SIZE) {
1010 ntfs_error(vi->i_sb,
1011 "Index block size (%u) < NTFS_BLOCK_SIZE (%i) is not supported.",
1012 ni->itype.index.block_size,
1013 NTFS_BLOCK_SIZE);
1014 err = -EOPNOTSUPP;
1015 goto unm_err_out;
1016 }
1017 ni->itype.index.block_size_bits =
1018 ffs(ni->itype.index.block_size) - 1;
1019 /* Determine the size of a vcn in the directory index. */
1020 if (vol->cluster_size <= ni->itype.index.block_size) {
1021 ni->itype.index.vcn_size = vol->cluster_size;
1022 ni->itype.index.vcn_size_bits = vol->cluster_size_bits;
1023 } else {
1024 ni->itype.index.vcn_size = vol->sector_size;
1025 ni->itype.index.vcn_size_bits = vol->sector_size_bits;
1026 }
1027
1028 /* Setup the index allocation attribute, even if not present. */
1029 ni->type = AT_INDEX_ROOT;
1030 ni->name = name;
1031 ni->name_len = name_len;
1032 vi->i_size = ni->initialized_size = ni->data_size =
1033 le32_to_cpu(a->data.resident.value_length);
1034 ni->allocated_size = (ni->data_size + 7) & ~7;
1035 /* We are done with the mft record, so we release it. */
1036 ntfs_attr_put_search_ctx(ctx);
1037 unmap_mft_record(ni);
1038 m = NULL;
1039 ctx = NULL;
1040 /* Setup the operations for this inode. */
1041 ntfs_set_vfs_operations(vi, vi->i_mode, 0);
1042 if (ir->index.flags & LARGE_INDEX)
1043 NInoSetIndexAllocPresent(ni);
1044 } else {
1045 /* It is a file. */
1046 ntfs_attr_reinit_search_ctx(ctx);
1047
1048 /* Setup the data attribute, even if not present. */
1049 ni->type = AT_DATA;
1050 ni->name = AT_UNNAMED;
1051 ni->name_len = 0;
1052
1053 /* Find first extent of the unnamed data attribute. */
1054 err = ntfs_attr_lookup(AT_DATA, NULL, 0, 0, 0, NULL, 0, ctx);
1055 if (unlikely(err)) {
1056 vi->i_size = ni->initialized_size =
1057 ni->allocated_size = 0;
1058 if (err != -ENOENT) {
1059 ntfs_error(vi->i_sb, "Failed to lookup $DATA attribute.");
1060 goto unm_err_out;
1061 }
1062 /*
1063 * FILE_Secure does not have an unnamed $DATA
1064 * attribute, so we special case it here.
1065 */
1066 if (vi->i_ino == FILE_Secure)
1067 goto no_data_attr_special_case;
1068 /*
1069 * Most if not all the system files in the $Extend
1070 * system directory do not have unnamed data
1071 * attributes so we need to check if the parent
1072 * directory of the file is FILE_Extend and if it is
1073 * ignore this error. To do this we need to get the
1074 * name of this inode from the mft record as the name
1075 * contains the back reference to the parent directory.
1076 */
1077 extend_sys = ntfs_is_extended_system_file(ctx);
1078 if (extend_sys > 0) {
1079 if (m->flags & MFT_RECORD_IS_VIEW_INDEX) {
1080 if (extend_sys == 2) {
1081 name = reparse_index_name;
1082 name_len = 2;
1083 goto view_index_meta;
1084 } else if (extend_sys == 3) {
1085 name = objid_index_name;
1086 name_len = 2;
1087 goto view_index_meta;
1088 }
1089 }
1090 goto no_data_attr_special_case;
1091 }
1092
1093 err = extend_sys;
1094 ntfs_error(vi->i_sb, "$DATA attribute is missing, err : %d", err);
1095 goto unm_err_out;
1096 }
1097 a = ctx->attr;
1098 /* Setup the state. */
1099 if (a->flags & (ATTR_COMPRESSION_MASK | ATTR_IS_SPARSE)) {
1100 if (a->flags & ATTR_COMPRESSION_MASK) {
1101 if (NInoWofCompressed(ni)) {
1102 ntfs_error(vi->i_sb,
1103 "Found native compression on a WOF file.");
1104 goto unm_err_out;
1105 }
1106 NInoSetCompressed(ni);
1107 ni->flags |= FILE_ATTR_COMPRESSED;
1108 if (vol->cluster_size > 4096) {
1109 ntfs_error(vi->i_sb,
1110 "Found compressed data but compression is disabled due to cluster size (%i) > 4kiB.",
1111 vol->cluster_size);
1112 goto unm_err_out;
1113 }
1114 if ((a->flags & ATTR_COMPRESSION_MASK)
1115 != ATTR_IS_COMPRESSED) {
1116 ntfs_error(vi->i_sb,
1117 "Found unknown compression method or corrupt file.");
1118 goto unm_err_out;
1119 }
1120 }
1121 if (a->flags & ATTR_IS_SPARSE) {
1122 NInoSetSparse(ni);
1123 ni->flags |= FILE_ATTR_SPARSE_FILE;
1124 }
1125 }
1126 if (a->flags & ATTR_IS_ENCRYPTED) {
1127 if (NInoCompressed(ni)) {
1128 ntfs_error(vi->i_sb, "Found encrypted and compressed data.");
1129 goto unm_err_out;
1130 }
1131 NInoSetEncrypted(ni);
1132 ni->flags |= FILE_ATTR_ENCRYPTED;
1133 }
1134 if (a->non_resident) {
1135 NInoSetNonResident(ni);
1136 if (NInoCompressed(ni) || (NInoSparse(ni) && !NInoWofCompressed(ni))) {
1137 if (NInoCompressed(ni) &&
1138 a->data.non_resident.compression_unit != 4) {
1139 ntfs_error(vi->i_sb,
1140 "Found non-standard compression unit (%u instead of 4). Cannot handle this.",
1141 a->data.non_resident.compression_unit);
1142 err = -EOPNOTSUPP;
1143 goto unm_err_out;
1144 }
1145
1146 if (NInoSparse(ni) &&
1147 a->data.non_resident.compression_unit &&
1148 a->data.non_resident.compression_unit !=
1149 vol->sparse_compression_unit) {
1150 ntfs_error(vi->i_sb,
1151 "Found non-standard compression unit (%u instead of 0 or %d). Cannot handle this.",
1152 a->data.non_resident.compression_unit,
1153 vol->sparse_compression_unit);
1154 err = -EOPNOTSUPP;
1155 goto unm_err_out;
1156 }
1157
1158
1159 if (a->data.non_resident.compression_unit) {
1160 ni->itype.compressed.block_size = 1U <<
1161 (a->data.non_resident.compression_unit +
1162 vol->cluster_size_bits);
1163 ni->itype.compressed.block_size_bits =
1164 ffs(ni->itype.compressed.block_size) - 1;
1165 ni->itype.compressed.block_clusters =
1166 1U << a->data.non_resident.compression_unit;
1167 } else {
1168 ni->itype.compressed.block_size = 0;
1169 ni->itype.compressed.block_size_bits =
1170 0;
1171 ni->itype.compressed.block_clusters =
1172 0;
1173 }
1174 ni->itype.compressed.size = le64_to_cpu(
1175 a->data.non_resident.compressed_size);
1176 }
1177 if (a->data.non_resident.lowest_vcn) {
1178 ntfs_error(vi->i_sb,
1179 "First extent of $DATA attribute has non zero lowest_vcn.");
1180 goto unm_err_out;
1181 }
1182 vi->i_size = ni->data_size = le64_to_cpu(a->data.non_resident.data_size);
1183 ni->initialized_size = le64_to_cpu(a->data.non_resident.initialized_size);
1184 ni->allocated_size = le64_to_cpu(a->data.non_resident.allocated_size);
1185 } else { /* Resident attribute. */
1186 vi->i_size = ni->data_size = ni->initialized_size = le32_to_cpu(
1187 a->data.resident.value_length);
1188 ni->allocated_size = le32_to_cpu(a->length) -
1189 le16_to_cpu(
1190 a->data.resident.value_offset);
1191 if (vi->i_size > ni->allocated_size) {
1192 ntfs_error(vi->i_sb,
1193 "Resident data attribute is corrupt (size exceeds allocation).");
1194 goto unm_err_out;
1195 }
1196 }
1197 no_data_attr_special_case:
1198 /* We are done with the mft record, so we release it. */
1199 ntfs_attr_put_search_ctx(ctx);
1200 unmap_mft_record(ni);
1201 m = NULL;
1202 ctx = NULL;
1203 /* Setup the operations for this inode. */
1204 ntfs_set_vfs_operations(vi, vi->i_mode, dev);
1205 }
1206
1207 if (NVolSysImmutable(vol) && (ni->flags & FILE_ATTR_SYSTEM) &&
1208 !S_ISFIFO(vi->i_mode) && !S_ISSOCK(vi->i_mode) && !S_ISLNK(vi->i_mode))
1209 vi->i_flags |= S_IMMUTABLE;
1210
1211 /*
1212 * System files such as $Bitmap and $MFT are maintained by the driver
1213 * itself, and writing them from userspace corrupts the volume.
1214 * Always make them immutable regardless of the sys_immutable option.
1215 * Directories are skipped so the root and $Extend stay usable.
1216 */
1217 if (ni->mft_no < FILE_first_user && S_ISREG(vi->i_mode))
1218 vi->i_flags |= S_IMMUTABLE;
1219
1220 /*
1221 * The number of 512-byte blocks used on disk (for stat). This is in so
1222 * far inaccurate as it doesn't account for any named streams or other
1223 * special non-resident attributes, but that is how Windows works, too,
1224 * so we are at least consistent with Windows, if not entirely
1225 * consistent with the Linux Way. Doing it the Linux Way would cause a
1226 * significant slowdown as it would involve iterating over all
1227 * attributes in the mft record and adding the allocated/compressed
1228 * sizes of all non-resident attributes present to give us the Linux
1229 * correct size that should go into i_blocks (after division by 512).
1230 */
1231 if (S_ISREG(vi->i_mode) &&
1232 (NInoCompressed(ni) || (NInoSparse(ni) && !NInoWofCompressed(ni))))
1233 vi->i_blocks = ni->itype.compressed.size >> 9;
1234 else
1235 vi->i_blocks = ni->allocated_size >> 9;
1236
1237 if (S_ISLNK(vi->i_mode) && ni->target)
1238 vi->i_size = strlen(ni->target);
1239
1240 ntfs_debug("Done.");
1241 return 0;
1242 unm_err_out:
1243 if (!err)
1244 err = -EIO;
1245 if (ctx)
1246 ntfs_attr_put_search_ctx(ctx);
1247 if (m)
1248 unmap_mft_record(ni);
1249 err_out:
1250 if (err != -EOPNOTSUPP && err != -ENOMEM &&
1251 err != -EINTR && err != -ERESTARTSYS && vol_err == true) {
1252 ntfs_error(vol->sb,
1253 "Failed with error code %i. Marking corrupt inode 0x%llx as bad. Run chkdsk.",
1254 err, ni->mft_no);
1255 NVolSetErrors(vol);
1256 }
1257 return err;
1258 }
1259
1260 /*
1261 * ntfs_read_locked_attr_inode - read an attribute inode from its base inode
1262 * @base_vi: base inode
1263 * @vi: attribute inode to read
1264 *
1265 * ntfs_read_locked_attr_inode() is called from ntfs_attr_iget() to read the
1266 * attribute inode described by @vi into memory from the base mft record
1267 * described by @base_ni.
1268 *
1269 * ntfs_read_locked_attr_inode() maps, pins and locks the base inode for
1270 * reading and looks up the attribute described by @vi before setting up the
1271 * necessary fields in @vi as well as initializing the ntfs inode.
1272 *
1273 * Q: What locks are held when the function is called?
1274 * A: i_state has I_NEW set, hence the inode is locked, also
1275 * i_count is set to 1, so it is not going to go away
1276 *
1277 * Return 0 on success and -errno on error.
1278 *
1279 * Note this cannot be called for AT_INDEX_ALLOCATION.
1280 */
ntfs_read_locked_attr_inode(struct inode * base_vi,struct inode * vi)1281 static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi)
1282 {
1283 struct ntfs_volume *vol = NTFS_SB(vi->i_sb);
1284 struct ntfs_inode *ni = NTFS_I(vi), *base_ni = NTFS_I(base_vi);
1285 struct mft_record *m;
1286 struct attr_record *a;
1287 struct ntfs_attr_search_ctx *ctx;
1288 int err = 0;
1289
1290 ntfs_debug("Entering for i_ino 0x%llx.", ni->mft_no);
1291
1292 ntfs_init_big_inode(vi);
1293
1294 /* Just mirror the values from the base inode. */
1295 vi->i_uid = base_vi->i_uid;
1296 vi->i_gid = base_vi->i_gid;
1297 set_nlink(vi, base_vi->i_nlink);
1298 inode_set_mtime_to_ts(vi, inode_get_mtime(base_vi));
1299 inode_set_ctime_to_ts(vi, inode_get_ctime(base_vi));
1300 inode_set_atime_to_ts(vi, inode_get_atime(base_vi));
1301 vi->i_generation = ni->seq_no = base_ni->seq_no;
1302
1303 /* Set inode type to zero but preserve permissions. */
1304 vi->i_mode = base_vi->i_mode & ~S_IFMT;
1305
1306 m = map_mft_record(base_ni);
1307 if (IS_ERR(m)) {
1308 err = PTR_ERR(m);
1309 goto err_out;
1310 }
1311 ctx = ntfs_attr_get_search_ctx(base_ni, m);
1312 if (!ctx) {
1313 err = -ENOMEM;
1314 goto unm_err_out;
1315 }
1316 /* Find the attribute. */
1317 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1318 CASE_SENSITIVE, 0, NULL, 0, ctx);
1319 if (unlikely(err))
1320 goto unm_err_out;
1321 a = ctx->attr;
1322 if (a->flags & (ATTR_COMPRESSION_MASK | ATTR_IS_SPARSE)) {
1323 if (a->flags & ATTR_COMPRESSION_MASK) {
1324 NInoSetCompressed(ni);
1325 ni->flags |= FILE_ATTR_COMPRESSED;
1326 if ((ni->type != AT_DATA) || (ni->type == AT_DATA &&
1327 ni->name_len)) {
1328 ntfs_error(vi->i_sb,
1329 "Found compressed non-data or named data attribute.");
1330 goto unm_err_out;
1331 }
1332 if (vol->cluster_size > 4096) {
1333 ntfs_error(vi->i_sb,
1334 "Found compressed attribute but compression is disabled due to cluster size (%i) > 4kiB.",
1335 vol->cluster_size);
1336 goto unm_err_out;
1337 }
1338 if ((a->flags & ATTR_COMPRESSION_MASK) !=
1339 ATTR_IS_COMPRESSED) {
1340 ntfs_error(vi->i_sb, "Found unknown compression method.");
1341 goto unm_err_out;
1342 }
1343 }
1344 /*
1345 * The compressed/sparse flag set in an index root just means
1346 * to compress all files.
1347 */
1348 if (NInoMstProtected(ni) && ni->type != AT_INDEX_ROOT) {
1349 ntfs_error(vi->i_sb,
1350 "Found mst protected attribute but the attribute is %s.",
1351 NInoCompressed(ni) ? "compressed" : "sparse");
1352 goto unm_err_out;
1353 }
1354 if (a->flags & ATTR_IS_SPARSE) {
1355 NInoSetSparse(ni);
1356 ni->flags |= FILE_ATTR_SPARSE_FILE;
1357 }
1358 }
1359 if (a->flags & ATTR_IS_ENCRYPTED) {
1360 if (NInoCompressed(ni)) {
1361 ntfs_error(vi->i_sb, "Found encrypted and compressed data.");
1362 goto unm_err_out;
1363 }
1364 /*
1365 * The encryption flag set in an index root just means to
1366 * encrypt all files.
1367 */
1368 if (NInoMstProtected(ni) && ni->type != AT_INDEX_ROOT) {
1369 ntfs_error(vi->i_sb,
1370 "Found mst protected attribute but the attribute is encrypted.");
1371 goto unm_err_out;
1372 }
1373 if (ni->type != AT_DATA) {
1374 ntfs_error(vi->i_sb,
1375 "Found encrypted non-data attribute.");
1376 goto unm_err_out;
1377 }
1378 NInoSetEncrypted(ni);
1379 ni->flags |= FILE_ATTR_ENCRYPTED;
1380 }
1381 if (!a->non_resident) {
1382 /* Ensure the attribute name is placed before the value. */
1383 if (unlikely(a->name_length && (le16_to_cpu(a->name_offset) >=
1384 le16_to_cpu(a->data.resident.value_offset)))) {
1385 ntfs_error(vol->sb,
1386 "Attribute name is placed after the attribute value.");
1387 goto unm_err_out;
1388 }
1389 if (NInoMstProtected(ni)) {
1390 ntfs_error(vi->i_sb,
1391 "Found mst protected attribute but the attribute is resident.");
1392 goto unm_err_out;
1393 }
1394 vi->i_size = ni->initialized_size = ni->data_size = le32_to_cpu(
1395 a->data.resident.value_length);
1396 ni->allocated_size = le32_to_cpu(a->length) -
1397 le16_to_cpu(a->data.resident.value_offset);
1398 if (vi->i_size > ni->allocated_size) {
1399 ntfs_error(vi->i_sb,
1400 "Resident attribute is corrupt (size exceeds allocation).");
1401 goto unm_err_out;
1402 }
1403 } else {
1404 NInoSetNonResident(ni);
1405 /*
1406 * Ensure the attribute name is placed before the mapping pairs
1407 * array.
1408 */
1409 if (unlikely(a->name_length && (le16_to_cpu(a->name_offset) >=
1410 le16_to_cpu(
1411 a->data.non_resident.mapping_pairs_offset)))) {
1412 ntfs_error(vol->sb,
1413 "Attribute name is placed after the mapping pairs array.");
1414 goto unm_err_out;
1415 }
1416 if (NInoCompressed(ni) || (NInoSparse(ni) && !NInoWofCompressed(ni))) {
1417 if (NInoCompressed(ni) && a->data.non_resident.compression_unit != 4) {
1418 ntfs_error(vi->i_sb,
1419 "Found non-standard compression unit (%u instead of 4). Cannot handle this.",
1420 a->data.non_resident.compression_unit);
1421 err = -EOPNOTSUPP;
1422 goto unm_err_out;
1423 }
1424 if (a->data.non_resident.compression_unit) {
1425 ni->itype.compressed.block_size = 1U <<
1426 (a->data.non_resident.compression_unit +
1427 vol->cluster_size_bits);
1428 ni->itype.compressed.block_size_bits =
1429 ffs(ni->itype.compressed.block_size) - 1;
1430 ni->itype.compressed.block_clusters = 1U <<
1431 a->data.non_resident.compression_unit;
1432 } else {
1433 ni->itype.compressed.block_size = 0;
1434 ni->itype.compressed.block_size_bits = 0;
1435 ni->itype.compressed.block_clusters = 0;
1436 }
1437 ni->itype.compressed.size = le64_to_cpu(
1438 a->data.non_resident.compressed_size);
1439 }
1440 if (a->data.non_resident.lowest_vcn) {
1441 ntfs_error(vi->i_sb, "First extent of attribute has non-zero lowest_vcn.");
1442 goto unm_err_out;
1443 }
1444 vi->i_size = ni->data_size = le64_to_cpu(a->data.non_resident.data_size);
1445 ni->initialized_size = le64_to_cpu(a->data.non_resident.initialized_size);
1446 ni->allocated_size = le64_to_cpu(a->data.non_resident.allocated_size);
1447 }
1448 vi->i_mapping->a_ops = &ntfs_aops;
1449 if ((NInoCompressed(ni) || NInoSparse(ni)) && ni->type != AT_INDEX_ROOT)
1450 vi->i_blocks = ni->itype.compressed.size >> 9;
1451 else
1452 vi->i_blocks = ni->allocated_size >> 9;
1453 /*
1454 * Make sure the base inode does not go away and attach it to the
1455 * attribute inode.
1456 */
1457 if (!igrab(base_vi)) {
1458 err = -ENOENT;
1459 goto unm_err_out;
1460 }
1461 ni->ext.base_ntfs_ino = base_ni;
1462 ni->nr_extents = -1;
1463
1464 ntfs_attr_put_search_ctx(ctx);
1465 unmap_mft_record(base_ni);
1466
1467 ntfs_debug("Done.");
1468 return 0;
1469
1470 unm_err_out:
1471 if (!err)
1472 err = -EIO;
1473 if (ctx)
1474 ntfs_attr_put_search_ctx(ctx);
1475 unmap_mft_record(base_ni);
1476 err_out:
1477 if (err != -ENOENT && err != -EINTR && err != -ERESTARTSYS)
1478 ntfs_error(vol->sb,
1479 "Failed with error code %i while reading attribute inode (mft_no 0x%llx, type 0x%x, name_len %i). Marking corrupt inode and base inode 0x%llx as bad. Run chkdsk.",
1480 err, ni->mft_no, ni->type, ni->name_len,
1481 base_ni->mft_no);
1482 if (err != -ENOENT && err != -ENOMEM &&
1483 err != -EINTR && err != -ERESTARTSYS)
1484 NVolSetErrors(vol);
1485 return err;
1486 }
1487
1488 /*
1489 * ntfs_read_locked_index_inode - read an index inode from its base inode
1490 * @base_vi: base inode
1491 * @vi: index inode to read
1492 *
1493 * ntfs_read_locked_index_inode() is called from ntfs_index_iget() to read the
1494 * index inode described by @vi into memory from the base mft record described
1495 * by @base_ni.
1496 *
1497 * ntfs_read_locked_index_inode() maps, pins and locks the base inode for
1498 * reading and looks up the attributes relating to the index described by @vi
1499 * before setting up the necessary fields in @vi as well as initializing the
1500 * ntfs inode.
1501 *
1502 * Note, index inodes are essentially attribute inodes (NInoAttr() is true)
1503 * with the attribute type set to AT_INDEX_ALLOCATION. Apart from that, they
1504 * are setup like directory inodes since directories are a special case of
1505 * indices ao they need to be treated in much the same way. Most importantly,
1506 * for small indices the index allocation attribute might not actually exist.
1507 * However, the index root attribute always exists but this does not need to
1508 * have an inode associated with it and this is why we define a new inode type
1509 * index. Also, like for directories, we need to have an attribute inode for
1510 * the bitmap attribute corresponding to the index allocation attribute and we
1511 * can store this in the appropriate field of the inode, just like we do for
1512 * normal directory inodes.
1513 *
1514 * Q: What locks are held when the function is called?
1515 * A: i_state has I_NEW set, hence the inode is locked, also
1516 * i_count is set to 1, so it is not going to go away
1517 *
1518 * Return 0 on success and -errno on error.
1519 */
ntfs_read_locked_index_inode(struct inode * base_vi,struct inode * vi)1520 static int ntfs_read_locked_index_inode(struct inode *base_vi, struct inode *vi)
1521 {
1522 loff_t bvi_size;
1523 struct ntfs_volume *vol = NTFS_SB(vi->i_sb);
1524 struct ntfs_inode *ni = NTFS_I(vi), *base_ni = NTFS_I(base_vi), *bni;
1525 struct inode *bvi;
1526 struct mft_record *m;
1527 struct attr_record *a;
1528 struct ntfs_attr_search_ctx *ctx;
1529 struct index_root *ir;
1530 int err = 0;
1531
1532 ntfs_debug("Entering for i_ino 0x%llx.", ni->mft_no);
1533 lockdep_assert_held(&base_ni->mrec_lock);
1534
1535 ntfs_init_big_inode(vi);
1536 /* Just mirror the values from the base inode. */
1537 vi->i_uid = base_vi->i_uid;
1538 vi->i_gid = base_vi->i_gid;
1539 set_nlink(vi, base_vi->i_nlink);
1540 inode_set_mtime_to_ts(vi, inode_get_mtime(base_vi));
1541 inode_set_ctime_to_ts(vi, inode_get_ctime(base_vi));
1542 inode_set_atime_to_ts(vi, inode_get_atime(base_vi));
1543 vi->i_generation = ni->seq_no = base_ni->seq_no;
1544 /* Set inode type to zero but preserve permissions. */
1545 vi->i_mode = base_vi->i_mode & ~S_IFMT;
1546 /* Map the mft record for the base inode. */
1547 m = map_mft_record(base_ni);
1548 if (IS_ERR(m)) {
1549 err = PTR_ERR(m);
1550 goto err_out;
1551 }
1552 ctx = ntfs_attr_get_search_ctx(base_ni, m);
1553 if (!ctx) {
1554 err = -ENOMEM;
1555 goto unm_err_out;
1556 }
1557 /* Find the index root attribute. */
1558 err = ntfs_attr_lookup(AT_INDEX_ROOT, ni->name, ni->name_len,
1559 CASE_SENSITIVE, 0, NULL, 0, ctx);
1560 if (unlikely(err)) {
1561 if (err == -ENOENT)
1562 ntfs_error(vi->i_sb, "$INDEX_ROOT attribute is missing.");
1563 goto unm_err_out;
1564 }
1565 a = ctx->attr;
1566 /* Set up the state. */
1567 if (unlikely(a->non_resident)) {
1568 ntfs_error(vol->sb, "$INDEX_ROOT attribute is not resident.");
1569 goto unm_err_out;
1570 }
1571 /* Ensure the attribute name is placed before the value. */
1572 if (unlikely(a->name_length && (le16_to_cpu(a->name_offset) >=
1573 le16_to_cpu(a->data.resident.value_offset)))) {
1574 ntfs_error(vol->sb,
1575 "$INDEX_ROOT attribute name is placed after the attribute value.");
1576 goto unm_err_out;
1577 }
1578
1579 ir = (struct index_root *)((u8 *)a + le16_to_cpu(a->data.resident.value_offset));
1580 if (ntfs_index_root_inconsistent(vol, a, ir, ni->mft_no) ||
1581 ntfs_index_entries_inconsistent(vol, &ir->index,
1582 ir->collation_rule, ni->mft_no)) {
1583 ntfs_error(vi->i_sb, "Index is corrupt.");
1584 goto unm_err_out;
1585 }
1586
1587 ni->itype.index.collation_rule = ir->collation_rule;
1588 ntfs_debug("Index collation rule is 0x%x.",
1589 le32_to_cpu(ir->collation_rule));
1590 ni->itype.index.block_size = le32_to_cpu(ir->index_block_size);
1591 if (!is_power_of_2(ni->itype.index.block_size)) {
1592 ntfs_error(vi->i_sb, "Index block size (%u) is not a power of two.",
1593 ni->itype.index.block_size);
1594 goto unm_err_out;
1595 }
1596 if (ni->itype.index.block_size > PAGE_SIZE) {
1597 ntfs_error(vi->i_sb, "Index block size (%u) > PAGE_SIZE (%ld) is not supported.",
1598 ni->itype.index.block_size, PAGE_SIZE);
1599 err = -EOPNOTSUPP;
1600 goto unm_err_out;
1601 }
1602 if (ni->itype.index.block_size < NTFS_BLOCK_SIZE) {
1603 ntfs_error(vi->i_sb,
1604 "Index block size (%u) < NTFS_BLOCK_SIZE (%i) is not supported.",
1605 ni->itype.index.block_size, NTFS_BLOCK_SIZE);
1606 err = -EOPNOTSUPP;
1607 goto unm_err_out;
1608 }
1609 ni->itype.index.block_size_bits = ffs(ni->itype.index.block_size) - 1;
1610 /* Determine the size of a vcn in the index. */
1611 if (vol->cluster_size <= ni->itype.index.block_size) {
1612 ni->itype.index.vcn_size = vol->cluster_size;
1613 ni->itype.index.vcn_size_bits = vol->cluster_size_bits;
1614 } else {
1615 ni->itype.index.vcn_size = vol->sector_size;
1616 ni->itype.index.vcn_size_bits = vol->sector_size_bits;
1617 }
1618
1619 /* Find index allocation attribute. */
1620 ntfs_attr_reinit_search_ctx(ctx);
1621 err = ntfs_attr_lookup(AT_INDEX_ALLOCATION, ni->name, ni->name_len,
1622 CASE_SENSITIVE, 0, NULL, 0, ctx);
1623 if (unlikely(err)) {
1624 if (err == -ENOENT) {
1625 /* No index allocation. */
1626 vi->i_size = ni->initialized_size = ni->allocated_size = 0;
1627 /* We are done with the mft record, so we release it. */
1628 ntfs_attr_put_search_ctx(ctx);
1629 unmap_mft_record(base_ni);
1630 m = NULL;
1631 ctx = NULL;
1632 goto skip_large_index_stuff;
1633 } else
1634 ntfs_error(vi->i_sb, "Failed to lookup $INDEX_ALLOCATION attribute.");
1635 goto unm_err_out;
1636 }
1637 NInoSetIndexAllocPresent(ni);
1638 NInoSetNonResident(ni);
1639 ni->type = AT_INDEX_ALLOCATION;
1640
1641 a = ctx->attr;
1642 if (!a->non_resident) {
1643 ntfs_error(vi->i_sb, "$INDEX_ALLOCATION attribute is resident.");
1644 goto unm_err_out;
1645 }
1646 /*
1647 * Ensure the attribute name is placed before the mapping pairs array.
1648 */
1649 if (unlikely(a->name_length && (le16_to_cpu(a->name_offset) >=
1650 le16_to_cpu(a->data.non_resident.mapping_pairs_offset)))) {
1651 ntfs_error(vol->sb,
1652 "$INDEX_ALLOCATION attribute name is placed after the mapping pairs array.");
1653 goto unm_err_out;
1654 }
1655 if (a->flags & ATTR_IS_ENCRYPTED) {
1656 ntfs_error(vi->i_sb, "$INDEX_ALLOCATION attribute is encrypted.");
1657 goto unm_err_out;
1658 }
1659 if (a->flags & ATTR_IS_SPARSE) {
1660 ntfs_error(vi->i_sb, "$INDEX_ALLOCATION attribute is sparse.");
1661 goto unm_err_out;
1662 }
1663 if (a->flags & ATTR_COMPRESSION_MASK) {
1664 ntfs_error(vi->i_sb,
1665 "$INDEX_ALLOCATION attribute is compressed.");
1666 goto unm_err_out;
1667 }
1668 if (a->data.non_resident.lowest_vcn) {
1669 ntfs_error(vi->i_sb,
1670 "First extent of $INDEX_ALLOCATION attribute has non zero lowest_vcn.");
1671 goto unm_err_out;
1672 }
1673 vi->i_size = ni->data_size = le64_to_cpu(a->data.non_resident.data_size);
1674 ni->initialized_size = le64_to_cpu(a->data.non_resident.initialized_size);
1675 ni->allocated_size = le64_to_cpu(a->data.non_resident.allocated_size);
1676 /*
1677 * We are done with the mft record, so we release it. Otherwise
1678 * we would deadlock in ntfs_attr_iget().
1679 */
1680 ntfs_attr_put_search_ctx(ctx);
1681 unmap_mft_record(base_ni);
1682 m = NULL;
1683 ctx = NULL;
1684 /* Get the index bitmap attribute inode. */
1685 bvi = ntfs_attr_iget(base_vi, AT_BITMAP, ni->name, ni->name_len);
1686 if (IS_ERR(bvi)) {
1687 err = PTR_ERR(bvi);
1688 if (err != -EINTR && err != -ERESTARTSYS)
1689 ntfs_error(vi->i_sb, "Failed to get bitmap attribute.");
1690 goto unm_err_out;
1691 }
1692 bni = NTFS_I(bvi);
1693 if (NInoCompressed(bni) || NInoEncrypted(bni) ||
1694 NInoSparse(bni)) {
1695 ntfs_error(vi->i_sb,
1696 "$BITMAP attribute is compressed and/or encrypted and/or sparse.");
1697 goto iput_unm_err_out;
1698 }
1699 /* Consistency check bitmap size vs. index allocation size. */
1700 bvi_size = i_size_read(bvi);
1701 if ((bvi_size << 3) < (vi->i_size >> ni->itype.index.block_size_bits)) {
1702 ntfs_error(vi->i_sb,
1703 "Index bitmap too small (0x%llx) for index allocation (0x%llx).",
1704 bvi_size << 3, vi->i_size);
1705 goto iput_unm_err_out;
1706 }
1707 iput(bvi);
1708 skip_large_index_stuff:
1709 /* Setup the operations for this index inode. */
1710 ntfs_set_vfs_operations(vi, S_IFDIR, 0);
1711 vi->i_blocks = ni->allocated_size >> 9;
1712 /*
1713 * Make sure the base inode doesn't go away and attach it to the
1714 * index inode.
1715 */
1716 if (!igrab(base_vi))
1717 goto unm_err_out;
1718 ni->ext.base_ntfs_ino = base_ni;
1719 ni->nr_extents = -1;
1720
1721 ntfs_debug("Done.");
1722 return 0;
1723 iput_unm_err_out:
1724 iput(bvi);
1725 unm_err_out:
1726 if (!err)
1727 err = -EIO;
1728 if (ctx)
1729 ntfs_attr_put_search_ctx(ctx);
1730 if (m)
1731 unmap_mft_record(base_ni);
1732 err_out:
1733 if (err != -EINTR && err != -ERESTARTSYS)
1734 ntfs_error(vi->i_sb,
1735 "Failed with error code %i while reading index inode (mft_no 0x%llx, name_len %i.",
1736 err, ni->mft_no, ni->name_len);
1737 if (err != -EOPNOTSUPP && err != -ENOMEM &&
1738 err != -EINTR && err != -ERESTARTSYS)
1739 NVolSetErrors(vol);
1740 return err;
1741 }
1742
1743 /*
1744 * load_attribute_list_mount - load an attribute list into memory
1745 * @vol: ntfs volume from which to read
1746 * @rl: runlist of the attribute list
1747 * @al_start: destination buffer
1748 * @size: size of the destination buffer in bytes
1749 * @initialized_size: initialized size of the attribute list
1750 *
1751 * Walk the runlist @rl and load all clusters from it copying them into
1752 * the linear buffer @al. The maximum number of bytes copied to @al is @size
1753 * bytes. Note, @size does not need to be a multiple of the cluster size. If
1754 * @initialized_size is less than @size, the region in @al between
1755 * @initialized_size and @size will be zeroed and not read from disk.
1756 *
1757 * Return 0 on success or -errno on error.
1758 */
load_attribute_list_mount(struct ntfs_volume * vol,struct runlist_element * rl,u8 * al_start,const s64 size,const s64 initialized_size)1759 static int load_attribute_list_mount(struct ntfs_volume *vol,
1760 struct runlist_element *rl, u8 *al_start, const s64 size,
1761 const s64 initialized_size)
1762 {
1763 s64 lcn;
1764 u8 *al = al_start;
1765 u8 *al_end = al + initialized_size;
1766 struct super_block *sb;
1767 int err = 0;
1768 loff_t rl_byte_off, rl_byte_len;
1769
1770 ntfs_debug("Entering.");
1771 if (!vol || !rl || !al || size <= 0 || initialized_size < 0 ||
1772 initialized_size > size)
1773 return -EINVAL;
1774 if (!initialized_size) {
1775 memset(al, 0, size);
1776 return 0;
1777 }
1778 sb = vol->sb;
1779
1780 /* Read all clusters specified by the runlist one run at a time. */
1781 while (rl->length) {
1782 lcn = ntfs_rl_vcn_to_lcn(rl, rl->vcn);
1783 ntfs_debug("Reading vcn = 0x%llx, lcn = 0x%llx.",
1784 (unsigned long long)rl->vcn,
1785 (unsigned long long)lcn);
1786 /* The attribute list cannot be sparse. */
1787 if (lcn < 0) {
1788 ntfs_error(sb, "ntfs_rl_vcn_to_lcn() failed. Cannot read attribute list.");
1789 return -EIO;
1790 }
1791
1792 rl_byte_off = ntfs_cluster_to_bytes(vol, lcn);
1793 rl_byte_len = ntfs_cluster_to_bytes(vol, rl->length);
1794
1795 if (al + rl_byte_len > al_end)
1796 rl_byte_len = al_end - al;
1797
1798 err = ntfs_bdev_read(sb->s_bdev, al, rl_byte_off,
1799 round_up(rl_byte_len, SECTOR_SIZE));
1800 if (err) {
1801 ntfs_error(sb, "Cannot read attribute list.");
1802 return -EIO;
1803 }
1804
1805 if (al + rl_byte_len >= al_end) {
1806 if (initialized_size < size)
1807 goto initialize;
1808 goto done;
1809 }
1810
1811 al += rl_byte_len;
1812 rl++;
1813 }
1814 if (initialized_size < size) {
1815 initialize:
1816 memset(al_start + initialized_size, 0, size - initialized_size);
1817 }
1818 done:
1819 return err;
1820 }
1821
1822 /*
1823 * The MFT inode has special locking, so teach the lock validator
1824 * about this by splitting off the locking rules of the MFT from
1825 * the locking rules of other inodes. The MFT inode can never be
1826 * accessed from the VFS side (or even internally), only by the
1827 * map_mft functions.
1828 */
1829 static struct lock_class_key mft_ni_runlist_lock_key, mft_ni_mrec_lock_key;
1830
1831 /*
1832 * ntfs_read_inode_mount - special read_inode for mount time use only
1833 * @vi: inode to read
1834 *
1835 * Read inode FILE_MFT at mount time, only called with super_block lock
1836 * held from within the read_super() code path.
1837 *
1838 * This function exists because when it is called the page cache for $MFT/$DATA
1839 * is not initialized and hence we cannot get at the contents of mft records
1840 * by calling map_mft_record*().
1841 *
1842 * Further it needs to cope with the circular references problem, i.e. cannot
1843 * load any attributes other than $ATTRIBUTE_LIST until $DATA is loaded, because
1844 * we do not know where the other extent mft records are yet and again, because
1845 * we cannot call map_mft_record*() yet. Obviously this applies only when an
1846 * attribute list is actually present in $MFT inode.
1847 *
1848 * We solve these problems by starting with the $DATA attribute before anything
1849 * else and iterating using ntfs_attr_lookup($DATA) over all extents. As each
1850 * extent is found, we ntfs_mapping_pairs_decompress() including the implied
1851 * ntfs_runlists_merge(). Each step of the iteration necessarily provides
1852 * sufficient information for the next step to complete.
1853 *
1854 * This should work but there are two possible pit falls (see inline comments
1855 * below), but only time will tell if they are real pits or just smoke...
1856 */
ntfs_read_inode_mount(struct inode * vi)1857 int ntfs_read_inode_mount(struct inode *vi)
1858 {
1859 s64 next_vcn, last_vcn, highest_vcn;
1860 struct super_block *sb = vi->i_sb;
1861 struct ntfs_volume *vol = NTFS_SB(sb);
1862 struct ntfs_inode *ni = NTFS_I(vi);
1863 struct mft_record *m = NULL;
1864 struct attr_record *a;
1865 struct ntfs_attr_search_ctx *ctx;
1866 unsigned int i;
1867 int err;
1868 size_t new_rl_count;
1869
1870 ntfs_debug("Entering.");
1871
1872 /* Initialize the ntfs specific part of @vi. */
1873 ntfs_init_big_inode(vi);
1874
1875
1876 /* Setup the data attribute. It is special as it is mst protected. */
1877 NInoSetNonResident(ni);
1878 NInoSetMstProtected(ni);
1879 NInoSetSparseDisabled(ni);
1880 ni->type = AT_DATA;
1881 ni->name = AT_UNNAMED;
1882 ni->name_len = 0;
1883 /*
1884 * This sets up our little cheat allowing us to reuse the async read io
1885 * completion handler for directories.
1886 */
1887 ni->itype.index.block_size = vol->mft_record_size;
1888 ni->itype.index.block_size_bits = vol->mft_record_size_bits;
1889
1890 /* Very important! Needed to be able to call map_mft_record*(). */
1891 vol->mft_ino = vi;
1892
1893 /* Allocate enough memory to read the first mft record. */
1894 if (vol->mft_record_size > 64 * 1024) {
1895 ntfs_error(sb, "Unsupported mft record size %i (max 64kiB).",
1896 vol->mft_record_size);
1897 goto err_out;
1898 }
1899
1900 i = vol->mft_record_size;
1901 if (i < sb->s_blocksize)
1902 i = sb->s_blocksize;
1903
1904 m = kzalloc(i, GFP_NOFS);
1905 if (!m) {
1906 ntfs_error(sb, "Failed to allocate buffer for $MFT record 0.");
1907 goto err_out;
1908 }
1909
1910 /* Load $MFT/$DATA's first mft record. */
1911 err = ntfs_bdev_read(sb->s_bdev, (char *)m,
1912 ntfs_cluster_to_bytes(vol, vol->mft_lcn), i);
1913 if (err) {
1914 ntfs_error(sb, "Device read failed.");
1915 goto err_out;
1916 }
1917
1918 if (le32_to_cpu(m->bytes_allocated) != vol->mft_record_size) {
1919 ntfs_error(sb, "Incorrect mft record size %u in superblock, should be %u.",
1920 le32_to_cpu(m->bytes_allocated), vol->mft_record_size);
1921 goto err_out;
1922 }
1923
1924 /* Apply the mst fixups. */
1925 if (post_read_mst_fixup((struct ntfs_record *)m, vol->mft_record_size)) {
1926 ntfs_error(sb, "MST fixup failed. $MFT is corrupt.");
1927 goto err_out;
1928 }
1929
1930 if (ntfs_mft_record_check(vol, m, FILE_MFT)) {
1931 ntfs_error(sb, "ntfs_mft_record_check failed. $MFT is corrupt.");
1932 goto err_out;
1933 }
1934
1935 /* Need this to sanity check attribute list references to $MFT. */
1936 vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
1937
1938 /* Provides read_folio() for map_mft_record(). */
1939 vi->i_mapping->a_ops = &ntfs_mft_aops;
1940
1941 ctx = ntfs_attr_get_search_ctx(ni, m);
1942 if (!ctx) {
1943 err = -ENOMEM;
1944 goto err_out;
1945 }
1946
1947 /* Find the attribute list attribute if present. */
1948 err = ntfs_attr_lookup(AT_ATTRIBUTE_LIST, NULL, 0, 0, 0, NULL, 0, ctx);
1949 if (err) {
1950 if (unlikely(err != -ENOENT)) {
1951 ntfs_error(sb,
1952 "Failed to lookup attribute list attribute. You should run chkdsk.");
1953 goto put_err_out;
1954 }
1955 } else /* if (!err) */ {
1956 struct attr_list_entry *al_entry, *next_al_entry;
1957 u8 *al_end;
1958 static const char *es = " Not allowed. $MFT is corrupt. You should run chkdsk.";
1959
1960 ntfs_debug("Attribute list attribute found in $MFT.");
1961 NInoSetAttrList(ni);
1962 a = ctx->attr;
1963 if (a->flags & ATTR_COMPRESSION_MASK) {
1964 ntfs_error(sb,
1965 "Attribute list attribute is compressed.%s",
1966 es);
1967 goto put_err_out;
1968 }
1969 if (a->flags & ATTR_IS_ENCRYPTED ||
1970 a->flags & ATTR_IS_SPARSE) {
1971 if (a->non_resident) {
1972 ntfs_error(sb,
1973 "Non-resident attribute list attribute is encrypted/sparse.%s",
1974 es);
1975 goto put_err_out;
1976 }
1977 ntfs_warning(sb,
1978 "Resident attribute list attribute in $MFT system file is marked encrypted/sparse which is not true. However, Windows allows this and chkdsk does not detect or correct it so we will just ignore the invalid flags and pretend they are not set.");
1979 }
1980 /* Now allocate memory for the attribute list. */
1981 ni->attr_list_size = (u32)ntfs_attr_size(a);
1982 if (!ni->attr_list_size) {
1983 ntfs_error(sb, "Attr_list_size is zero");
1984 goto put_err_out;
1985 }
1986 ni->attr_list = kvzalloc(round_up(ni->attr_list_size, SECTOR_SIZE),
1987 GFP_NOFS);
1988 if (!ni->attr_list) {
1989 ntfs_error(sb, "Not enough memory to allocate buffer for attribute list.");
1990 goto put_err_out;
1991 }
1992 if (a->non_resident) {
1993 struct runlist_element *rl;
1994 size_t new_rl_count;
1995
1996 NInoSetAttrListNonResident(ni);
1997 if (a->data.non_resident.lowest_vcn) {
1998 ntfs_error(sb,
1999 "Attribute list has non zero lowest_vcn. $MFT is corrupt. You should run chkdsk.");
2000 goto put_err_out;
2001 }
2002
2003 rl = ntfs_mapping_pairs_decompress(vol, a, NULL, &new_rl_count);
2004 if (IS_ERR(rl)) {
2005 err = PTR_ERR(rl);
2006 ntfs_error(sb,
2007 "Mapping pairs decompression failed with error code %i.",
2008 -err);
2009 goto put_err_out;
2010 }
2011
2012 err = load_attribute_list_mount(vol, rl, ni->attr_list, ni->attr_list_size,
2013 le64_to_cpu(a->data.non_resident.initialized_size));
2014 kvfree(rl);
2015 if (err) {
2016 ntfs_error(sb,
2017 "Failed to load attribute list with error code %i.",
2018 -err);
2019 goto put_err_out;
2020 }
2021 } else /* if (!ctx.attr->non_resident) */ {
2022 /* Now copy the attribute list. */
2023 memcpy(ni->attr_list, (u8 *)a + le16_to_cpu(
2024 a->data.resident.value_offset),
2025 le32_to_cpu(a->data.resident.value_length));
2026 }
2027 /* The attribute list is now setup in memory. */
2028 al_entry = (struct attr_list_entry *)ni->attr_list;
2029 al_end = (u8 *)al_entry + ni->attr_list_size;
2030 for (;; al_entry = next_al_entry) {
2031 /* Out of bounds check. */
2032 if ((u8 *)al_entry < ni->attr_list ||
2033 (u8 *)al_entry > al_end)
2034 goto em_put_err_out;
2035 /* Catch the end of the attribute list. */
2036 if ((u8 *)al_entry == al_end)
2037 goto em_put_err_out;
2038 if (!ntfs_attr_list_entry_is_valid(al_entry, al_end))
2039 goto em_put_err_out;
2040 next_al_entry = (struct attr_list_entry *)((u8 *)al_entry +
2041 le16_to_cpu(al_entry->length));
2042 if (le32_to_cpu(al_entry->type) > le32_to_cpu(AT_DATA))
2043 goto em_put_err_out;
2044 if (al_entry->type != AT_DATA)
2045 continue;
2046 /* We want an unnamed attribute. */
2047 if (al_entry->name_length)
2048 goto em_put_err_out;
2049 /* Want the first entry, i.e. lowest_vcn == 0. */
2050 if (al_entry->lowest_vcn)
2051 goto em_put_err_out;
2052 /* First entry has to be in the base mft record. */
2053 if (MREF_LE(al_entry->mft_reference) != vi->i_ino) {
2054 /* MFT references do not match, logic fails. */
2055 ntfs_error(sb,
2056 "BUG: The first $DATA extent of $MFT is not in the base mft record.");
2057 goto put_err_out;
2058 } else {
2059 /* Sequence numbers must match. */
2060 if (MSEQNO_LE(al_entry->mft_reference) !=
2061 ni->seq_no)
2062 goto em_put_err_out;
2063 /* Got it. All is ok. We can stop now. */
2064 break;
2065 }
2066 }
2067 }
2068
2069 ntfs_attr_reinit_search_ctx(ctx);
2070
2071 /* Now load all attribute extents. */
2072 a = NULL;
2073 next_vcn = last_vcn = highest_vcn = 0;
2074 while (!(err = ntfs_attr_lookup(AT_DATA, NULL, 0, 0, next_vcn, NULL, 0,
2075 ctx))) {
2076 struct runlist_element *nrl;
2077
2078 /* Cache the current attribute. */
2079 a = ctx->attr;
2080 /* $MFT must be non-resident. */
2081 if (!a->non_resident) {
2082 ntfs_error(sb,
2083 "$MFT must be non-resident but a resident extent was found. $MFT is corrupt. Run chkdsk.");
2084 goto put_err_out;
2085 }
2086 /* $MFT must be uncompressed and unencrypted. */
2087 if (a->flags & ATTR_COMPRESSION_MASK ||
2088 a->flags & ATTR_IS_ENCRYPTED ||
2089 a->flags & ATTR_IS_SPARSE) {
2090 ntfs_error(sb,
2091 "$MFT must be uncompressed, non-sparse, and unencrypted but a compressed/sparse/encrypted extent was found. $MFT is corrupt. Run chkdsk.");
2092 goto put_err_out;
2093 }
2094 /*
2095 * Decompress the mapping pairs array of this extent and merge
2096 * the result into the existing runlist. No need for locking
2097 * as we have exclusive access to the inode at this time and we
2098 * are a mount in progress task, too.
2099 */
2100 nrl = ntfs_mapping_pairs_decompress(vol, a, &ni->runlist,
2101 &new_rl_count);
2102 if (IS_ERR(nrl)) {
2103 ntfs_error(sb,
2104 "ntfs_mapping_pairs_decompress() failed with error code %ld.",
2105 PTR_ERR(nrl));
2106 goto put_err_out;
2107 }
2108 ni->runlist.rl = nrl;
2109 ni->runlist.count = new_rl_count;
2110
2111 /* Are we in the first extent? */
2112 if (!next_vcn) {
2113 if (a->data.non_resident.lowest_vcn) {
2114 ntfs_error(sb,
2115 "First extent of $DATA attribute has non zero lowest_vcn. $MFT is corrupt. You should run chkdsk.");
2116 goto put_err_out;
2117 }
2118 /* Get the last vcn in the $DATA attribute. */
2119 last_vcn = ntfs_bytes_to_cluster(vol,
2120 le64_to_cpu(a->data.non_resident.allocated_size));
2121 /* Fill in the inode size. */
2122 vi->i_size = le64_to_cpu(a->data.non_resident.data_size);
2123 ni->initialized_size = le64_to_cpu(a->data.non_resident.initialized_size);
2124 ni->allocated_size = le64_to_cpu(a->data.non_resident.allocated_size);
2125 /*
2126 * Verify the number of mft records does not exceed
2127 * 2^32 - 1.
2128 */
2129 if ((vi->i_size >> vol->mft_record_size_bits) >=
2130 (1ULL << 32)) {
2131 ntfs_error(sb, "$MFT is too big! Aborting.");
2132 goto put_err_out;
2133 }
2134 /*
2135 * We have got the first extent of the runlist for
2136 * $MFT which means it is now relatively safe to call
2137 * the normal ntfs_read_inode() function.
2138 * Complete reading the inode, this will actually
2139 * re-read the mft record for $MFT, this time entering
2140 * it into the page cache with which we complete the
2141 * kick start of the volume. It should be safe to do
2142 * this now as the first extent of $MFT/$DATA is
2143 * already known and we would hope that we don't need
2144 * further extents in order to find the other
2145 * attributes belonging to $MFT. Only time will tell if
2146 * this is really the case. If not we will have to play
2147 * magic at this point, possibly duplicating a lot of
2148 * ntfs_read_inode() at this point. We will need to
2149 * ensure we do enough of its work to be able to call
2150 * ntfs_read_inode() on extents of $MFT/$DATA. But lets
2151 * hope this never happens...
2152 */
2153 err = ntfs_read_locked_inode(vi);
2154 if (err) {
2155 ntfs_error(sb, "ntfs_read_inode() of $MFT failed.\n");
2156 ntfs_attr_put_search_ctx(ctx);
2157 /* Revert to the safe super operations. */
2158 kfree(m);
2159 return -1;
2160 }
2161 /*
2162 * Re-initialize some specifics about $MFT's inode as
2163 * ntfs_read_inode() will have set up the default ones.
2164 */
2165 /* Set uid and gid to root. */
2166 vi->i_uid = GLOBAL_ROOT_UID;
2167 vi->i_gid = GLOBAL_ROOT_GID;
2168 /* Regular file. No access for anyone. */
2169 vi->i_mode = S_IFREG;
2170 /* No VFS initiated operations allowed for $MFT. */
2171 vi->i_op = &ntfs_empty_inode_ops;
2172 vi->i_fop = &ntfs_empty_file_ops;
2173 }
2174
2175 /* Get the lowest vcn for the next extent. */
2176 highest_vcn = le64_to_cpu(a->data.non_resident.highest_vcn);
2177 next_vcn = highest_vcn + 1;
2178
2179 /* Only one extent or error, which we catch below. */
2180 if (next_vcn <= 0)
2181 break;
2182
2183 /* Avoid endless loops due to corruption. */
2184 if (next_vcn < le64_to_cpu(a->data.non_resident.lowest_vcn)) {
2185 ntfs_error(sb, "$MFT has corrupt attribute list attribute. Run chkdsk.");
2186 goto put_err_out;
2187 }
2188 }
2189 if (err != -ENOENT) {
2190 ntfs_error(sb, "Failed to lookup $MFT/$DATA attribute extent. Run chkdsk.\n");
2191 goto put_err_out;
2192 }
2193 if (!a) {
2194 ntfs_error(sb, "$MFT/$DATA attribute not found. $MFT is corrupt. Run chkdsk.");
2195 goto put_err_out;
2196 }
2197 if (highest_vcn && highest_vcn != last_vcn - 1) {
2198 ntfs_error(sb, "Failed to load the complete runlist for $MFT/$DATA. Run chkdsk.");
2199 ntfs_debug("highest_vcn = 0x%llx, last_vcn - 1 = 0x%llx",
2200 (unsigned long long)highest_vcn,
2201 (unsigned long long)last_vcn - 1);
2202 goto put_err_out;
2203 }
2204 ntfs_attr_put_search_ctx(ctx);
2205 ntfs_debug("Done.");
2206 kfree(m);
2207
2208 /*
2209 * Split the locking rules of the MFT inode from the
2210 * locking rules of other inodes:
2211 */
2212 lockdep_set_class(&ni->runlist.lock, &mft_ni_runlist_lock_key);
2213 lockdep_set_class(&ni->mrec_lock, &mft_ni_mrec_lock_key);
2214
2215 return 0;
2216
2217 em_put_err_out:
2218 ntfs_error(sb,
2219 "Couldn't find first extent of $DATA attribute in attribute list. $MFT is corrupt. Run chkdsk.");
2220 put_err_out:
2221 ntfs_attr_put_search_ctx(ctx);
2222 err_out:
2223 ntfs_error(sb, "Failed. Marking inode as bad.");
2224 kfree(m);
2225 return -1;
2226 }
2227
__ntfs_clear_inode(struct ntfs_inode * ni)2228 static void __ntfs_clear_inode(struct ntfs_inode *ni)
2229 {
2230 /* Free all alocated memory. */
2231 if (NInoNonResident(ni) && ni->runlist.rl) {
2232 kvfree(ni->runlist.rl);
2233 ni->runlist.rl = NULL;
2234 }
2235
2236 if (ni->attr_list) {
2237 kvfree(ni->attr_list);
2238 ni->attr_list = NULL;
2239 }
2240
2241 if (ni->name_len && ni->name != I30 &&
2242 ni->name != reparse_index_name &&
2243 ni->name != objid_index_name) {
2244 WARN_ON(!ni->name);
2245 kfree(ni->name);
2246 }
2247 }
2248
ntfs_clear_extent_inode(struct ntfs_inode * ni)2249 void ntfs_clear_extent_inode(struct ntfs_inode *ni)
2250 {
2251 ntfs_debug("Entering for inode 0x%llx.", ni->mft_no);
2252
2253 WARN_ON(NInoAttr(ni));
2254 WARN_ON(ni->nr_extents != -1);
2255
2256 __ntfs_clear_inode(ni);
2257 ntfs_destroy_extent_inode(ni);
2258 }
2259
ntfs_delete_base_inode(struct ntfs_inode * ni)2260 static int ntfs_delete_base_inode(struct ntfs_inode *ni)
2261 {
2262 struct super_block *sb = ni->vol->sb;
2263 int err;
2264
2265 if (NInoAttr(ni) || ni->nr_extents == -1)
2266 return 0;
2267
2268 err = ntfs_non_resident_dealloc_clusters(ni);
2269
2270 /*
2271 * Deallocate extent mft records and free extent inodes.
2272 * No need to lock as no one else has a reference.
2273 */
2274 while (ni->nr_extents) {
2275 err = ntfs_mft_record_free(ni->vol, *(ni->ext.extent_ntfs_inos));
2276 if (err)
2277 ntfs_error(sb,
2278 "Failed to free extent MFT record. Leaving inconsistent metadata.\n");
2279 ntfs_inode_close(*(ni->ext.extent_ntfs_inos));
2280 }
2281
2282 /* Deallocate base mft record */
2283 err = ntfs_mft_record_free(ni->vol, ni);
2284 if (err)
2285 ntfs_error(sb, "Failed to free base MFT record. Leaving inconsistent metadata.\n");
2286 return err;
2287 }
2288
2289 /*
2290 * ntfs_evict_big_inode - clean up the ntfs specific part of an inode
2291 * @vi: vfs inode pending annihilation
2292 *
2293 * When the VFS is going to remove an inode from memory, ntfs_clear_big_inode()
2294 * is called, which deallocates all memory belonging to the NTFS specific part
2295 * of the inode and returns.
2296 *
2297 * If the MFT record is dirty, we commit it before doing anything else.
2298 */
ntfs_evict_big_inode(struct inode * vi)2299 void ntfs_evict_big_inode(struct inode *vi)
2300 {
2301 struct ntfs_inode *ni = NTFS_I(vi);
2302
2303 truncate_inode_pages_final(&vi->i_data);
2304
2305 if (!vi->i_nlink) {
2306 if (!NInoAttr(ni)) {
2307 /* Never called with extent inodes */
2308 WARN_ON(ni->nr_extents == -1);
2309 ntfs_delete_base_inode(ni);
2310 }
2311 goto release;
2312 }
2313
2314 if (NInoDirty(ni)) {
2315 /* Committing the inode also commits all extent inodes. */
2316 ntfs_commit_inode(vi);
2317
2318 if (NInoDirty(ni)) {
2319 ntfs_debug("Failed to commit dirty inode 0x%llx. Losing data!",
2320 ni->mft_no);
2321 NInoClearAttrListDirty(ni);
2322 NInoClearDirty(ni);
2323 }
2324 }
2325
2326 /* No need to lock at this stage as no one else has a reference. */
2327 if (ni->nr_extents > 0) {
2328 int i;
2329
2330 for (i = 0; i < ni->nr_extents; i++) {
2331 if (ni->ext.extent_ntfs_inos[i])
2332 ntfs_clear_extent_inode(ni->ext.extent_ntfs_inos[i]);
2333 }
2334 ni->nr_extents = 0;
2335 kvfree(ni->ext.extent_ntfs_inos);
2336 }
2337
2338 release:
2339 clear_inode(vi);
2340 __ntfs_clear_inode(ni);
2341
2342 if (NInoAttr(ni)) {
2343 /* Release the base inode if we are holding it. */
2344 if (ni->nr_extents == -1) {
2345 iput(VFS_I(ni->ext.base_ntfs_ino));
2346 ni->nr_extents = 0;
2347 ni->ext.base_ntfs_ino = NULL;
2348 }
2349 }
2350
2351 if (!atomic_dec_and_test(&ni->count))
2352 WARN_ON(1);
2353 if (ni->folio)
2354 folio_put(ni->folio);
2355 kfree(ni->mrec);
2356 kvfree(ni->target);
2357 }
2358
2359 /*
2360 * ntfs_show_options - show mount options in /proc/mounts
2361 * @sf: seq_file in which to write our mount options
2362 * @root: root of the mounted tree whose mount options to display
2363 *
2364 * Called by the VFS once for each mounted ntfs volume when someone reads
2365 * /proc/mounts in order to display the NTFS specific mount options of each
2366 * mount. The mount options of fs specified by @root are written to the seq file
2367 * @sf and success is returned.
2368 */
ntfs_show_options(struct seq_file * sf,struct dentry * root)2369 int ntfs_show_options(struct seq_file *sf, struct dentry *root)
2370 {
2371 struct ntfs_volume *vol = NTFS_SB(root->d_sb);
2372 int i;
2373
2374 if (uid_valid(vol->uid))
2375 seq_printf(sf, ",uid=%i", from_kuid_munged(&init_user_ns, vol->uid));
2376 if (gid_valid(vol->gid))
2377 seq_printf(sf, ",gid=%i", from_kgid_munged(&init_user_ns, vol->gid));
2378 if (vol->fmask == vol->dmask)
2379 seq_printf(sf, ",umask=0%o", vol->fmask);
2380 else {
2381 seq_printf(sf, ",fmask=0%o", vol->fmask);
2382 seq_printf(sf, ",dmask=0%o", vol->dmask);
2383 }
2384 seq_printf(sf, ",iocharset=%s", vol->nls_map->charset);
2385 if (NVolCaseSensitive(vol))
2386 seq_puts(sf, ",case_sensitive");
2387 else
2388 seq_puts(sf, ",nocase");
2389 if (NVolShowSystemFiles(vol))
2390 seq_puts(sf, ",show_sys_files,showmeta");
2391 for (i = 0; on_errors_arr[i].val; i++) {
2392 if (on_errors_arr[i].val == vol->on_errors)
2393 seq_printf(sf, ",errors=%s", on_errors_arr[i].str);
2394 }
2395 seq_printf(sf, ",mft_zone_multiplier=%i", vol->mft_zone_multiplier);
2396 if (NVolSysImmutable(vol))
2397 seq_puts(sf, ",sys_immutable");
2398 if (!NVolShowHiddenFiles(vol))
2399 seq_puts(sf, ",nohidden");
2400 if (NVolHideDotFiles(vol))
2401 seq_puts(sf, ",hide_dot_files");
2402 if (NVolCheckWindowsNames(vol))
2403 seq_puts(sf, ",windows_names");
2404 if (NVolDiscard(vol))
2405 seq_puts(sf, ",discard");
2406 if (NVolDisableSparse(vol))
2407 seq_puts(sf, ",disable_sparse");
2408 if (NVolNativeSymlinkRel(vol))
2409 seq_puts(sf, ",native_symlink=rel");
2410 else
2411 seq_puts(sf, ",native_symlink=raw");
2412 if (NVolSymlinkNative(vol))
2413 seq_puts(sf, ",symlink=native");
2414 else
2415 seq_puts(sf, ",symlink=wsl");
2416 if (vol->sb->s_flags & SB_POSIXACL)
2417 seq_puts(sf, ",acl");
2418 return 0;
2419 }
2420
ntfs_extend_initialized_size(struct inode * vi,const loff_t offset,const loff_t new_size)2421 int ntfs_extend_initialized_size(struct inode *vi, const loff_t offset,
2422 const loff_t new_size)
2423 {
2424 struct ntfs_inode *ni = NTFS_I(vi);
2425 loff_t old_init_size;
2426 unsigned long flags;
2427 int err;
2428
2429 read_lock_irqsave(&ni->size_lock, flags);
2430 old_init_size = ni->initialized_size;
2431 read_unlock_irqrestore(&ni->size_lock, flags);
2432
2433 if (!NInoNonResident(ni))
2434 return -EINVAL;
2435 if (old_init_size >= new_size)
2436 return 0;
2437
2438 err = ntfs_attr_map_whole_runlist(ni);
2439 if (err)
2440 return err;
2441
2442 if (!NInoCompressed(ni) && old_init_size < offset) {
2443 err = iomap_zero_range(vi, old_init_size,
2444 offset - old_init_size,
2445 NULL, &ntfs_seek_iomap_ops,
2446 &ntfs_iomap_folio_ops, NULL);
2447 if (err)
2448 return err;
2449 }
2450
2451
2452 mutex_lock(&ni->mrec_lock);
2453 err = ntfs_attr_set_initialized_size(ni, new_size);
2454 mutex_unlock(&ni->mrec_lock);
2455 if (err)
2456 truncate_setsize(vi, old_init_size);
2457 return err;
2458 }
2459
ntfs_truncate_vfs(struct inode * vi,loff_t new_size,loff_t i_size)2460 int ntfs_truncate_vfs(struct inode *vi, loff_t new_size, loff_t i_size)
2461 {
2462 struct ntfs_inode *ni = NTFS_I(vi);
2463 int err;
2464
2465 mutex_lock(&ni->mrec_lock);
2466 err = __ntfs_attr_truncate_vfs(ni, new_size, i_size);
2467 mutex_unlock(&ni->mrec_lock);
2468 if (err < 0)
2469 return err;
2470
2471 inode_set_mtime_to_ts(vi, inode_set_ctime_current(vi));
2472 return 0;
2473 }
2474
2475 /*
2476 * ntfs_inode_sync_standard_information - update standard information attribute
2477 * @vi: inode to update standard information
2478 * @m: mft record
2479 *
2480 * Return 0 on success or -errno on error.
2481 */
ntfs_inode_sync_standard_information(struct inode * vi,struct mft_record * m)2482 static int ntfs_inode_sync_standard_information(struct inode *vi, struct mft_record *m)
2483 {
2484 struct ntfs_inode *ni = NTFS_I(vi);
2485 struct ntfs_attr_search_ctx *ctx;
2486 struct standard_information *si;
2487 __le64 nt;
2488 int err = 0;
2489 bool modified = false;
2490
2491 /* Update the access times in the standard information attribute. */
2492 ctx = ntfs_attr_get_search_ctx(ni, m);
2493 if (unlikely(!ctx))
2494 return -ENOMEM;
2495 err = ntfs_attr_lookup(AT_STANDARD_INFORMATION, NULL, 0,
2496 CASE_SENSITIVE, 0, NULL, 0, ctx);
2497 if (unlikely(err)) {
2498 ntfs_attr_put_search_ctx(ctx);
2499 return err;
2500 }
2501 si = (struct standard_information *)((u8 *)ctx->attr +
2502 le16_to_cpu(ctx->attr->data.resident.value_offset));
2503 if (si->file_attributes != ni->flags) {
2504 si->file_attributes = ni->flags;
2505 modified = true;
2506 }
2507
2508 /* Update the creation times if they have changed. */
2509 nt = utc2ntfs(ni->i_crtime);
2510 if (si->creation_time != nt) {
2511 ntfs_debug("Updating creation time for inode 0x%llx: old = 0x%llx, new = 0x%llx",
2512 ni->mft_no, le64_to_cpu(si->creation_time),
2513 le64_to_cpu(nt));
2514 si->creation_time = nt;
2515 modified = true;
2516 }
2517
2518 /* Update the access times if they have changed. */
2519 nt = utc2ntfs(inode_get_mtime(vi));
2520 if (si->last_data_change_time != nt) {
2521 ntfs_debug("Updating mtime for inode 0x%llx: old = 0x%llx, new = 0x%llx",
2522 ni->mft_no, le64_to_cpu(si->last_data_change_time),
2523 le64_to_cpu(nt));
2524 si->last_data_change_time = nt;
2525 modified = true;
2526 }
2527
2528 nt = utc2ntfs(inode_get_ctime(vi));
2529 if (si->last_mft_change_time != nt) {
2530 ntfs_debug("Updating ctime for inode 0x%llx: old = 0x%llx, new = 0x%llx",
2531 ni->mft_no, le64_to_cpu(si->last_mft_change_time),
2532 le64_to_cpu(nt));
2533 si->last_mft_change_time = nt;
2534 modified = true;
2535 }
2536 nt = utc2ntfs(inode_get_atime(vi));
2537 if (si->last_access_time != nt) {
2538 ntfs_debug("Updating atime for inode 0x%llx: old = 0x%llx, new = 0x%llx",
2539 ni->mft_no,
2540 le64_to_cpu(si->last_access_time),
2541 le64_to_cpu(nt));
2542 si->last_access_time = nt;
2543 modified = true;
2544 }
2545
2546 /*
2547 * If we just modified the standard information attribute we need to
2548 * mark the mft record it is in dirty. We do this manually so that
2549 * mark_inode_dirty() is not called which would redirty the inode and
2550 * hence result in an infinite loop of trying to write the inode.
2551 * There is no need to mark the base inode nor the base mft record
2552 * dirty, since we are going to write this mft record below in any case
2553 * and the base mft record may actually not have been modified so it
2554 * might not need to be written out.
2555 * NOTE: It is not a problem when the inode for $MFT itself is being
2556 * written out as ntfs_mft_mark_dirty() will only set I_DIRTY_PAGES
2557 * on the $MFT inode and hence ntfs_write_inode() will not be
2558 * re-invoked because of it which in turn is ok since the dirtied mft
2559 * record will be cleaned and written out to disk below, i.e. before
2560 * this function returns.
2561 */
2562 if (modified)
2563 NInoSetDirty(ctx->ntfs_ino);
2564 ntfs_attr_put_search_ctx(ctx);
2565
2566 return err;
2567 }
2568
2569 /*
2570 * ntfs_inode_sync_filename - update FILE_NAME attributes
2571 * @ni: ntfs inode to update FILE_NAME attributes
2572 *
2573 * Update all FILE_NAME attributes for inode @ni in the index.
2574 *
2575 * Return 0 on success or error.
2576 */
ntfs_inode_sync_filename(struct ntfs_inode * ni)2577 int ntfs_inode_sync_filename(struct ntfs_inode *ni)
2578 {
2579 struct inode *index_vi;
2580 struct super_block *sb = VFS_I(ni)->i_sb;
2581 struct ntfs_attr_search_ctx *ctx = NULL;
2582 struct ntfs_index_context *ictx;
2583 struct ntfs_inode *index_ni;
2584 struct file_name_attr *fn;
2585 struct file_name_attr *fnx;
2586 struct reparse_point *rpp;
2587 __le32 reparse_tag;
2588 int err = 0;
2589 unsigned long flags;
2590
2591 ntfs_debug("Entering for inode %llu\n", ni->mft_no);
2592
2593 ctx = ntfs_attr_get_search_ctx(ni, NULL);
2594 if (!ctx)
2595 return -ENOMEM;
2596
2597 /* Collect the reparse tag, if any */
2598 reparse_tag = cpu_to_le32(0);
2599 if (ni->flags & FILE_ATTR_REPARSE_POINT) {
2600 if (!ntfs_attr_lookup(AT_REPARSE_POINT, NULL,
2601 0, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
2602 rpp = (struct reparse_point *)((u8 *)ctx->attr +
2603 le16_to_cpu(ctx->attr->data.resident.value_offset));
2604 reparse_tag = rpp->reparse_tag;
2605 }
2606 ntfs_attr_reinit_search_ctx(ctx);
2607 }
2608
2609 /* Walk through all FILE_NAME attributes and update them. */
2610 while (!(err = ntfs_attr_lookup(AT_FILE_NAME, NULL, 0, 0, 0, NULL, 0, ctx))) {
2611 fn = (struct file_name_attr *)((u8 *)ctx->attr +
2612 le16_to_cpu(ctx->attr->data.resident.value_offset));
2613 if (MREF_LE(fn->parent_directory) == ni->mft_no)
2614 continue;
2615
2616 index_vi = ntfs_iget(sb, MREF_LE(fn->parent_directory));
2617 if (IS_ERR(index_vi)) {
2618 ntfs_error(sb, "Failed to open inode %lld with index",
2619 (long long)MREF_LE(fn->parent_directory));
2620 continue;
2621 }
2622
2623 index_ni = NTFS_I(index_vi);
2624
2625 mutex_lock_nested(&index_ni->mrec_lock, NTFS_INODE_MUTEX_PARENT);
2626 if (NInoBeingDeleted(ni)) {
2627 mutex_unlock(&index_ni->mrec_lock);
2628 iput(index_vi);
2629 continue;
2630 }
2631
2632 ictx = ntfs_index_ctx_get(index_ni, I30, 4);
2633 if (!ictx) {
2634 ntfs_error(sb, "Failed to get index ctx, inode %llu",
2635 index_ni->mft_no);
2636 mutex_unlock(&index_ni->mrec_lock);
2637 iput(index_vi);
2638 continue;
2639 }
2640
2641 err = ntfs_index_lookup(fn, sizeof(struct file_name_attr), ictx);
2642 if (err) {
2643 ntfs_debug("Index lookup failed, inode %llu",
2644 index_ni->mft_no);
2645 ntfs_index_ctx_put(ictx);
2646 mutex_unlock(&index_ni->mrec_lock);
2647 iput(index_vi);
2648 continue;
2649 }
2650 /* Update flags and file size. */
2651 fnx = (struct file_name_attr *)ictx->data;
2652 fnx->file_attributes =
2653 (fnx->file_attributes & ~FILE_ATTR_VALID_FLAGS) |
2654 (ni->flags & FILE_ATTR_VALID_FLAGS);
2655 if (ctx->mrec->flags & MFT_RECORD_IS_DIRECTORY)
2656 fnx->data_size = fnx->allocated_size = 0;
2657 else {
2658 read_lock_irqsave(&ni->size_lock, flags);
2659 if (NInoSparse(ni) || NInoCompressed(ni))
2660 fnx->allocated_size = cpu_to_le64(ni->itype.compressed.size);
2661 else
2662 fnx->allocated_size = cpu_to_le64(ni->allocated_size);
2663 fnx->data_size = cpu_to_le64(ni->data_size);
2664
2665 /*
2666 * The file name record has also to be fixed if some
2667 * attribute update implied the unnamed data to be
2668 * made non-resident
2669 */
2670 fn->allocated_size = fnx->allocated_size;
2671 fn->data_size = fnx->data_size;
2672 read_unlock_irqrestore(&ni->size_lock, flags);
2673 }
2674
2675 /* update or clear the reparse tag in the index */
2676 fnx->type.rp.reparse_point_tag = reparse_tag;
2677 fnx->creation_time = fn->creation_time;
2678 fnx->last_data_change_time = fn->last_data_change_time;
2679 fnx->last_mft_change_time = fn->last_mft_change_time;
2680 fnx->last_access_time = fn->last_access_time;
2681 ntfs_index_entry_mark_dirty(ictx);
2682 ntfs_icx_ib_sync_write(ictx);
2683 NInoSetDirty(ctx->ntfs_ino);
2684 ntfs_index_ctx_put(ictx);
2685 mutex_unlock(&index_ni->mrec_lock);
2686 iput(index_vi);
2687 }
2688 /* Check for real error occurred. */
2689 if (err != -ENOENT) {
2690 ntfs_error(sb, "Attribute lookup failed, err : %d, inode %llu", err,
2691 ni->mft_no);
2692 } else
2693 err = 0;
2694
2695 ntfs_attr_put_search_ctx(ctx);
2696 return err;
2697 }
2698
ntfs_get_block_mft_record(struct ntfs_inode * mft_ni,struct ntfs_inode * ni)2699 int ntfs_get_block_mft_record(struct ntfs_inode *mft_ni, struct ntfs_inode *ni)
2700 {
2701 s64 vcn;
2702 struct runlist_element *rl;
2703
2704 if (ni->mft_lcn[0] != LCN_RL_NOT_MAPPED)
2705 return 0;
2706
2707 vcn = (s64)ni->mft_no << mft_ni->vol->mft_record_size_bits >>
2708 mft_ni->vol->cluster_size_bits;
2709
2710 rl = mft_ni->runlist.rl;
2711 if (!rl) {
2712 ntfs_error(mft_ni->vol->sb, "$MFT runlist is not present");
2713 return -EIO;
2714 }
2715
2716 /* Seek to element containing target vcn. */
2717 while (rl->length && rl[1].vcn <= vcn)
2718 rl++;
2719 ni->mft_lcn[0] = ntfs_rl_vcn_to_lcn(rl, vcn);
2720 ni->mft_lcn_count = 1;
2721
2722 if (mft_ni->vol->cluster_size < mft_ni->vol->mft_record_size &&
2723 (rl->length - (vcn - rl->vcn)) <= 1) {
2724 rl++;
2725 ni->mft_lcn[1] = ntfs_rl_vcn_to_lcn(rl, vcn + 1);
2726 ni->mft_lcn_count++;
2727 }
2728 return 0;
2729 }
2730
2731 /*
2732 * __ntfs_write_inode - write out a dirty inode
2733 * @vi: inode to write out
2734 * @sync: if true, write out synchronously
2735 *
2736 * Write out a dirty inode to disk including any extent inodes if present.
2737 *
2738 * If @sync is true, commit the inode to disk and wait for io completion. This
2739 * is done using write_mft_record().
2740 *
2741 * If @sync is false, just schedule the write to happen but do not wait for i/o
2742 * completion.
2743 *
2744 * Return 0 on success and -errno on error.
2745 */
__ntfs_write_inode(struct inode * vi,int sync)2746 int __ntfs_write_inode(struct inode *vi, int sync)
2747 {
2748 struct ntfs_inode *ni = NTFS_I(vi);
2749 struct ntfs_inode *mft_ni = NTFS_I(ni->vol->mft_ino);
2750 struct mft_record *m;
2751 int err = 0;
2752 bool need_iput = false;
2753
2754 ntfs_debug("Entering for %sinode 0x%llx.", NInoAttr(ni) ? "attr " : "",
2755 ni->mft_no);
2756
2757 if (NVolShutdown(ni->vol))
2758 return -EIO;
2759
2760 /*
2761 * Dirty attribute inodes are written via their real inodes so just
2762 * clean them here. Access time updates are taken care off when the
2763 * real inode is written.
2764 */
2765 if (NInoAttr(ni) || ni->nr_extents == -1) {
2766 NInoClearDirty(ni);
2767 ntfs_debug("Done.");
2768 return 0;
2769 }
2770
2771 /* igrab prevents vi from being evicted while mrec_lock is hold. */
2772 if (igrab(vi) != NULL)
2773 need_iput = true;
2774
2775 mutex_lock_nested(&ni->mrec_lock, NTFS_INODE_MUTEX_NORMAL);
2776 /* Map, pin, and lock the mft record belonging to the inode. */
2777 m = map_mft_record(ni);
2778 if (IS_ERR(m)) {
2779 mutex_unlock(&ni->mrec_lock);
2780 err = PTR_ERR(m);
2781 goto err_out;
2782 }
2783
2784 if (NInoNonResident(ni) && NInoRunlistDirty(ni)) {
2785 down_write(&ni->runlist.lock);
2786 err = ntfs_attr_update_mapping_pairs_locked(ni, 0, ni);
2787 if (!err)
2788 NInoClearRunlistDirty(ni);
2789 up_write(&ni->runlist.lock);
2790 }
2791
2792 err = ntfs_inode_sync_standard_information(vi, m);
2793 if (err)
2794 goto unm_err_out;
2795
2796 /*
2797 * when being umounted and inodes are evicted, write_inode()
2798 * is called with all inodes being marked with I_FREEING.
2799 * then ntfs_inode_sync_filename() waits infinitly because
2800 * of ntfs_iget. This situation happens only where sync_filesysem()
2801 * from umount fails because of a disk unplug and etc.
2802 * the absent of SB_ACTIVE means umounting.
2803 */
2804 if ((vi->i_sb->s_flags & SB_ACTIVE) && NInoTestClearFileNameDirty(ni))
2805 ntfs_inode_sync_filename(ni);
2806
2807 /* Now the access times are updated, write the base mft record. */
2808 if (NInoDirty(ni)) {
2809 down_read(&mft_ni->runlist.lock);
2810 err = ntfs_get_block_mft_record(mft_ni, ni);
2811 up_read(&mft_ni->runlist.lock);
2812 if (err)
2813 goto unm_err_out;
2814
2815 err = write_mft_record(ni, m, sync);
2816 if (err)
2817 ntfs_error(vi->i_sb, "write_mft_record failed, err : %d\n", err);
2818 }
2819 unmap_mft_record(ni);
2820
2821 /* Map any unmapped extent mft records with LCNs. */
2822 down_read(&mft_ni->runlist.lock);
2823 mutex_lock(&ni->extent_lock);
2824 if (ni->nr_extents > 0) {
2825 int i;
2826
2827 for (i = 0; i < ni->nr_extents; i++) {
2828 err = ntfs_get_block_mft_record(mft_ni,
2829 ni->ext.extent_ntfs_inos[i]);
2830 if (err) {
2831 mutex_unlock(&ni->extent_lock);
2832 up_read(&mft_ni->runlist.lock);
2833 mutex_unlock(&ni->mrec_lock);
2834 goto err_out;
2835 }
2836 }
2837 }
2838 mutex_unlock(&ni->extent_lock);
2839 up_read(&mft_ni->runlist.lock);
2840
2841 /* Write all attached extent mft records. */
2842 mutex_lock(&ni->extent_lock);
2843 if (ni->nr_extents > 0) {
2844 struct ntfs_inode **extent_nis = ni->ext.extent_ntfs_inos;
2845 int i;
2846
2847 ntfs_debug("Writing %i extent inodes.", ni->nr_extents);
2848 for (i = 0; i < ni->nr_extents; i++) {
2849 struct ntfs_inode *tni = extent_nis[i];
2850
2851 if (NInoDirty(tni)) {
2852 struct mft_record *tm;
2853 int ret;
2854
2855 mutex_lock(&tni->mrec_lock);
2856 tm = map_mft_record(tni);
2857 if (IS_ERR(tm)) {
2858 mutex_unlock(&tni->mrec_lock);
2859 if (!err || err == -ENOMEM)
2860 err = PTR_ERR(tm);
2861 continue;
2862 }
2863
2864 ret = write_mft_record(tni, tm, sync);
2865 unmap_mft_record(tni);
2866 mutex_unlock(&tni->mrec_lock);
2867
2868 if (unlikely(ret)) {
2869 if (!err || err == -ENOMEM)
2870 err = ret;
2871 }
2872 }
2873 }
2874 }
2875 mutex_unlock(&ni->extent_lock);
2876 mutex_unlock(&ni->mrec_lock);
2877
2878 if (unlikely(err))
2879 goto err_out;
2880 if (need_iput)
2881 iput(vi);
2882 ntfs_debug("Done.");
2883 return 0;
2884 unm_err_out:
2885 unmap_mft_record(ni);
2886 mutex_unlock(&ni->mrec_lock);
2887 err_out:
2888 if (err == -ENOMEM)
2889 mark_inode_dirty(vi);
2890 else {
2891 ntfs_error(vi->i_sb, "Failed (error %i): Run chkdsk.", -err);
2892 NVolSetErrors(ni->vol);
2893 }
2894 if (need_iput)
2895 iput(vi);
2896 return err;
2897 }
2898
2899 /*
2900 * ntfs_extent_inode_open - load an extent inode and attach it to its base
2901 * @base_ni: base ntfs inode
2902 * @mref: mft reference of the extent inode to load (in little endian)
2903 *
2904 * First check if the extent inode @mref is already attached to the base ntfs
2905 * inode @base_ni, and if so, return a pointer to the attached extent inode.
2906 *
2907 * If the extent inode is not already attached to the base inode, allocate an
2908 * ntfs_inode structure and initialize it for the given inode @mref. @mref
2909 * specifies the inode number / mft record to read, including the sequence
2910 * number, which can be 0 if no sequence number checking is to be performed.
2911 *
2912 * Then, allocate a buffer for the mft record, read the mft record from the
2913 * volume @base_ni->vol, and attach it to the ntfs_inode structure (->mrec).
2914 * The mft record is mst deprotected and sanity checked for validity and we
2915 * abort if deprotection or checks fail.
2916 *
2917 * Finally attach the ntfs inode to its base inode @base_ni and return a
2918 * pointer to the ntfs_inode structure on success or NULL on error, with errno
2919 * set to the error code.
2920 *
2921 * Note, extent inodes are never closed directly. They are automatically
2922 * disposed off by the closing of the base inode.
2923 */
ntfs_extent_inode_open(struct ntfs_inode * base_ni,const __le64 mref)2924 static struct ntfs_inode *ntfs_extent_inode_open(struct ntfs_inode *base_ni,
2925 const __le64 mref)
2926 {
2927 u64 mft_no = MREF_LE(mref);
2928 struct ntfs_inode *ni = NULL;
2929 struct ntfs_inode **extent_nis;
2930 int i;
2931 struct mft_record *ni_mrec;
2932 struct super_block *sb;
2933
2934 if (!base_ni)
2935 return NULL;
2936
2937 sb = base_ni->vol->sb;
2938 ntfs_debug("Opening extent inode %llu (base mft record %llu).\n",
2939 mft_no, base_ni->mft_no);
2940
2941 /* Is the extent inode already open and attached to the base inode? */
2942 if (base_ni->nr_extents > 0) {
2943 extent_nis = base_ni->ext.extent_ntfs_inos;
2944 for (i = 0; i < base_ni->nr_extents; i++) {
2945 u16 seq_no;
2946
2947 ni = extent_nis[i];
2948 if (mft_no != ni->mft_no)
2949 continue;
2950 ni_mrec = map_mft_record(ni);
2951 if (IS_ERR(ni_mrec)) {
2952 ntfs_error(sb, "failed to map mft record for %llu",
2953 ni->mft_no);
2954 goto out;
2955 }
2956 /* Verify the sequence number if given. */
2957 seq_no = MSEQNO_LE(mref);
2958 if (seq_no &&
2959 seq_no != le16_to_cpu(ni_mrec->sequence_number)) {
2960 ntfs_error(sb, "Found stale extent mft reference mft=%llu",
2961 ni->mft_no);
2962 unmap_mft_record(ni);
2963 goto out;
2964 }
2965 unmap_mft_record(ni);
2966 goto out;
2967 }
2968 }
2969 /* Wasn't there, we need to load the extent inode. */
2970 ni = ntfs_new_extent_inode(base_ni->vol->sb, mft_no);
2971 if (!ni)
2972 goto out;
2973
2974 ni->seq_no = (u16)MSEQNO_LE(mref);
2975 ni->nr_extents = -1;
2976 ni->ext.base_ntfs_ino = base_ni;
2977 /* Attach extent inode to base inode, reallocating memory if needed. */
2978 if (!(base_ni->nr_extents & 3)) {
2979 i = (base_ni->nr_extents + 4) * sizeof(struct ntfs_inode *);
2980
2981 extent_nis = kvzalloc(i, GFP_NOFS);
2982 if (!extent_nis)
2983 goto err_out;
2984 if (base_ni->nr_extents) {
2985 memcpy(extent_nis, base_ni->ext.extent_ntfs_inos,
2986 i - 4 * sizeof(struct ntfs_inode *));
2987 kvfree(base_ni->ext.extent_ntfs_inos);
2988 }
2989 base_ni->ext.extent_ntfs_inos = extent_nis;
2990 }
2991 base_ni->ext.extent_ntfs_inos[base_ni->nr_extents++] = ni;
2992
2993 out:
2994 ntfs_debug("\n");
2995 return ni;
2996 err_out:
2997 ntfs_destroy_ext_inode(ni);
2998 ni = NULL;
2999 goto out;
3000 }
3001
3002 /*
3003 * ntfs_inode_attach_all_extents - attach all extents for target inode
3004 * @ni: opened ntfs inode for which perform attach
3005 *
3006 * Return 0 on success and error.
3007 */
ntfs_inode_attach_all_extents(struct ntfs_inode * ni)3008 int ntfs_inode_attach_all_extents(struct ntfs_inode *ni)
3009 {
3010 struct attr_list_entry *ale;
3011 u64 prev_attached = 0;
3012
3013 if (!ni) {
3014 ntfs_debug("Invalid arguments.\n");
3015 return -EINVAL;
3016 }
3017
3018 if (NInoAttr(ni))
3019 ni = ni->ext.base_ntfs_ino;
3020
3021 ntfs_debug("Entering for inode 0x%llx.\n", ni->mft_no);
3022
3023 /* Inode haven't got attribute list, thus nothing to attach. */
3024 if (!NInoAttrList(ni))
3025 return 0;
3026
3027 if (!ni->attr_list) {
3028 ntfs_debug("Corrupt in-memory struct.\n");
3029 return -EINVAL;
3030 }
3031
3032 /* Walk through attribute list and attach all extents. */
3033 ale = (struct attr_list_entry *)ni->attr_list;
3034 while ((u8 *)ale < ni->attr_list + ni->attr_list_size) {
3035 if (ni->mft_no != MREF_LE(ale->mft_reference) &&
3036 prev_attached != MREF_LE(ale->mft_reference)) {
3037 if (!ntfs_extent_inode_open(ni, ale->mft_reference)) {
3038 ntfs_debug("Couldn't attach extent inode.\n");
3039 return -1;
3040 }
3041 prev_attached = MREF_LE(ale->mft_reference);
3042 }
3043 ale = (struct attr_list_entry *)((u8 *)ale + le16_to_cpu(ale->length));
3044 }
3045 return 0;
3046 }
3047
3048 /*
3049 * ntfs_inode_add_attrlist - add attribute list to inode and fill it
3050 * @ni: opened ntfs inode to which add attribute list
3051 *
3052 * Return 0 on success or error.
3053 */
ntfs_inode_add_attrlist(struct ntfs_inode * ni)3054 int ntfs_inode_add_attrlist(struct ntfs_inode *ni)
3055 {
3056 int err;
3057 struct ntfs_attr_search_ctx *ctx;
3058 u8 *al = NULL, *aln;
3059 int al_len = 0;
3060 struct attr_list_entry *ale = NULL;
3061 struct mft_record *ni_mrec;
3062 u32 attr_al_len;
3063 bool free_empty_extents = true;
3064
3065 if (!ni)
3066 return -EINVAL;
3067
3068 ntfs_debug("inode %llu\n", ni->mft_no);
3069
3070 if (NInoAttrList(ni) || ni->nr_extents) {
3071 ntfs_error(ni->vol->sb, "Inode already has attribute list");
3072 return -EEXIST;
3073 }
3074
3075 ni_mrec = map_mft_record(ni);
3076 if (IS_ERR(ni_mrec))
3077 return -EIO;
3078
3079 /* Form attribute list. */
3080 ctx = ntfs_attr_get_search_ctx(ni, ni_mrec);
3081 if (!ctx) {
3082 err = -ENOMEM;
3083 goto err_out;
3084 }
3085
3086 /* Walk through all attributes. */
3087 while (!(err = ntfs_attr_lookup(AT_UNUSED, NULL, 0, 0, 0, NULL, 0, ctx))) {
3088 int ale_size;
3089
3090 if (ctx->attr->type == AT_ATTRIBUTE_LIST) {
3091 err = -EIO;
3092 ntfs_error(ni->vol->sb, "Attribute list already present");
3093 goto put_err_out;
3094 }
3095
3096 ale_size = (sizeof(struct attr_list_entry) + sizeof(__le16) *
3097 ctx->attr->name_length + 7) & ~7;
3098 al_len += ale_size;
3099
3100 aln = kvrealloc(al, al_len, GFP_NOFS);
3101 if (!aln) {
3102 err = -ENOMEM;
3103 ntfs_error(ni->vol->sb, "Failed to realloc %d bytes", al_len);
3104 goto put_err_out;
3105 }
3106 ale = (struct attr_list_entry *)(aln + ((u8 *)ale - al));
3107 al = aln;
3108
3109 memset(ale, 0, ale_size);
3110
3111 /* Add attribute to attribute list. */
3112 ale->type = ctx->attr->type;
3113 ale->length = cpu_to_le16((sizeof(struct attr_list_entry) +
3114 sizeof(__le16) * ctx->attr->name_length + 7) & ~7);
3115 ale->name_length = ctx->attr->name_length;
3116 ale->name_offset = (u8 *)ale->name - (u8 *)ale;
3117 if (ctx->attr->non_resident)
3118 ale->lowest_vcn =
3119 ctx->attr->data.non_resident.lowest_vcn;
3120 else
3121 ale->lowest_vcn = 0;
3122 ale->mft_reference = MK_LE_MREF(ni->mft_no,
3123 le16_to_cpu(ni_mrec->sequence_number));
3124 ale->instance = ctx->attr->instance;
3125 memcpy(ale->name, (u8 *)ctx->attr +
3126 le16_to_cpu(ctx->attr->name_offset),
3127 ctx->attr->name_length * sizeof(__le16));
3128 ale = (struct attr_list_entry *)(al + al_len);
3129 }
3130
3131 /* Check for real error occurred. */
3132 if (err != -ENOENT) {
3133 ntfs_error(ni->vol->sb, "%s: Attribute lookup failed, inode %llu",
3134 __func__, ni->mft_no);
3135 goto put_err_out;
3136 }
3137
3138 /* Set in-memory attribute list. */
3139 ni->attr_list = al;
3140 ni->attr_list_size = al_len;
3141 NInoSetAttrList(ni);
3142
3143 attr_al_len = offsetof(struct attr_record, data.resident.reserved) + 1 +
3144 ((al_len + 7) & ~7);
3145 /* Free space if there is not enough it for $ATTRIBUTE_LIST. */
3146 if (le32_to_cpu(ni_mrec->bytes_allocated) -
3147 le32_to_cpu(ni_mrec->bytes_in_use) < attr_al_len) {
3148 if (ntfs_inode_free_space(ni, (int)attr_al_len)) {
3149 /* Failed to free space. */
3150 err = -ENOSPC;
3151 ntfs_error(ni->vol->sb, "Failed to free space for attrlist");
3152 goto rollback;
3153 }
3154 }
3155
3156 /* Add $ATTRIBUTE_LIST to mft record. */
3157 err = ntfs_resident_attr_record_add(ni, AT_ATTRIBUTE_LIST, AT_UNNAMED, 0,
3158 NULL, al_len, 0);
3159 if (err < 0) {
3160 ntfs_error(ni->vol->sb, "Couldn't add $ATTRIBUTE_LIST to MFT");
3161 goto rollback;
3162 }
3163 free_empty_extents = false;
3164
3165 err = ntfs_attrlist_update(ni);
3166 if (err < 0)
3167 goto remove_attrlist_record;
3168
3169 ntfs_attr_put_search_ctx(ctx);
3170 unmap_mft_record(ni);
3171 return 0;
3172
3173 remove_attrlist_record:
3174 /* Prevent ntfs_attr_recorm_rm from freeing attribute list. */
3175 ni->attr_list = NULL;
3176 NInoClearAttrList(ni);
3177 /* Remove $ATTRIBUTE_LIST record. */
3178 ntfs_attr_reinit_search_ctx(ctx);
3179 if (!ntfs_attr_lookup(AT_ATTRIBUTE_LIST, NULL, 0,
3180 CASE_SENSITIVE, 0, NULL, 0, ctx)) {
3181 if (ntfs_attr_record_rm(ctx))
3182 ntfs_error(ni->vol->sb, "Rollback failed to remove attrlist");
3183 else
3184 free_empty_extents = true;
3185 } else {
3186 ntfs_error(ni->vol->sb, "Rollback failed to find attrlist");
3187 }
3188
3189 /* Setup back in-memory runlist. */
3190 ni->attr_list = al;
3191 ni->attr_list_size = al_len;
3192 NInoSetAttrList(ni);
3193 rollback:
3194 /*
3195 * Scan attribute list for attributes that placed not in the base MFT
3196 * record and move them to it.
3197 */
3198 ntfs_attr_reinit_search_ctx(ctx);
3199 ale = (struct attr_list_entry *)al;
3200 while ((u8 *)ale < al + al_len) {
3201 if (MREF_LE(ale->mft_reference) != ni->mft_no) {
3202 if (!ntfs_attr_lookup(ale->type, ale->name,
3203 ale->name_length,
3204 CASE_SENSITIVE,
3205 le64_to_cpu(ale->lowest_vcn),
3206 NULL, 0, ctx)) {
3207 if (ntfs_attr_record_move_to(ctx, ni))
3208 ntfs_error(ni->vol->sb,
3209 "Rollback failed to move attribute");
3210 } else {
3211 ntfs_error(ni->vol->sb, "Rollback failed to find attr");
3212 }
3213 ntfs_attr_reinit_search_ctx(ctx);
3214 }
3215 ale = (struct attr_list_entry *)((u8 *)ale + le16_to_cpu(ale->length));
3216 }
3217
3218 /* Remove in-memory attribute list. */
3219 ni->attr_list = NULL;
3220 ni->attr_list_size = 0;
3221 NInoClearAttrList(ni);
3222 NInoClearAttrListDirty(ni);
3223 ntfs_attr_put_search_ctx(ctx);
3224 ctx = NULL;
3225 if (free_empty_extents && ntfs_inode_free_empty_extents(ni))
3226 ntfs_error(ni->vol->sb, "Rollback failed to free empty extent");
3227 goto err_out;
3228 put_err_out:
3229 ntfs_attr_put_search_ctx(ctx);
3230 err_out:
3231 kvfree(al);
3232 unmap_mft_record(ni);
3233 return err;
3234 }
3235
3236 /*
3237 * ntfs_inode_close - close an ntfs inode and free all associated memory
3238 * @ni: ntfs inode to close
3239 *
3240 * Make sure the ntfs inode @ni is clean.
3241 *
3242 * If the ntfs inode @ni is a base inode, close all associated extent inodes,
3243 * then deallocate all memory attached to it, and finally free the ntfs inode
3244 * structure itself.
3245 *
3246 * If it is an extent inode, we disconnect it from its base inode before we
3247 * destroy it.
3248 *
3249 * It is OK to pass NULL to this function, it is just noop in this case.
3250 *
3251 * Return 0 on success or error.
3252 */
ntfs_inode_close(struct ntfs_inode * ni)3253 int ntfs_inode_close(struct ntfs_inode *ni)
3254 {
3255 int err = -1;
3256 struct ntfs_inode **tmp_nis;
3257 struct ntfs_inode *base_ni;
3258 s32 i;
3259
3260 if (!ni)
3261 return 0;
3262
3263 ntfs_debug("Entering for inode %llu\n", ni->mft_no);
3264
3265 /* Is this a base inode with mapped extent inodes? */
3266 /*
3267 * If the inode is an extent inode, disconnect it from the
3268 * base inode before destroying it.
3269 */
3270 base_ni = ni->ext.base_ntfs_ino;
3271 tmp_nis = base_ni->ext.extent_ntfs_inos;
3272 if (!tmp_nis)
3273 goto out;
3274 for (i = 0; i < base_ni->nr_extents; ++i) {
3275 if (tmp_nis[i] != ni)
3276 continue;
3277 /* Found it. Disconnect. */
3278 memmove(tmp_nis + i, tmp_nis + i + 1,
3279 (base_ni->nr_extents - i - 1) *
3280 sizeof(struct ntfs_inode *));
3281 /* Buffer should be for multiple of four extents. */
3282 if ((--base_ni->nr_extents) & 3)
3283 break;
3284 /*
3285 * ElectricFence is unhappy with realloc(x,0) as free(x)
3286 * thus we explicitly separate these two cases.
3287 */
3288 if (base_ni->nr_extents) {
3289 /* Resize the memory buffer. */
3290 tmp_nis = kvrealloc(tmp_nis, base_ni->nr_extents *
3291 sizeof(struct ntfs_inode *), GFP_NOFS);
3292 /* Ignore errors, they don't really matter. */
3293 if (tmp_nis)
3294 base_ni->ext.extent_ntfs_inos = tmp_nis;
3295 } else if (tmp_nis) {
3296 kvfree(tmp_nis);
3297 base_ni->ext.extent_ntfs_inos = NULL;
3298 }
3299 break;
3300 }
3301
3302 out:
3303 if (NInoDirty(ni))
3304 ntfs_error(ni->vol->sb, "Releasing dirty inode %llu!\n",
3305 ni->mft_no);
3306 if (NInoAttrList(ni) && ni->attr_list)
3307 kvfree(ni->attr_list);
3308 ntfs_destroy_ext_inode(ni);
3309 err = 0;
3310 ntfs_debug("\n");
3311 return err;
3312 }
3313
3314 /*
3315 * ntfs_inode_free_empty_extents - free empty extent MFT records
3316 * @ni: base inode whose empty extent records should be freed
3317 *
3318 * The caller must ensure that no on-disk attribute list references an empty
3319 * extent record and must hold @ni->mrec_lock to serialize the extent array.
3320 */
ntfs_inode_free_empty_extents(struct ntfs_inode * ni)3321 int ntfs_inode_free_empty_extents(struct ntfs_inode *ni)
3322 {
3323 int err = 0, i = 0;
3324
3325 if (!ni || ni->nr_extents < 0)
3326 return -EINVAL;
3327
3328 mutex_lock(&ni->extent_lock);
3329 while (i < ni->nr_extents) {
3330 struct ntfs_inode *ext_ni = ni->ext.extent_ntfs_inos[i];
3331 struct mft_record *m;
3332 int ret;
3333
3334 m = map_mft_record(ext_ni);
3335 if (IS_ERR(m)) {
3336 if (!err)
3337 err = PTR_ERR(m);
3338 i++;
3339 continue;
3340 }
3341 if (le32_to_cpu(m->bytes_in_use) -
3342 le16_to_cpu(m->attrs_offset) != 8) {
3343 unmap_mft_record(ext_ni);
3344 i++;
3345 continue;
3346 }
3347 unmap_mft_record(ext_ni);
3348
3349 ret = ntfs_mft_record_free(ni->vol, ext_ni);
3350 if (ret) {
3351 if (!err)
3352 err = ret;
3353 i++;
3354 continue;
3355 }
3356 ntfs_inode_close(ext_ni);
3357 /* ntfs_inode_close() removed this entry from the extent array. */
3358 }
3359 mutex_unlock(&ni->extent_lock);
3360 return err;
3361 }
3362
ntfs_destroy_ext_inode(struct ntfs_inode * ni)3363 void ntfs_destroy_ext_inode(struct ntfs_inode *ni)
3364 {
3365 ntfs_debug("Entering.");
3366 if (ni == NULL)
3367 return;
3368
3369 ntfs_attr_close(ni);
3370
3371 if (NInoDirty(ni))
3372 ntfs_error(ni->vol->sb, "Releasing dirty ext inode %llu!\n",
3373 ni->mft_no);
3374 if (NInoAttrList(ni) && ni->attr_list)
3375 kvfree(ni->attr_list);
3376 kfree(ni->mrec);
3377 kmem_cache_free(ntfs_inode_cache, ni);
3378 }
3379
ntfs_inode_base(struct ntfs_inode * ni)3380 static struct ntfs_inode *ntfs_inode_base(struct ntfs_inode *ni)
3381 {
3382 if (ni->nr_extents == -1)
3383 return ni->ext.base_ntfs_ino;
3384 return ni;
3385 }
3386
ntfs_attr_position(__le32 type,struct ntfs_attr_search_ctx * ctx)3387 static int ntfs_attr_position(__le32 type, struct ntfs_attr_search_ctx *ctx)
3388 {
3389 int err;
3390
3391 err = ntfs_attr_lookup(type, NULL, 0, CASE_SENSITIVE, 0, NULL,
3392 0, ctx);
3393 if (err) {
3394 __le32 atype;
3395
3396 if (err != -ENOENT)
3397 return err;
3398
3399 atype = ctx->attr->type;
3400 if (atype == AT_END)
3401 return -ENOSPC;
3402
3403 /*
3404 * if ntfs_external_attr_lookup return -ENOENT, ctx->al_entry
3405 * could point to an attribute in an extent mft record, but
3406 * ctx->attr and ctx->ntfs_ino always points to an attibute in
3407 * a base mft record.
3408 */
3409 if (ctx->al_entry &&
3410 MREF_LE(ctx->al_entry->mft_reference) != ctx->ntfs_ino->mft_no) {
3411 ntfs_attr_reinit_search_ctx(ctx);
3412 err = ntfs_attr_lookup(atype, NULL, 0, CASE_SENSITIVE, 0, NULL,
3413 0, ctx);
3414 if (err)
3415 return err;
3416 }
3417 }
3418 return 0;
3419 }
3420
3421 /*
3422 * ntfs_inode_free_space - free space in the MFT record of inode
3423 * @ni: ntfs inode in which MFT record free space
3424 * @size: amount of space needed to free
3425 *
3426 * Return 0 on success or error.
3427 */
ntfs_inode_free_space(struct ntfs_inode * ni,int size)3428 int ntfs_inode_free_space(struct ntfs_inode *ni, int size)
3429 {
3430 struct ntfs_attr_search_ctx *ctx;
3431 int freed, err;
3432 struct mft_record *ni_mrec;
3433 struct super_block *sb;
3434
3435 if (!ni || size < 0)
3436 return -EINVAL;
3437 ntfs_debug("Entering for inode %llu, size %d\n", ni->mft_no, size);
3438
3439 sb = ni->vol->sb;
3440 ni_mrec = map_mft_record(ni);
3441 if (IS_ERR(ni_mrec))
3442 return -EIO;
3443
3444 freed = (le32_to_cpu(ni_mrec->bytes_allocated) -
3445 le32_to_cpu(ni_mrec->bytes_in_use));
3446
3447 unmap_mft_record(ni);
3448
3449 if (size <= freed)
3450 return 0;
3451
3452 ctx = ntfs_attr_get_search_ctx(ni, NULL);
3453 if (!ctx) {
3454 ntfs_error(sb, "%s, Failed to get search context", __func__);
3455 return -ENOMEM;
3456 }
3457
3458 /*
3459 * Chkdsk complain if $STANDARD_INFORMATION is not in the base MFT
3460 * record.
3461 *
3462 * $INDEX_ROOT must remain resident, but its attribute record may be moved
3463 * to an extent MFT record when the base record needs room for the list.
3464 *
3465 * Also we can't move $ATTRIBUTE_LIST from base MFT_RECORD, so position
3466 * search context on first attribute after $STANDARD_INFORMATION and
3467 * $ATTRIBUTE_LIST.
3468 *
3469 * Why we reposition instead of simply skip this attributes during
3470 * enumeration? Because in case we have got only in-memory attribute
3471 * list ntfs_attr_lookup will fail when it will try to find
3472 * $ATTRIBUTE_LIST.
3473 */
3474 err = ntfs_attr_position(AT_FILE_NAME, ctx);
3475 if (err)
3476 goto put_err_out;
3477
3478 while (1) {
3479 int record_size;
3480
3481 /*
3482 * Check whether attribute is from different MFT record. If so,
3483 * find next, because we don't need such.
3484 */
3485 while (ctx->ntfs_ino->mft_no != ni->mft_no) {
3486 retry:
3487 err = ntfs_attr_lookup(AT_UNUSED, NULL, 0, CASE_SENSITIVE,
3488 0, NULL, 0, ctx);
3489 if (err) {
3490 if (err != -ENOENT)
3491 ntfs_error(sb, "Attr lookup failed #2");
3492 else if (ctx->attr->type == AT_END)
3493 err = -ENOSPC;
3494 else
3495 err = 0;
3496
3497 if (err)
3498 goto put_err_out;
3499 }
3500 }
3501
3502 if (ntfs_inode_base(ctx->ntfs_ino)->mft_no == FILE_MFT &&
3503 ctx->attr->type == AT_DATA)
3504 goto retry;
3505
3506 record_size = le32_to_cpu(ctx->attr->length);
3507
3508 /* Move away attribute. */
3509 err = ntfs_attr_record_move_away(ctx, 0);
3510 if (err) {
3511 ntfs_error(sb, "Failed to move out attribute #2");
3512 break;
3513 }
3514 freed += record_size;
3515
3516 /* Check whether we done. */
3517 if (size <= freed) {
3518 ntfs_attr_put_search_ctx(ctx);
3519 return 0;
3520 }
3521
3522 /*
3523 * Reposition to first attribute after $STANDARD_INFORMATION and
3524 * $ATTRIBUTE_LIST (see comments upwards).
3525 */
3526 ntfs_attr_reinit_search_ctx(ctx);
3527 err = ntfs_attr_position(AT_FILE_NAME, ctx);
3528 if (err)
3529 break;
3530 }
3531 put_err_out:
3532 ntfs_attr_put_search_ctx(ctx);
3533 if (err == -ENOSPC)
3534 ntfs_debug("No attributes left that can be moved out.\n");
3535 return err;
3536 }
3537
ntfs_inode_attr_pread(struct inode * vi,s64 pos,s64 count,u8 * buf)3538 s64 ntfs_inode_attr_pread(struct inode *vi, s64 pos, s64 count, u8 *buf)
3539 {
3540 struct address_space *mapping = vi->i_mapping;
3541 struct folio *folio;
3542 struct ntfs_inode *ni = NTFS_I(vi);
3543 s64 isize;
3544 u32 attr_len, total = 0, offset;
3545 pgoff_t index;
3546 int err = 0;
3547
3548 WARN_ON(!NInoAttr(ni));
3549 if (!count)
3550 return 0;
3551
3552 mutex_lock(&ni->mrec_lock);
3553 isize = i_size_read(vi);
3554 if (pos > isize) {
3555 mutex_unlock(&ni->mrec_lock);
3556 return -EINVAL;
3557 }
3558 if (pos + count > isize)
3559 count = isize - pos;
3560
3561 if (!NInoNonResident(ni)) {
3562 struct ntfs_attr_search_ctx *ctx;
3563 u8 *attr;
3564
3565 ctx = ntfs_attr_get_search_ctx(ni->ext.base_ntfs_ino, NULL);
3566 if (!ctx) {
3567 ntfs_error(vi->i_sb, "Failed to get attr search ctx");
3568 err = -ENOMEM;
3569 mutex_unlock(&ni->mrec_lock);
3570 goto out;
3571 }
3572
3573 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len, CASE_SENSITIVE,
3574 0, NULL, 0, ctx);
3575 if (err) {
3576 ntfs_error(vi->i_sb, "Failed to look up attr %#x", ni->type);
3577 ntfs_attr_put_search_ctx(ctx);
3578 mutex_unlock(&ni->mrec_lock);
3579 goto out;
3580 }
3581
3582 attr = (u8 *)ctx->attr + le16_to_cpu(ctx->attr->data.resident.value_offset);
3583 memcpy(buf, (u8 *)attr + pos, count);
3584 ntfs_attr_put_search_ctx(ctx);
3585 mutex_unlock(&ni->mrec_lock);
3586 return count;
3587 }
3588 mutex_unlock(&ni->mrec_lock);
3589
3590 index = pos >> PAGE_SHIFT;
3591 do {
3592 /* Update @index and get the next folio. */
3593 folio = read_mapping_folio(mapping, index, NULL);
3594 if (IS_ERR(folio))
3595 break;
3596
3597 offset = offset_in_folio(folio, pos);
3598 attr_len = min_t(size_t, (size_t)count, folio_size(folio) - offset);
3599
3600 folio_lock(folio);
3601 memcpy_from_folio(buf, folio, offset, attr_len);
3602 folio_unlock(folio);
3603 folio_put(folio);
3604
3605 total += attr_len;
3606 buf += attr_len;
3607 pos += attr_len;
3608 count -= attr_len;
3609 index++;
3610 } while (count);
3611 out:
3612 return err ? (s64)err : total;
3613 }
3614
ntfs_enlarge_attribute(struct inode * vi,s64 pos,s64 count,struct ntfs_attr_search_ctx * ctx)3615 static inline int ntfs_enlarge_attribute(struct inode *vi, s64 pos, s64 count,
3616 struct ntfs_attr_search_ctx *ctx)
3617 {
3618 struct ntfs_inode *ni = NTFS_I(vi);
3619 struct super_block *sb = vi->i_sb;
3620 int ret;
3621
3622 if (pos + count <= ni->initialized_size)
3623 return 0;
3624
3625 if (NInoEncrypted(ni) && NInoNonResident(ni))
3626 return -EACCES;
3627
3628 if (NInoCompressed(ni))
3629 return -EOPNOTSUPP;
3630
3631 if (pos + count > ni->data_size) {
3632 if (ntfs_attr_truncate(ni, pos + count)) {
3633 ntfs_debug("Failed to truncate attribute");
3634 return -1;
3635 }
3636
3637 ntfs_attr_reinit_search_ctx(ctx);
3638 ret = ntfs_attr_lookup(ni->type,
3639 ni->name, ni->name_len, CASE_SENSITIVE,
3640 0, NULL, 0, ctx);
3641 if (ret) {
3642 ntfs_error(sb, "Failed to look up attr %#x", ni->type);
3643 return ret;
3644 }
3645 }
3646
3647 if (!NInoNonResident(ni)) {
3648 if (likely(i_size_read(vi) < ni->data_size))
3649 i_size_write(vi, ni->data_size);
3650 return 0;
3651 }
3652
3653 if (pos + count > ni->initialized_size) {
3654 ctx->attr->data.non_resident.initialized_size = cpu_to_le64(pos + count);
3655 mark_mft_record_dirty(ctx->ntfs_ino);
3656 ni->initialized_size = pos + count;
3657 if (i_size_read(vi) < ni->initialized_size)
3658 i_size_write(vi, ni->initialized_size);
3659 }
3660 return 0;
3661 }
3662
__ntfs_inode_resident_attr_pwrite(struct inode * vi,s64 pos,s64 count,u8 * buf,struct ntfs_attr_search_ctx * ctx)3663 static s64 __ntfs_inode_resident_attr_pwrite(struct inode *vi,
3664 s64 pos, s64 count, u8 *buf,
3665 struct ntfs_attr_search_ctx *ctx)
3666 {
3667 struct ntfs_inode *ni = NTFS_I(vi);
3668 struct folio *folio;
3669 struct address_space *mapping = vi->i_mapping;
3670 u8 *addr;
3671 int err = 0;
3672
3673 WARN_ON(NInoNonResident(ni));
3674 if (pos + count > PAGE_SIZE) {
3675 ntfs_error(vi->i_sb, "Out of write into resident attr %#x", ni->type);
3676 return -EINVAL;
3677 }
3678
3679 /* Copy to mft record page */
3680 addr = (u8 *)ctx->attr + le16_to_cpu(ctx->attr->data.resident.value_offset);
3681 memcpy(addr + pos, buf, count);
3682 mark_mft_record_dirty(ctx->ntfs_ino);
3683
3684 /* Keep the first page clean and uptodate */
3685 folio = __filemap_get_folio(mapping, 0, FGP_WRITEBEGIN | FGP_NOFS,
3686 mapping_gfp_mask(mapping));
3687 if (IS_ERR(folio)) {
3688 err = PTR_ERR(folio);
3689 ntfs_error(vi->i_sb, "Failed to read a page 0 for attr %#x: %d",
3690 ni->type, err);
3691 goto out;
3692 }
3693 if (!folio_test_uptodate(folio))
3694 folio_fill_tail(folio, 0, addr,
3695 le32_to_cpu(ctx->attr->data.resident.value_length));
3696 else
3697 memcpy_to_folio(folio, offset_in_folio(folio, pos), buf, count);
3698 folio_mark_uptodate(folio);
3699 folio_unlock(folio);
3700 folio_put(folio);
3701 out:
3702 return err ? err : count;
3703 }
3704
__ntfs_inode_non_resident_attr_pwrite(struct inode * vi,s64 pos,s64 count,u8 * buf,struct ntfs_attr_search_ctx * ctx,bool sync)3705 static s64 __ntfs_inode_non_resident_attr_pwrite(struct inode *vi,
3706 s64 pos, s64 count, u8 *buf,
3707 struct ntfs_attr_search_ctx *ctx,
3708 bool sync)
3709 {
3710 struct ntfs_inode *ni = NTFS_I(vi);
3711 struct address_space *mapping = vi->i_mapping;
3712 struct folio *folio;
3713 pgoff_t index;
3714 unsigned long offset, length;
3715 size_t attr_len;
3716 s64 ret = 0, written = 0;
3717
3718 WARN_ON(!NInoNonResident(ni));
3719
3720 index = pos >> PAGE_SHIFT;
3721 while (count) {
3722 if (count == PAGE_SIZE) {
3723 folio = __filemap_get_folio(vi->i_mapping, index,
3724 FGP_CREAT | FGP_LOCK,
3725 mapping_gfp_mask(mapping));
3726 if (IS_ERR(folio)) {
3727 ret = PTR_ERR(folio);
3728 break;
3729 }
3730 } else {
3731 folio = read_mapping_folio(mapping, index, NULL);
3732 if (IS_ERR(folio)) {
3733 ret = PTR_ERR(folio);
3734 ntfs_error(vi->i_sb, "Failed to read a page %lu for attr %#x: %ld",
3735 index, ni->type, PTR_ERR(folio));
3736 break;
3737 }
3738
3739 folio_lock(folio);
3740 }
3741
3742 if (count == PAGE_SIZE) {
3743 offset = 0;
3744 attr_len = count;
3745 } else {
3746 offset = offset_in_folio(folio, pos);
3747 attr_len = min_t(size_t, (size_t)count, folio_size(folio) - offset);
3748 }
3749 memcpy_to_folio(folio, offset, buf, attr_len);
3750
3751 if (sync) {
3752 struct ntfs_volume *vol = ni->vol;
3753 s64 lcn, lcn_count;
3754 unsigned int lcn_folio_off = 0;
3755 struct bio *bio;
3756 u64 rl_length = 0;
3757 s64 vcn;
3758 struct runlist_element *rl;
3759 int bio_err;
3760
3761 lcn_count = max_t(s64, 1, ntfs_bytes_to_cluster(vol, attr_len));
3762 vcn = ntfs_pidx_to_cluster(vol, folio->index);
3763
3764 do {
3765 down_write(&ni->runlist.lock);
3766 rl = ntfs_attr_vcn_to_rl(ni, vcn, &lcn);
3767 if (IS_ERR(rl)) {
3768 ret = PTR_ERR(rl);
3769 up_write(&ni->runlist.lock);
3770 goto err_unlock_folio;
3771 }
3772
3773 rl_length = rl->length - (vcn - rl->vcn);
3774 if (rl_length < lcn_count) {
3775 lcn_count -= rl_length;
3776 } else {
3777 rl_length = lcn_count;
3778 lcn_count = 0;
3779 }
3780 up_write(&ni->runlist.lock);
3781
3782 if (vol->cluster_size_bits > PAGE_SHIFT) {
3783 lcn_folio_off = folio->index << PAGE_SHIFT;
3784 lcn_folio_off &= vol->cluster_size_mask;
3785 }
3786
3787 bio = bio_alloc(vol->sb->s_bdev, 1, REQ_OP_WRITE,
3788 GFP_NOIO);
3789 bio->bi_iter.bi_sector =
3790 ntfs_bytes_to_bio_sector(ntfs_cluster_to_bytes(vol, lcn) +
3791 lcn_folio_off);
3792
3793 length = min_t(unsigned long,
3794 ntfs_cluster_to_bytes(vol, rl_length),
3795 folio_size(folio));
3796 if (!bio_add_folio(bio, folio, length, offset)) {
3797 ret = -EIO;
3798 bio_put(bio);
3799 goto err_unlock_folio;
3800 }
3801
3802 bio_err = submit_bio_wait(bio);
3803 bio_put(bio);
3804 if (bio_err) {
3805 ntfs_error(vi->i_sb,
3806 "Synchronous attribute write failed (%d)",
3807 bio_err);
3808 ret = bio_err;
3809 goto err_unlock_folio;
3810 }
3811 vcn += rl_length;
3812 offset += length;
3813 } while (lcn_count != 0);
3814
3815 folio_mark_uptodate(folio);
3816 } else {
3817 folio_mark_uptodate(folio);
3818 folio_mark_dirty(folio);
3819 }
3820 err_unlock_folio:
3821 folio_unlock(folio);
3822 folio_put(folio);
3823
3824 if (ret)
3825 break;
3826
3827 written += attr_len;
3828 buf += attr_len;
3829 pos += attr_len;
3830 count -= attr_len;
3831 index++;
3832
3833 cond_resched();
3834 }
3835
3836 return ret ? ret : written;
3837 }
3838
ntfs_inode_attr_pwrite(struct inode * vi,s64 pos,s64 count,u8 * buf,bool sync)3839 s64 ntfs_inode_attr_pwrite(struct inode *vi, s64 pos, s64 count, u8 *buf, bool sync)
3840 {
3841 struct ntfs_inode *ni = NTFS_I(vi);
3842 struct ntfs_attr_search_ctx *ctx;
3843 s64 ret;
3844
3845 WARN_ON(!NInoAttr(ni));
3846
3847 ctx = ntfs_attr_get_search_ctx(ni->ext.base_ntfs_ino, NULL);
3848 if (!ctx) {
3849 ntfs_error(vi->i_sb, "Failed to get attr search ctx");
3850 return -ENOMEM;
3851 }
3852
3853 ret = ntfs_attr_lookup(ni->type, ni->name, ni->name_len, CASE_SENSITIVE,
3854 0, NULL, 0, ctx);
3855 if (ret) {
3856 ntfs_attr_put_search_ctx(ctx);
3857 ntfs_error(vi->i_sb, "Failed to look up attr %#x", ni->type);
3858 return ret;
3859 }
3860
3861 mutex_lock(&ni->mrec_lock);
3862 ret = ntfs_enlarge_attribute(vi, pos, count, ctx);
3863 mutex_unlock(&ni->mrec_lock);
3864 if (ret)
3865 goto out;
3866
3867 if (NInoNonResident(ni))
3868 ret = __ntfs_inode_non_resident_attr_pwrite(vi, pos, count, buf, ctx, sync);
3869 else
3870 ret = __ntfs_inode_resident_attr_pwrite(vi, pos, count, buf, ctx);
3871 out:
3872 ntfs_attr_put_search_ctx(ctx);
3873 return ret;
3874 }
3875
ntfs_get_locked_folio(struct address_space * mapping,pgoff_t index,pgoff_t end_index,struct file_ra_state * ra)3876 struct folio *ntfs_get_locked_folio(struct address_space *mapping,
3877 pgoff_t index, pgoff_t end_index, struct file_ra_state *ra)
3878 {
3879 struct folio *folio;
3880
3881 folio = filemap_lock_folio(mapping, index);
3882 if (IS_ERR(folio)) {
3883 if (PTR_ERR(folio) != -ENOENT)
3884 return folio;
3885
3886 page_cache_sync_readahead(mapping, ra, NULL, index,
3887 end_index - index);
3888 folio = read_mapping_folio(mapping, index, NULL);
3889 if (!IS_ERR(folio))
3890 folio_lock(folio);
3891 }
3892
3893 return folio;
3894 }
3895