]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blame - fs/ntfs/aops.c
NTFS: Fix a bug in fs/ntfs/runlist.c::ntfs_mapping_pairs_decompress() in
[mirror_ubuntu-artful-kernel.git] / fs / ntfs / aops.c
CommitLineData
1da177e4
LT
1/**
2 * aops.c - NTFS kernel address space operations and page cache handling.
3 * Part of the Linux-NTFS project.
4 *
5 * Copyright (c) 2001-2004 Anton Altaparmakov
6 * Copyright (c) 2002 Richard Russon
7 *
8 * This program/include file is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License as published
10 * by the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program/include file is distributed in the hope that it will be
14 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
15 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program (in the main directory of the Linux-NTFS
20 * distribution in the file COPYING); if not, write to the Free Software
21 * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 */
23
24#include <linux/errno.h>
25#include <linux/mm.h>
26#include <linux/pagemap.h>
27#include <linux/swap.h>
28#include <linux/buffer_head.h>
29#include <linux/writeback.h>
30
31#include "aops.h"
32#include "attrib.h"
33#include "debug.h"
34#include "inode.h"
35#include "mft.h"
36#include "runlist.h"
37#include "types.h"
38#include "ntfs.h"
39
40/**
41 * ntfs_end_buffer_async_read - async io completion for reading attributes
42 * @bh: buffer head on which io is completed
43 * @uptodate: whether @bh is now uptodate or not
44 *
45 * Asynchronous I/O completion handler for reading pages belonging to the
46 * attribute address space of an inode. The inodes can either be files or
47 * directories or they can be fake inodes describing some attribute.
48 *
49 * If NInoMstProtected(), perform the post read mst fixups when all IO on the
50 * page has been completed and mark the page uptodate or set the error bit on
51 * the page. To determine the size of the records that need fixing up, we
52 * cheat a little bit by setting the index_block_size in ntfs_inode to the ntfs
53 * record size, and index_block_size_bits, to the log(base 2) of the ntfs
54 * record size.
55 */
56static void ntfs_end_buffer_async_read(struct buffer_head *bh, int uptodate)
57{
58 static DEFINE_SPINLOCK(page_uptodate_lock);
59 unsigned long flags;
60 struct buffer_head *tmp;
61 struct page *page;
62 ntfs_inode *ni;
63 int page_uptodate = 1;
64
65 page = bh->b_page;
66 ni = NTFS_I(page->mapping->host);
67
68 if (likely(uptodate)) {
07a4e2da 69 s64 file_ofs, initialized_size;
1da177e4
LT
70
71 set_buffer_uptodate(bh);
72
73 file_ofs = ((s64)page->index << PAGE_CACHE_SHIFT) +
74 bh_offset(bh);
07a4e2da
AA
75 read_lock_irqsave(&ni->size_lock, flags);
76 initialized_size = ni->initialized_size;
77 read_unlock_irqrestore(&ni->size_lock, flags);
1da177e4 78 /* Check for the current buffer head overflowing. */
07a4e2da 79 if (file_ofs + bh->b_size > initialized_size) {
1da177e4
LT
80 char *addr;
81 int ofs = 0;
82
07a4e2da
AA
83 if (file_ofs < initialized_size)
84 ofs = initialized_size - file_ofs;
1da177e4
LT
85 addr = kmap_atomic(page, KM_BIO_SRC_IRQ);
86 memset(addr + bh_offset(bh) + ofs, 0, bh->b_size - ofs);
87 flush_dcache_page(page);
88 kunmap_atomic(addr, KM_BIO_SRC_IRQ);
89 }
90 } else {
91 clear_buffer_uptodate(bh);
92 ntfs_error(ni->vol->sb, "Buffer I/O error, logical block %llu.",
93 (unsigned long long)bh->b_blocknr);
94 SetPageError(page);
95 }
96 spin_lock_irqsave(&page_uptodate_lock, flags);
97 clear_buffer_async_read(bh);
98 unlock_buffer(bh);
99 tmp = bh;
100 do {
101 if (!buffer_uptodate(tmp))
102 page_uptodate = 0;
103 if (buffer_async_read(tmp)) {
104 if (likely(buffer_locked(tmp)))
105 goto still_busy;
106 /* Async buffers must be locked. */
107 BUG();
108 }
109 tmp = tmp->b_this_page;
110 } while (tmp != bh);
111 spin_unlock_irqrestore(&page_uptodate_lock, flags);
112 /*
113 * If none of the buffers had errors then we can set the page uptodate,
114 * but we first have to perform the post read mst fixups, if the
115 * attribute is mst protected, i.e. if NInoMstProteced(ni) is true.
116 * Note we ignore fixup errors as those are detected when
117 * map_mft_record() is called which gives us per record granularity
118 * rather than per page granularity.
119 */
120 if (!NInoMstProtected(ni)) {
121 if (likely(page_uptodate && !PageError(page)))
122 SetPageUptodate(page);
123 } else {
124 char *addr;
125 unsigned int i, recs;
126 u32 rec_size;
127
128 rec_size = ni->itype.index.block_size;
129 recs = PAGE_CACHE_SIZE / rec_size;
130 /* Should have been verified before we got here... */
131 BUG_ON(!recs);
132 addr = kmap_atomic(page, KM_BIO_SRC_IRQ);
133 for (i = 0; i < recs; i++)
134 post_read_mst_fixup((NTFS_RECORD*)(addr +
135 i * rec_size), rec_size);
136 flush_dcache_page(page);
137 kunmap_atomic(addr, KM_BIO_SRC_IRQ);
138 if (likely(!PageError(page) && page_uptodate))
139 SetPageUptodate(page);
140 }
141 unlock_page(page);
142 return;
143still_busy:
144 spin_unlock_irqrestore(&page_uptodate_lock, flags);
145 return;
146}
147
148/**
149 * ntfs_read_block - fill a @page of an address space with data
150 * @page: page cache page to fill with data
151 *
152 * Fill the page @page of the address space belonging to the @page->host inode.
153 * We read each buffer asynchronously and when all buffers are read in, our io
154 * completion handler ntfs_end_buffer_read_async(), if required, automatically
155 * applies the mst fixups to the page before finally marking it uptodate and
156 * unlocking it.
157 *
158 * We only enforce allocated_size limit because i_size is checked for in
159 * generic_file_read().
160 *
161 * Return 0 on success and -errno on error.
162 *
163 * Contains an adapted version of fs/buffer.c::block_read_full_page().
164 */
165static int ntfs_read_block(struct page *page)
166{
167 VCN vcn;
168 LCN lcn;
169 ntfs_inode *ni;
170 ntfs_volume *vol;
171 runlist_element *rl;
172 struct buffer_head *bh, *head, *arr[MAX_BUF_PER_PAGE];
173 sector_t iblock, lblock, zblock;
07a4e2da 174 unsigned long flags;
1da177e4
LT
175 unsigned int blocksize, vcn_ofs;
176 int i, nr;
177 unsigned char blocksize_bits;
178
179 ni = NTFS_I(page->mapping->host);
180 vol = ni->vol;
181
182 /* $MFT/$DATA must have its complete runlist in memory at all times. */
183 BUG_ON(!ni->runlist.rl && !ni->mft_no && !NInoAttr(ni));
184
185 blocksize_bits = VFS_I(ni)->i_blkbits;
186 blocksize = 1 << blocksize_bits;
187
188 if (!page_has_buffers(page))
189 create_empty_buffers(page, blocksize, 0);
190 bh = head = page_buffers(page);
191 if (unlikely(!bh)) {
192 unlock_page(page);
193 return -ENOMEM;
194 }
195
196 iblock = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
07a4e2da 197 read_lock_irqsave(&ni->size_lock, flags);
1da177e4
LT
198 lblock = (ni->allocated_size + blocksize - 1) >> blocksize_bits;
199 zblock = (ni->initialized_size + blocksize - 1) >> blocksize_bits;
07a4e2da 200 read_unlock_irqrestore(&ni->size_lock, flags);
1da177e4
LT
201
202 /* Loop through all the buffers in the page. */
203 rl = NULL;
204 nr = i = 0;
205 do {
206 u8 *kaddr;
207
208 if (unlikely(buffer_uptodate(bh)))
209 continue;
210 if (unlikely(buffer_mapped(bh))) {
211 arr[nr++] = bh;
212 continue;
213 }
214 bh->b_bdev = vol->sb->s_bdev;
215 /* Is the block within the allowed limits? */
216 if (iblock < lblock) {
217 BOOL is_retry = FALSE;
218
219 /* Convert iblock into corresponding vcn and offset. */
220 vcn = (VCN)iblock << blocksize_bits >>
221 vol->cluster_size_bits;
222 vcn_ofs = ((VCN)iblock << blocksize_bits) &
223 vol->cluster_size_mask;
224 if (!rl) {
225lock_retry_remap:
226 down_read(&ni->runlist.lock);
227 rl = ni->runlist.rl;
228 }
229 if (likely(rl != NULL)) {
230 /* Seek to element containing target vcn. */
231 while (rl->length && rl[1].vcn <= vcn)
232 rl++;
233 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
234 } else
235 lcn = LCN_RL_NOT_MAPPED;
236 /* Successful remap. */
237 if (lcn >= 0) {
238 /* Setup buffer head to correct block. */
239 bh->b_blocknr = ((lcn << vol->cluster_size_bits)
240 + vcn_ofs) >> blocksize_bits;
241 set_buffer_mapped(bh);
242 /* Only read initialized data blocks. */
243 if (iblock < zblock) {
244 arr[nr++] = bh;
245 continue;
246 }
247 /* Fully non-initialized data block, zero it. */
248 goto handle_zblock;
249 }
250 /* It is a hole, need to zero it. */
251 if (lcn == LCN_HOLE)
252 goto handle_hole;
253 /* If first try and runlist unmapped, map and retry. */
254 if (!is_retry && lcn == LCN_RL_NOT_MAPPED) {
255 int err;
256 is_retry = TRUE;
257 /*
258 * Attempt to map runlist, dropping lock for
259 * the duration.
260 */
261 up_read(&ni->runlist.lock);
262 err = ntfs_map_runlist(ni, vcn);
263 if (likely(!err))
264 goto lock_retry_remap;
265 rl = NULL;
266 lcn = err;
267 }
268 /* Hard error, zero out region. */
269 bh->b_blocknr = -1;
270 SetPageError(page);
271 ntfs_error(vol->sb, "Failed to read from inode 0x%lx, "
272 "attribute type 0x%x, vcn 0x%llx, "
273 "offset 0x%x because its location on "
274 "disk could not be determined%s "
275 "(error code %lli).", ni->mft_no,
276 ni->type, (unsigned long long)vcn,
277 vcn_ofs, is_retry ? " even after "
278 "retrying" : "", (long long)lcn);
279 }
280 /*
281 * Either iblock was outside lblock limits or
282 * ntfs_rl_vcn_to_lcn() returned error. Just zero that portion
283 * of the page and set the buffer uptodate.
284 */
285handle_hole:
286 bh->b_blocknr = -1UL;
287 clear_buffer_mapped(bh);
288handle_zblock:
289 kaddr = kmap_atomic(page, KM_USER0);
290 memset(kaddr + i * blocksize, 0, blocksize);
291 flush_dcache_page(page);
292 kunmap_atomic(kaddr, KM_USER0);
293 set_buffer_uptodate(bh);
294 } while (i++, iblock++, (bh = bh->b_this_page) != head);
295
296 /* Release the lock if we took it. */
297 if (rl)
298 up_read(&ni->runlist.lock);
299
300 /* Check we have at least one buffer ready for i/o. */
301 if (nr) {
302 struct buffer_head *tbh;
303
304 /* Lock the buffers. */
305 for (i = 0; i < nr; i++) {
306 tbh = arr[i];
307 lock_buffer(tbh);
308 tbh->b_end_io = ntfs_end_buffer_async_read;
309 set_buffer_async_read(tbh);
310 }
311 /* Finally, start i/o on the buffers. */
312 for (i = 0; i < nr; i++) {
313 tbh = arr[i];
314 if (likely(!buffer_uptodate(tbh)))
315 submit_bh(READ, tbh);
316 else
317 ntfs_end_buffer_async_read(tbh, 1);
318 }
319 return 0;
320 }
321 /* No i/o was scheduled on any of the buffers. */
322 if (likely(!PageError(page)))
323 SetPageUptodate(page);
324 else /* Signal synchronous i/o error. */
325 nr = -EIO;
326 unlock_page(page);
327 return nr;
328}
329
330/**
331 * ntfs_readpage - fill a @page of a @file with data from the device
332 * @file: open file to which the page @page belongs or NULL
333 * @page: page cache page to fill with data
334 *
335 * For non-resident attributes, ntfs_readpage() fills the @page of the open
336 * file @file by calling the ntfs version of the generic block_read_full_page()
337 * function, ntfs_read_block(), which in turn creates and reads in the buffers
338 * associated with the page asynchronously.
339 *
340 * For resident attributes, OTOH, ntfs_readpage() fills @page by copying the
341 * data from the mft record (which at this stage is most likely in memory) and
342 * fills the remainder with zeroes. Thus, in this case, I/O is synchronous, as
343 * even if the mft record is not cached at this point in time, we need to wait
344 * for it to be read in before we can do the copy.
345 *
346 * Return 0 on success and -errno on error.
347 */
348static int ntfs_readpage(struct file *file, struct page *page)
349{
350 loff_t i_size;
351 ntfs_inode *ni, *base_ni;
352 u8 *kaddr;
353 ntfs_attr_search_ctx *ctx;
354 MFT_RECORD *mrec;
355 u32 attr_len;
356 int err = 0;
357
358 BUG_ON(!PageLocked(page));
359 /*
360 * This can potentially happen because we clear PageUptodate() during
361 * ntfs_writepage() of MstProtected() attributes.
362 */
363 if (PageUptodate(page)) {
364 unlock_page(page);
365 return 0;
366 }
367 ni = NTFS_I(page->mapping->host);
368
369 /* NInoNonResident() == NInoIndexAllocPresent() */
370 if (NInoNonResident(ni)) {
371 /*
372 * Only unnamed $DATA attributes can be compressed or
373 * encrypted.
374 */
375 if (ni->type == AT_DATA && !ni->name_len) {
376 /* If file is encrypted, deny access, just like NT4. */
377 if (NInoEncrypted(ni)) {
378 err = -EACCES;
379 goto err_out;
380 }
381 /* Compressed data streams are handled in compress.c. */
382 if (NInoCompressed(ni))
383 return ntfs_read_compressed_block(page);
384 }
385 /* Normal data stream. */
386 return ntfs_read_block(page);
387 }
388 /*
389 * Attribute is resident, implying it is not compressed or encrypted.
390 * This also means the attribute is smaller than an mft record and
391 * hence smaller than a page, so can simply zero out any pages with
392 * index above 0. We can also do this if the file size is 0.
393 */
394 if (unlikely(page->index > 0 || !i_size_read(VFS_I(ni)))) {
395 kaddr = kmap_atomic(page, KM_USER0);
396 memset(kaddr, 0, PAGE_CACHE_SIZE);
397 flush_dcache_page(page);
398 kunmap_atomic(kaddr, KM_USER0);
399 goto done;
400 }
401 if (!NInoAttr(ni))
402 base_ni = ni;
403 else
404 base_ni = ni->ext.base_ntfs_ino;
405 /* Map, pin, and lock the mft record. */
406 mrec = map_mft_record(base_ni);
407 if (IS_ERR(mrec)) {
408 err = PTR_ERR(mrec);
409 goto err_out;
410 }
411 ctx = ntfs_attr_get_search_ctx(base_ni, mrec);
412 if (unlikely(!ctx)) {
413 err = -ENOMEM;
414 goto unm_err_out;
415 }
416 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
417 CASE_SENSITIVE, 0, NULL, 0, ctx);
418 if (unlikely(err))
419 goto put_unm_err_out;
420 attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
421 i_size = i_size_read(VFS_I(ni));
422 if (unlikely(attr_len > i_size))
423 attr_len = i_size;
424 kaddr = kmap_atomic(page, KM_USER0);
425 /* Copy the data to the page. */
426 memcpy(kaddr, (u8*)ctx->attr +
427 le16_to_cpu(ctx->attr->data.resident.value_offset),
428 attr_len);
429 /* Zero the remainder of the page. */
430 memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
431 flush_dcache_page(page);
432 kunmap_atomic(kaddr, KM_USER0);
433put_unm_err_out:
434 ntfs_attr_put_search_ctx(ctx);
435unm_err_out:
436 unmap_mft_record(base_ni);
437done:
438 SetPageUptodate(page);
439err_out:
440 unlock_page(page);
441 return err;
442}
443
444#ifdef NTFS_RW
445
446/**
447 * ntfs_write_block - write a @page to the backing store
448 * @page: page cache page to write out
449 * @wbc: writeback control structure
450 *
451 * This function is for writing pages belonging to non-resident, non-mst
452 * protected attributes to their backing store.
453 *
454 * For a page with buffers, map and write the dirty buffers asynchronously
455 * under page writeback. For a page without buffers, create buffers for the
456 * page, then proceed as above.
457 *
458 * If a page doesn't have buffers the page dirty state is definitive. If a page
459 * does have buffers, the page dirty state is just a hint, and the buffer dirty
460 * state is definitive. (A hint which has rules: dirty buffers against a clean
461 * page is illegal. Other combinations are legal and need to be handled. In
462 * particular a dirty page containing clean buffers for example.)
463 *
464 * Return 0 on success and -errno on error.
465 *
466 * Based on ntfs_read_block() and __block_write_full_page().
467 */
468static int ntfs_write_block(struct page *page, struct writeback_control *wbc)
469{
470 VCN vcn;
471 LCN lcn;
07a4e2da
AA
472 s64 initialized_size;
473 loff_t i_size;
1da177e4
LT
474 sector_t block, dblock, iblock;
475 struct inode *vi;
476 ntfs_inode *ni;
477 ntfs_volume *vol;
478 runlist_element *rl;
479 struct buffer_head *bh, *head;
07a4e2da 480 unsigned long flags;
1da177e4
LT
481 unsigned int blocksize, vcn_ofs;
482 int err;
483 BOOL need_end_writeback;
484 unsigned char blocksize_bits;
485
486 vi = page->mapping->host;
487 ni = NTFS_I(vi);
488 vol = ni->vol;
489
490 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
491 "0x%lx.", ni->mft_no, ni->type, page->index);
492
493 BUG_ON(!NInoNonResident(ni));
494 BUG_ON(NInoMstProtected(ni));
495
496 blocksize_bits = vi->i_blkbits;
497 blocksize = 1 << blocksize_bits;
498
499 if (!page_has_buffers(page)) {
500 BUG_ON(!PageUptodate(page));
501 create_empty_buffers(page, blocksize,
502 (1 << BH_Uptodate) | (1 << BH_Dirty));
503 }
504 bh = head = page_buffers(page);
505 if (unlikely(!bh)) {
506 ntfs_warning(vol->sb, "Error allocating page buffers. "
507 "Redirtying page so we try again later.");
508 /*
509 * Put the page back on mapping->dirty_pages, but leave its
510 * buffer's dirty state as-is.
511 */
512 redirty_page_for_writepage(wbc, page);
513 unlock_page(page);
514 return 0;
515 }
516
517 /* NOTE: Different naming scheme to ntfs_read_block()! */
518
519 /* The first block in the page. */
520 block = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
521
07a4e2da
AA
522 read_lock_irqsave(&ni->size_lock, flags);
523 i_size = i_size_read(vi);
524 initialized_size = ni->initialized_size;
525 read_unlock_irqrestore(&ni->size_lock, flags);
526
1da177e4 527 /* The first out of bounds block for the data size. */
07a4e2da 528 dblock = (i_size + blocksize - 1) >> blocksize_bits;
1da177e4
LT
529
530 /* The last (fully or partially) initialized block. */
07a4e2da 531 iblock = initialized_size >> blocksize_bits;
1da177e4
LT
532
533 /*
534 * Be very careful. We have no exclusion from __set_page_dirty_buffers
535 * here, and the (potentially unmapped) buffers may become dirty at
536 * any time. If a buffer becomes dirty here after we've inspected it
537 * then we just miss that fact, and the page stays dirty.
538 *
539 * Buffers outside i_size may be dirtied by __set_page_dirty_buffers;
540 * handle that here by just cleaning them.
541 */
542
543 /*
544 * Loop through all the buffers in the page, mapping all the dirty
545 * buffers to disk addresses and handling any aliases from the
546 * underlying block device's mapping.
547 */
548 rl = NULL;
549 err = 0;
550 do {
551 BOOL is_retry = FALSE;
552
553 if (unlikely(block >= dblock)) {
554 /*
555 * Mapped buffers outside i_size will occur, because
556 * this page can be outside i_size when there is a
557 * truncate in progress. The contents of such buffers
558 * were zeroed by ntfs_writepage().
559 *
560 * FIXME: What about the small race window where
561 * ntfs_writepage() has not done any clearing because
562 * the page was within i_size but before we get here,
563 * vmtruncate() modifies i_size?
564 */
565 clear_buffer_dirty(bh);
566 set_buffer_uptodate(bh);
567 continue;
568 }
569
570 /* Clean buffers are not written out, so no need to map them. */
571 if (!buffer_dirty(bh))
572 continue;
573
574 /* Make sure we have enough initialized size. */
575 if (unlikely((block >= iblock) &&
07a4e2da 576 (initialized_size < i_size))) {
1da177e4
LT
577 /*
578 * If this page is fully outside initialized size, zero
579 * out all pages between the current initialized size
580 * and the current page. Just use ntfs_readpage() to do
581 * the zeroing transparently.
582 */
583 if (block > iblock) {
584 // TODO:
585 // For each page do:
586 // - read_cache_page()
587 // Again for each page do:
588 // - wait_on_page_locked()
589 // - Check (PageUptodate(page) &&
590 // !PageError(page))
591 // Update initialized size in the attribute and
592 // in the inode.
593 // Again, for each page do:
594 // __set_page_dirty_buffers();
595 // page_cache_release()
596 // We don't need to wait on the writes.
597 // Update iblock.
598 }
599 /*
600 * The current page straddles initialized size. Zero
601 * all non-uptodate buffers and set them uptodate (and
602 * dirty?). Note, there aren't any non-uptodate buffers
603 * if the page is uptodate.
604 * FIXME: For an uptodate page, the buffers may need to
605 * be written out because they were not initialized on
606 * disk before.
607 */
608 if (!PageUptodate(page)) {
609 // TODO:
610 // Zero any non-uptodate buffers up to i_size.
611 // Set them uptodate and dirty.
612 }
613 // TODO:
614 // Update initialized size in the attribute and in the
615 // inode (up to i_size).
616 // Update iblock.
617 // FIXME: This is inefficient. Try to batch the two
618 // size changes to happen in one go.
619 ntfs_error(vol->sb, "Writing beyond initialized size "
620 "is not supported yet. Sorry.");
621 err = -EOPNOTSUPP;
622 break;
623 // Do NOT set_buffer_new() BUT DO clear buffer range
624 // outside write request range.
625 // set_buffer_uptodate() on complete buffers as well as
626 // set_buffer_dirty().
627 }
628
629 /* No need to map buffers that are already mapped. */
630 if (buffer_mapped(bh))
631 continue;
632
633 /* Unmapped, dirty buffer. Need to map it. */
634 bh->b_bdev = vol->sb->s_bdev;
635
636 /* Convert block into corresponding vcn and offset. */
637 vcn = (VCN)block << blocksize_bits;
638 vcn_ofs = vcn & vol->cluster_size_mask;
639 vcn >>= vol->cluster_size_bits;
640 if (!rl) {
641lock_retry_remap:
642 down_read(&ni->runlist.lock);
643 rl = ni->runlist.rl;
644 }
645 if (likely(rl != NULL)) {
646 /* Seek to element containing target vcn. */
647 while (rl->length && rl[1].vcn <= vcn)
648 rl++;
649 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
650 } else
651 lcn = LCN_RL_NOT_MAPPED;
652 /* Successful remap. */
653 if (lcn >= 0) {
654 /* Setup buffer head to point to correct block. */
655 bh->b_blocknr = ((lcn << vol->cluster_size_bits) +
656 vcn_ofs) >> blocksize_bits;
657 set_buffer_mapped(bh);
658 continue;
659 }
660 /* It is a hole, need to instantiate it. */
661 if (lcn == LCN_HOLE) {
662 // TODO: Instantiate the hole.
663 // clear_buffer_new(bh);
664 // unmap_underlying_metadata(bh->b_bdev, bh->b_blocknr);
665 ntfs_error(vol->sb, "Writing into sparse regions is "
666 "not supported yet. Sorry.");
667 err = -EOPNOTSUPP;
668 break;
669 }
670 /* If first try and runlist unmapped, map and retry. */
671 if (!is_retry && lcn == LCN_RL_NOT_MAPPED) {
672 is_retry = TRUE;
673 /*
674 * Attempt to map runlist, dropping lock for
675 * the duration.
676 */
677 up_read(&ni->runlist.lock);
678 err = ntfs_map_runlist(ni, vcn);
679 if (likely(!err))
680 goto lock_retry_remap;
681 rl = NULL;
682 lcn = err;
683 }
684 /* Failed to map the buffer, even after retrying. */
685 bh->b_blocknr = -1;
686 ntfs_error(vol->sb, "Failed to write to inode 0x%lx, "
687 "attribute type 0x%x, vcn 0x%llx, offset 0x%x "
688 "because its location on disk could not be "
689 "determined%s (error code %lli).", ni->mft_no,
690 ni->type, (unsigned long long)vcn,
691 vcn_ofs, is_retry ? " even after "
692 "retrying" : "", (long long)lcn);
693 if (!err)
694 err = -EIO;
695 break;
696 } while (block++, (bh = bh->b_this_page) != head);
697
698 /* Release the lock if we took it. */
699 if (rl)
700 up_read(&ni->runlist.lock);
701
702 /* For the error case, need to reset bh to the beginning. */
703 bh = head;
704
705 /* Just an optimization, so ->readpage() isn't called later. */
706 if (unlikely(!PageUptodate(page))) {
707 int uptodate = 1;
708 do {
709 if (!buffer_uptodate(bh)) {
710 uptodate = 0;
711 bh = head;
712 break;
713 }
714 } while ((bh = bh->b_this_page) != head);
715 if (uptodate)
716 SetPageUptodate(page);
717 }
718
719 /* Setup all mapped, dirty buffers for async write i/o. */
720 do {
721 get_bh(bh);
722 if (buffer_mapped(bh) && buffer_dirty(bh)) {
723 lock_buffer(bh);
724 if (test_clear_buffer_dirty(bh)) {
725 BUG_ON(!buffer_uptodate(bh));
726 mark_buffer_async_write(bh);
727 } else
728 unlock_buffer(bh);
729 } else if (unlikely(err)) {
730 /*
731 * For the error case. The buffer may have been set
732 * dirty during attachment to a dirty page.
733 */
734 if (err != -ENOMEM)
735 clear_buffer_dirty(bh);
736 }
737 } while ((bh = bh->b_this_page) != head);
738
739 if (unlikely(err)) {
740 // TODO: Remove the -EOPNOTSUPP check later on...
741 if (unlikely(err == -EOPNOTSUPP))
742 err = 0;
743 else if (err == -ENOMEM) {
744 ntfs_warning(vol->sb, "Error allocating memory. "
745 "Redirtying page so we try again "
746 "later.");
747 /*
748 * Put the page back on mapping->dirty_pages, but
749 * leave its buffer's dirty state as-is.
750 */
751 redirty_page_for_writepage(wbc, page);
752 err = 0;
753 } else
754 SetPageError(page);
755 }
756
757 BUG_ON(PageWriteback(page));
758 set_page_writeback(page); /* Keeps try_to_free_buffers() away. */
759 unlock_page(page);
760
761 /*
762 * Submit the prepared buffers for i/o. Note the page is unlocked,
763 * and the async write i/o completion handler can end_page_writeback()
764 * at any time after the *first* submit_bh(). So the buffers can then
765 * disappear...
766 */
767 need_end_writeback = TRUE;
768 do {
769 struct buffer_head *next = bh->b_this_page;
770 if (buffer_async_write(bh)) {
771 submit_bh(WRITE, bh);
772 need_end_writeback = FALSE;
773 }
774 put_bh(bh);
775 bh = next;
776 } while (bh != head);
777
778 /* If no i/o was started, need to end_page_writeback(). */
779 if (unlikely(need_end_writeback))
780 end_page_writeback(page);
781
782 ntfs_debug("Done.");
783 return err;
784}
785
786/**
787 * ntfs_write_mst_block - write a @page to the backing store
788 * @page: page cache page to write out
789 * @wbc: writeback control structure
790 *
791 * This function is for writing pages belonging to non-resident, mst protected
792 * attributes to their backing store. The only supported attributes are index
793 * allocation and $MFT/$DATA. Both directory inodes and index inodes are
794 * supported for the index allocation case.
795 *
796 * The page must remain locked for the duration of the write because we apply
797 * the mst fixups, write, and then undo the fixups, so if we were to unlock the
798 * page before undoing the fixups, any other user of the page will see the
799 * page contents as corrupt.
800 *
801 * We clear the page uptodate flag for the duration of the function to ensure
802 * exclusion for the $MFT/$DATA case against someone mapping an mft record we
803 * are about to apply the mst fixups to.
804 *
805 * Return 0 on success and -errno on error.
806 *
807 * Based on ntfs_write_block(), ntfs_mft_writepage(), and
808 * write_mft_record_nolock().
809 */
810static int ntfs_write_mst_block(struct page *page,
811 struct writeback_control *wbc)
812{
813 sector_t block, dblock, rec_block;
814 struct inode *vi = page->mapping->host;
815 ntfs_inode *ni = NTFS_I(vi);
816 ntfs_volume *vol = ni->vol;
817 u8 *kaddr;
818 unsigned char bh_size_bits = vi->i_blkbits;
819 unsigned int bh_size = 1 << bh_size_bits;
820 unsigned int rec_size = ni->itype.index.block_size;
821 ntfs_inode *locked_nis[PAGE_CACHE_SIZE / rec_size];
822 struct buffer_head *bh, *head, *tbh, *rec_start_bh;
823 int max_bhs = PAGE_CACHE_SIZE / bh_size;
824 struct buffer_head *bhs[max_bhs];
825 runlist_element *rl;
826 int i, nr_locked_nis, nr_recs, nr_bhs, bhs_per_rec, err, err2;
827 unsigned rec_size_bits;
828 BOOL sync, is_mft, page_is_dirty, rec_is_dirty;
829
830 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
831 "0x%lx.", vi->i_ino, ni->type, page->index);
832 BUG_ON(!NInoNonResident(ni));
833 BUG_ON(!NInoMstProtected(ni));
834 is_mft = (S_ISREG(vi->i_mode) && !vi->i_ino);
835 /*
836 * NOTE: ntfs_write_mst_block() would be called for $MFTMirr if a page
837 * in its page cache were to be marked dirty. However this should
838 * never happen with the current driver and considering we do not
839 * handle this case here we do want to BUG(), at least for now.
840 */
841 BUG_ON(!(is_mft || S_ISDIR(vi->i_mode) ||
842 (NInoAttr(ni) && ni->type == AT_INDEX_ALLOCATION)));
843 BUG_ON(!max_bhs);
844
845 /* Were we called for sync purposes? */
846 sync = (wbc->sync_mode == WB_SYNC_ALL);
847
848 /* Make sure we have mapped buffers. */
849 BUG_ON(!page_has_buffers(page));
850 bh = head = page_buffers(page);
851 BUG_ON(!bh);
852
853 rec_size_bits = ni->itype.index.block_size_bits;
854 BUG_ON(!(PAGE_CACHE_SIZE >> rec_size_bits));
855 bhs_per_rec = rec_size >> bh_size_bits;
856 BUG_ON(!bhs_per_rec);
857
858 /* The first block in the page. */
859 rec_block = block = (sector_t)page->index <<
860 (PAGE_CACHE_SHIFT - bh_size_bits);
861
862 /* The first out of bounds block for the data size. */
07a4e2da 863 dblock = (i_size_read(vi) + bh_size - 1) >> bh_size_bits;
1da177e4
LT
864
865 rl = NULL;
866 err = err2 = nr_bhs = nr_recs = nr_locked_nis = 0;
867 page_is_dirty = rec_is_dirty = FALSE;
868 rec_start_bh = NULL;
869 do {
870 BOOL is_retry = FALSE;
871
872 if (likely(block < rec_block)) {
873 if (unlikely(block >= dblock)) {
874 clear_buffer_dirty(bh);
946929d8 875 set_buffer_uptodate(bh);
1da177e4
LT
876 continue;
877 }
878 /*
879 * This block is not the first one in the record. We
880 * ignore the buffer's dirty state because we could
881 * have raced with a parallel mark_ntfs_record_dirty().
882 */
883 if (!rec_is_dirty)
884 continue;
885 if (unlikely(err2)) {
886 if (err2 != -ENOMEM)
887 clear_buffer_dirty(bh);
888 continue;
889 }
890 } else /* if (block == rec_block) */ {
891 BUG_ON(block > rec_block);
892 /* This block is the first one in the record. */
893 rec_block += bhs_per_rec;
894 err2 = 0;
895 if (unlikely(block >= dblock)) {
896 clear_buffer_dirty(bh);
897 continue;
898 }
899 if (!buffer_dirty(bh)) {
900 /* Clean records are not written out. */
901 rec_is_dirty = FALSE;
902 continue;
903 }
904 rec_is_dirty = TRUE;
905 rec_start_bh = bh;
906 }
907 /* Need to map the buffer if it is not mapped already. */
908 if (unlikely(!buffer_mapped(bh))) {
909 VCN vcn;
910 LCN lcn;
911 unsigned int vcn_ofs;
912
913 /* Obtain the vcn and offset of the current block. */
914 vcn = (VCN)block << bh_size_bits;
915 vcn_ofs = vcn & vol->cluster_size_mask;
916 vcn >>= vol->cluster_size_bits;
917 if (!rl) {
918lock_retry_remap:
919 down_read(&ni->runlist.lock);
920 rl = ni->runlist.rl;
921 }
922 if (likely(rl != NULL)) {
923 /* Seek to element containing target vcn. */
924 while (rl->length && rl[1].vcn <= vcn)
925 rl++;
926 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
927 } else
928 lcn = LCN_RL_NOT_MAPPED;
929 /* Successful remap. */
930 if (likely(lcn >= 0)) {
931 /* Setup buffer head to correct block. */
932 bh->b_blocknr = ((lcn <<
933 vol->cluster_size_bits) +
934 vcn_ofs) >> bh_size_bits;
935 set_buffer_mapped(bh);
936 } else {
937 /*
938 * Remap failed. Retry to map the runlist once
939 * unless we are working on $MFT which always
940 * has the whole of its runlist in memory.
941 */
942 if (!is_mft && !is_retry &&
943 lcn == LCN_RL_NOT_MAPPED) {
944 is_retry = TRUE;
945 /*
946 * Attempt to map runlist, dropping
947 * lock for the duration.
948 */
949 up_read(&ni->runlist.lock);
950 err2 = ntfs_map_runlist(ni, vcn);
951 if (likely(!err2))
952 goto lock_retry_remap;
953 if (err2 == -ENOMEM)
954 page_is_dirty = TRUE;
955 lcn = err2;
956 } else
957 err2 = -EIO;
958 /* Hard error. Abort writing this record. */
959 if (!err || err == -ENOMEM)
960 err = err2;
961 bh->b_blocknr = -1;
962 ntfs_error(vol->sb, "Cannot write ntfs record "
963 "0x%llx (inode 0x%lx, "
964 "attribute type 0x%x) because "
965 "its location on disk could "
966 "not be determined (error "
967 "code %lli).", (s64)block <<
968 bh_size_bits >>
969 vol->mft_record_size_bits,
970 ni->mft_no, ni->type,
971 (long long)lcn);
972 /*
973 * If this is not the first buffer, remove the
974 * buffers in this record from the list of
975 * buffers to write and clear their dirty bit
976 * if not error -ENOMEM.
977 */
978 if (rec_start_bh != bh) {
979 while (bhs[--nr_bhs] != rec_start_bh)
980 ;
981 if (err2 != -ENOMEM) {
982 do {
983 clear_buffer_dirty(
984 rec_start_bh);
985 } while ((rec_start_bh =
986 rec_start_bh->
987 b_this_page) !=
988 bh);
989 }
990 }
991 continue;
992 }
993 }
994 BUG_ON(!buffer_uptodate(bh));
995 BUG_ON(nr_bhs >= max_bhs);
996 bhs[nr_bhs++] = bh;
997 } while (block++, (bh = bh->b_this_page) != head);
998 if (unlikely(rl))
999 up_read(&ni->runlist.lock);
1000 /* If there were no dirty buffers, we are done. */
1001 if (!nr_bhs)
1002 goto done;
1003 /* Map the page so we can access its contents. */
1004 kaddr = kmap(page);
1005 /* Clear the page uptodate flag whilst the mst fixups are applied. */
1006 BUG_ON(!PageUptodate(page));
1007 ClearPageUptodate(page);
1008 for (i = 0; i < nr_bhs; i++) {
1009 unsigned int ofs;
1010
1011 /* Skip buffers which are not at the beginning of records. */
1012 if (i % bhs_per_rec)
1013 continue;
1014 tbh = bhs[i];
1015 ofs = bh_offset(tbh);
1016 if (is_mft) {
1017 ntfs_inode *tni;
1018 unsigned long mft_no;
1019
1020 /* Get the mft record number. */
1021 mft_no = (((s64)page->index << PAGE_CACHE_SHIFT) + ofs)
1022 >> rec_size_bits;
1023 /* Check whether to write this mft record. */
1024 tni = NULL;
1025 if (!ntfs_may_write_mft_record(vol, mft_no,
1026 (MFT_RECORD*)(kaddr + ofs), &tni)) {
1027 /*
1028 * The record should not be written. This
1029 * means we need to redirty the page before
1030 * returning.
1031 */
1032 page_is_dirty = TRUE;
1033 /*
1034 * Remove the buffers in this mft record from
1035 * the list of buffers to write.
1036 */
1037 do {
1038 bhs[i] = NULL;
1039 } while (++i % bhs_per_rec);
1040 continue;
1041 }
1042 /*
1043 * The record should be written. If a locked ntfs
1044 * inode was returned, add it to the array of locked
1045 * ntfs inodes.
1046 */
1047 if (tni)
1048 locked_nis[nr_locked_nis++] = tni;
1049 }
1050 /* Apply the mst protection fixups. */
1051 err2 = pre_write_mst_fixup((NTFS_RECORD*)(kaddr + ofs),
1052 rec_size);
1053 if (unlikely(err2)) {
1054 if (!err || err == -ENOMEM)
1055 err = -EIO;
1056 ntfs_error(vol->sb, "Failed to apply mst fixups "
1057 "(inode 0x%lx, attribute type 0x%x, "
1058 "page index 0x%lx, page offset 0x%x)!"
1059 " Unmount and run chkdsk.", vi->i_ino,
1060 ni->type, page->index, ofs);
1061 /*
1062 * Mark all the buffers in this record clean as we do
1063 * not want to write corrupt data to disk.
1064 */
1065 do {
1066 clear_buffer_dirty(bhs[i]);
1067 bhs[i] = NULL;
1068 } while (++i % bhs_per_rec);
1069 continue;
1070 }
1071 nr_recs++;
1072 }
1073 /* If no records are to be written out, we are done. */
1074 if (!nr_recs)
1075 goto unm_done;
1076 flush_dcache_page(page);
1077 /* Lock buffers and start synchronous write i/o on them. */
1078 for (i = 0; i < nr_bhs; i++) {
1079 tbh = bhs[i];
1080 if (!tbh)
1081 continue;
1082 if (unlikely(test_set_buffer_locked(tbh)))
1083 BUG();
1084 /* The buffer dirty state is now irrelevant, just clean it. */
1085 clear_buffer_dirty(tbh);
1086 BUG_ON(!buffer_uptodate(tbh));
1087 BUG_ON(!buffer_mapped(tbh));
1088 get_bh(tbh);
1089 tbh->b_end_io = end_buffer_write_sync;
1090 submit_bh(WRITE, tbh);
1091 }
1092 /* Synchronize the mft mirror now if not @sync. */
1093 if (is_mft && !sync)
1094 goto do_mirror;
1095do_wait:
1096 /* Wait on i/o completion of buffers. */
1097 for (i = 0; i < nr_bhs; i++) {
1098 tbh = bhs[i];
1099 if (!tbh)
1100 continue;
1101 wait_on_buffer(tbh);
1102 if (unlikely(!buffer_uptodate(tbh))) {
1103 ntfs_error(vol->sb, "I/O error while writing ntfs "
1104 "record buffer (inode 0x%lx, "
1105 "attribute type 0x%x, page index "
1106 "0x%lx, page offset 0x%lx)! Unmount "
1107 "and run chkdsk.", vi->i_ino, ni->type,
1108 page->index, bh_offset(tbh));
1109 if (!err || err == -ENOMEM)
1110 err = -EIO;
1111 /*
1112 * Set the buffer uptodate so the page and buffer
1113 * states do not become out of sync.
1114 */
1115 set_buffer_uptodate(tbh);
1116 }
1117 }
1118 /* If @sync, now synchronize the mft mirror. */
1119 if (is_mft && sync) {
1120do_mirror:
1121 for (i = 0; i < nr_bhs; i++) {
1122 unsigned long mft_no;
1123 unsigned int ofs;
1124
1125 /*
1126 * Skip buffers which are not at the beginning of
1127 * records.
1128 */
1129 if (i % bhs_per_rec)
1130 continue;
1131 tbh = bhs[i];
1132 /* Skip removed buffers (and hence records). */
1133 if (!tbh)
1134 continue;
1135 ofs = bh_offset(tbh);
1136 /* Get the mft record number. */
1137 mft_no = (((s64)page->index << PAGE_CACHE_SHIFT) + ofs)
1138 >> rec_size_bits;
1139 if (mft_no < vol->mftmirr_size)
1140 ntfs_sync_mft_mirror(vol, mft_no,
1141 (MFT_RECORD*)(kaddr + ofs),
1142 sync);
1143 }
1144 if (!sync)
1145 goto do_wait;
1146 }
1147 /* Remove the mst protection fixups again. */
1148 for (i = 0; i < nr_bhs; i++) {
1149 if (!(i % bhs_per_rec)) {
1150 tbh = bhs[i];
1151 if (!tbh)
1152 continue;
1153 post_write_mst_fixup((NTFS_RECORD*)(kaddr +
1154 bh_offset(tbh)));
1155 }
1156 }
1157 flush_dcache_page(page);
1158unm_done:
1159 /* Unlock any locked inodes. */
1160 while (nr_locked_nis-- > 0) {
1161 ntfs_inode *tni, *base_tni;
1162
1163 tni = locked_nis[nr_locked_nis];
1164 /* Get the base inode. */
1165 down(&tni->extent_lock);
1166 if (tni->nr_extents >= 0)
1167 base_tni = tni;
1168 else {
1169 base_tni = tni->ext.base_ntfs_ino;
1170 BUG_ON(!base_tni);
1171 }
1172 up(&tni->extent_lock);
1173 ntfs_debug("Unlocking %s inode 0x%lx.",
1174 tni == base_tni ? "base" : "extent",
1175 tni->mft_no);
1176 up(&tni->mrec_lock);
1177 atomic_dec(&tni->count);
1178 iput(VFS_I(base_tni));
1179 }
1180 SetPageUptodate(page);
1181 kunmap(page);
1182done:
1183 if (unlikely(err && err != -ENOMEM)) {
1184 /*
1185 * Set page error if there is only one ntfs record in the page.
1186 * Otherwise we would loose per-record granularity.
1187 */
1188 if (ni->itype.index.block_size == PAGE_CACHE_SIZE)
1189 SetPageError(page);
1190 NVolSetErrors(vol);
1191 }
1192 if (page_is_dirty) {
1193 ntfs_debug("Page still contains one or more dirty ntfs "
1194 "records. Redirtying the page starting at "
1195 "record 0x%lx.", page->index <<
1196 (PAGE_CACHE_SHIFT - rec_size_bits));
1197 redirty_page_for_writepage(wbc, page);
1198 unlock_page(page);
1199 } else {
1200 /*
1201 * Keep the VM happy. This must be done otherwise the
1202 * radix-tree tag PAGECACHE_TAG_DIRTY remains set even though
1203 * the page is clean.
1204 */
1205 BUG_ON(PageWriteback(page));
1206 set_page_writeback(page);
1207 unlock_page(page);
1208 end_page_writeback(page);
1209 }
1210 if (likely(!err))
1211 ntfs_debug("Done.");
1212 return err;
1213}
1214
1215/**
1216 * ntfs_writepage - write a @page to the backing store
1217 * @page: page cache page to write out
1218 * @wbc: writeback control structure
1219 *
1220 * This is called from the VM when it wants to have a dirty ntfs page cache
1221 * page cleaned. The VM has already locked the page and marked it clean.
1222 *
1223 * For non-resident attributes, ntfs_writepage() writes the @page by calling
1224 * the ntfs version of the generic block_write_full_page() function,
1225 * ntfs_write_block(), which in turn if necessary creates and writes the
1226 * buffers associated with the page asynchronously.
1227 *
1228 * For resident attributes, OTOH, ntfs_writepage() writes the @page by copying
1229 * the data to the mft record (which at this stage is most likely in memory).
1230 * The mft record is then marked dirty and written out asynchronously via the
1231 * vfs inode dirty code path for the inode the mft record belongs to or via the
1232 * vm page dirty code path for the page the mft record is in.
1233 *
1234 * Based on ntfs_readpage() and fs/buffer.c::block_write_full_page().
1235 *
1236 * Return 0 on success and -errno on error.
1237 */
1238static int ntfs_writepage(struct page *page, struct writeback_control *wbc)
1239{
1240 loff_t i_size;
149f0c52
AA
1241 struct inode *vi = page->mapping->host;
1242 ntfs_inode *base_ni = NULL, *ni = NTFS_I(vi);
1da177e4 1243 char *kaddr;
149f0c52
AA
1244 ntfs_attr_search_ctx *ctx = NULL;
1245 MFT_RECORD *m = NULL;
1da177e4
LT
1246 u32 attr_len;
1247 int err;
1248
1249 BUG_ON(!PageLocked(page));
149f0c52
AA
1250 /*
1251 * If a previous ntfs_truncate() failed, repeat it and abort if it
1252 * fails again.
1253 */
1254 if (unlikely(NInoTruncateFailed(ni))) {
1255 down_write(&vi->i_alloc_sem);
1256 err = ntfs_truncate(vi);
1257 up_write(&vi->i_alloc_sem);
1258 if (err || NInoTruncateFailed(ni)) {
1259 if (!err)
1260 err = -EIO;
1261 goto err_out;
1262 }
1263 }
1da177e4 1264 i_size = i_size_read(vi);
1da177e4
LT
1265 /* Is the page fully outside i_size? (truncate in progress) */
1266 if (unlikely(page->index >= (i_size + PAGE_CACHE_SIZE - 1) >>
1267 PAGE_CACHE_SHIFT)) {
1268 /*
1269 * The page may have dirty, unmapped buffers. Make them
1270 * freeable here, so the page does not leak.
1271 */
1272 block_invalidatepage(page, 0);
1273 unlock_page(page);
1274 ntfs_debug("Write outside i_size - truncated?");
1275 return 0;
1276 }
1da177e4
LT
1277 /* NInoNonResident() == NInoIndexAllocPresent() */
1278 if (NInoNonResident(ni)) {
1279 /*
1280 * Only unnamed $DATA attributes can be compressed, encrypted,
1281 * and/or sparse.
1282 */
1283 if (ni->type == AT_DATA && !ni->name_len) {
1284 /* If file is encrypted, deny access, just like NT4. */
1285 if (NInoEncrypted(ni)) {
1286 unlock_page(page);
1287 ntfs_debug("Denying write access to encrypted "
1288 "file.");
1289 return -EACCES;
1290 }
1291 /* Compressed data streams are handled in compress.c. */
1292 if (NInoCompressed(ni)) {
1293 // TODO: Implement and replace this check with
1294 // return ntfs_write_compressed_block(page);
1295 unlock_page(page);
1296 ntfs_error(vi->i_sb, "Writing to compressed "
1297 "files is not supported yet. "
1298 "Sorry.");
1299 return -EOPNOTSUPP;
1300 }
1301 // TODO: Implement and remove this check.
1302 if (NInoSparse(ni)) {
1303 unlock_page(page);
1304 ntfs_error(vi->i_sb, "Writing to sparse files "
1305 "is not supported yet. Sorry.");
1306 return -EOPNOTSUPP;
1307 }
1308 }
1309 /* We have to zero every time due to mmap-at-end-of-file. */
1310 if (page->index >= (i_size >> PAGE_CACHE_SHIFT)) {
1311 /* The page straddles i_size. */
1312 unsigned int ofs = i_size & ~PAGE_CACHE_MASK;
1313 kaddr = kmap_atomic(page, KM_USER0);
1314 memset(kaddr + ofs, 0, PAGE_CACHE_SIZE - ofs);
1315 flush_dcache_page(page);
1316 kunmap_atomic(kaddr, KM_USER0);
1317 }
1318 /* Handle mst protected attributes. */
1319 if (NInoMstProtected(ni))
1320 return ntfs_write_mst_block(page, wbc);
1321 /* Normal data stream. */
1322 return ntfs_write_block(page, wbc);
1323 }
1324 /*
1325 * Attribute is resident, implying it is not compressed, encrypted,
1326 * sparse, or mst protected. This also means the attribute is smaller
1327 * than an mft record and hence smaller than a page, so can simply
1328 * return error on any pages with index above 0.
1329 */
1330 BUG_ON(page_has_buffers(page));
1331 BUG_ON(!PageUptodate(page));
1332 if (unlikely(page->index > 0)) {
1333 ntfs_error(vi->i_sb, "BUG()! page->index (0x%lx) > 0. "
1334 "Aborting write.", page->index);
1335 BUG_ON(PageWriteback(page));
1336 set_page_writeback(page);
1337 unlock_page(page);
1338 end_page_writeback(page);
1339 return -EIO;
1340 }
1341 if (!NInoAttr(ni))
1342 base_ni = ni;
1343 else
1344 base_ni = ni->ext.base_ntfs_ino;
1345 /* Map, pin, and lock the mft record. */
1346 m = map_mft_record(base_ni);
1347 if (IS_ERR(m)) {
1348 err = PTR_ERR(m);
1349 m = NULL;
1350 ctx = NULL;
1351 goto err_out;
1352 }
1353 ctx = ntfs_attr_get_search_ctx(base_ni, m);
1354 if (unlikely(!ctx)) {
1355 err = -ENOMEM;
1356 goto err_out;
1357 }
1358 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1359 CASE_SENSITIVE, 0, NULL, 0, ctx);
1360 if (unlikely(err))
1361 goto err_out;
1362 /*
1363 * Keep the VM happy. This must be done otherwise the radix-tree tag
1364 * PAGECACHE_TAG_DIRTY remains set even though the page is clean.
1365 */
1366 BUG_ON(PageWriteback(page));
1367 set_page_writeback(page);
1368 unlock_page(page);
1369
1370 /*
1371 * Here, we don't need to zero the out of bounds area everytime because
1372 * the below memcpy() already takes care of the mmap-at-end-of-file
1373 * requirements. If the file is converted to a non-resident one, then
1374 * the code path use is switched to the non-resident one where the
1375 * zeroing happens on each ntfs_writepage() invocation.
1376 *
1377 * The above also applies nicely when i_size is decreased.
1378 *
1379 * When i_size is increased, the memory between the old and new i_size
1380 * _must_ be zeroed (or overwritten with new data). Otherwise we will
1381 * expose data to userspace/disk which should never have been exposed.
1382 *
1383 * FIXME: Ensure that i_size increases do the zeroing/overwriting and
1384 * if we cannot guarantee that, then enable the zeroing below. If the
1385 * zeroing below is enabled, we MUST move the unlock_page() from above
1386 * to after the kunmap_atomic(), i.e. just before the
1387 * end_page_writeback().
1388 * UPDATE: ntfs_prepare/commit_write() do the zeroing on i_size
1389 * increases for resident attributes so those are ok.
1390 * TODO: ntfs_truncate(), others?
1391 */
1392
1393 attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
07a4e2da 1394 i_size = i_size_read(vi);
1da177e4 1395 if (unlikely(attr_len > i_size)) {
1da177e4 1396 attr_len = i_size;
f40661be 1397 ctx->attr->data.resident.value_length = cpu_to_le32(attr_len);
1da177e4 1398 }
f40661be 1399 kaddr = kmap_atomic(page, KM_USER0);
1da177e4
LT
1400 /* Copy the data from the page to the mft record. */
1401 memcpy((u8*)ctx->attr +
1402 le16_to_cpu(ctx->attr->data.resident.value_offset),
1403 kaddr, attr_len);
1404 flush_dcache_mft_record_page(ctx->ntfs_ino);
1405 /* Zero out of bounds area in the page cache page. */
1406 memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
1407 flush_dcache_page(page);
1408 kunmap_atomic(kaddr, KM_USER0);
1409
1410 end_page_writeback(page);
1411
1412 /* Mark the mft record dirty, so it gets written back. */
1413 mark_mft_record_dirty(ctx->ntfs_ino);
1414 ntfs_attr_put_search_ctx(ctx);
1415 unmap_mft_record(base_ni);
1416 return 0;
1417err_out:
1418 if (err == -ENOMEM) {
1419 ntfs_warning(vi->i_sb, "Error allocating memory. Redirtying "
1420 "page so we try again later.");
1421 /*
1422 * Put the page back on mapping->dirty_pages, but leave its
1423 * buffers' dirty state as-is.
1424 */
1425 redirty_page_for_writepage(wbc, page);
1426 err = 0;
1427 } else {
1428 ntfs_error(vi->i_sb, "Resident attribute write failed with "
149f0c52 1429 "error %i.", err);
1da177e4 1430 SetPageError(page);
149f0c52
AA
1431 NVolSetErrors(ni->vol);
1432 make_bad_inode(vi);
1da177e4
LT
1433 }
1434 unlock_page(page);
1435 if (ctx)
1436 ntfs_attr_put_search_ctx(ctx);
1437 if (m)
1438 unmap_mft_record(base_ni);
1439 return err;
1440}
1441
1442/**
1443 * ntfs_prepare_nonresident_write -
1444 *
1445 */
1446static int ntfs_prepare_nonresident_write(struct page *page,
1447 unsigned from, unsigned to)
1448{
1449 VCN vcn;
1450 LCN lcn;
07a4e2da
AA
1451 s64 initialized_size;
1452 loff_t i_size;
1da177e4
LT
1453 sector_t block, ablock, iblock;
1454 struct inode *vi;
1455 ntfs_inode *ni;
1456 ntfs_volume *vol;
1457 runlist_element *rl;
1458 struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
07a4e2da 1459 unsigned long flags;
1da177e4
LT
1460 unsigned int vcn_ofs, block_start, block_end, blocksize;
1461 int err;
1462 BOOL is_retry;
1463 unsigned char blocksize_bits;
1464
1465 vi = page->mapping->host;
1466 ni = NTFS_I(vi);
1467 vol = ni->vol;
1468
1469 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
1470 "0x%lx, from = %u, to = %u.", ni->mft_no, ni->type,
1471 page->index, from, to);
1472
1473 BUG_ON(!NInoNonResident(ni));
1474
1475 blocksize_bits = vi->i_blkbits;
1476 blocksize = 1 << blocksize_bits;
1477
1478 /*
1479 * create_empty_buffers() will create uptodate/dirty buffers if the
1480 * page is uptodate/dirty.
1481 */
1482 if (!page_has_buffers(page))
1483 create_empty_buffers(page, blocksize, 0);
1484 bh = head = page_buffers(page);
1485 if (unlikely(!bh))
1486 return -ENOMEM;
1487
1488 /* The first block in the page. */
1489 block = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
1490
07a4e2da 1491 read_lock_irqsave(&ni->size_lock, flags);
1da177e4
LT
1492 /*
1493 * The first out of bounds block for the allocated size. No need to
1494 * round up as allocated_size is in multiples of cluster size and the
1495 * minimum cluster size is 512 bytes, which is equal to the smallest
1496 * blocksize.
1497 */
1498 ablock = ni->allocated_size >> blocksize_bits;
1499
07a4e2da
AA
1500 i_size = i_size_read(vi);
1501 initialized_size = ni->initialized_size;
1502 read_unlock_irqrestore(&ni->size_lock, flags);
1503
1da177e4 1504 /* The last (fully or partially) initialized block. */
07a4e2da 1505 iblock = initialized_size >> blocksize_bits;
1da177e4
LT
1506
1507 /* Loop through all the buffers in the page. */
1508 block_start = 0;
1509 rl = NULL;
1510 err = 0;
1511 do {
1512 block_end = block_start + blocksize;
1513 /*
1514 * If buffer @bh is outside the write, just mark it uptodate
1515 * if the page is uptodate and continue with the next buffer.
1516 */
1517 if (block_end <= from || block_start >= to) {
1518 if (PageUptodate(page)) {
1519 if (!buffer_uptodate(bh))
1520 set_buffer_uptodate(bh);
1521 }
1522 continue;
1523 }
1524 /*
1525 * @bh is at least partially being written to.
1526 * Make sure it is not marked as new.
1527 */
1528 //if (buffer_new(bh))
1529 // clear_buffer_new(bh);
1530
1531 if (block >= ablock) {
1532 // TODO: block is above allocated_size, need to
1533 // allocate it. Best done in one go to accommodate not
1534 // only block but all above blocks up to and including:
1535 // ((page->index << PAGE_CACHE_SHIFT) + to + blocksize
1536 // - 1) >> blobksize_bits. Obviously will need to round
1537 // up to next cluster boundary, too. This should be
1538 // done with a helper function, so it can be reused.
1539 ntfs_error(vol->sb, "Writing beyond allocated size "
1540 "is not supported yet. Sorry.");
1541 err = -EOPNOTSUPP;
1542 goto err_out;
1543 // Need to update ablock.
1544 // Need to set_buffer_new() on all block bhs that are
1545 // newly allocated.
1546 }
1547 /*
1548 * Now we have enough allocated size to fulfill the whole
1549 * request, i.e. block < ablock is true.
1550 */
1551 if (unlikely((block >= iblock) &&
07a4e2da 1552 (initialized_size < i_size))) {
1da177e4
LT
1553 /*
1554 * If this page is fully outside initialized size, zero
1555 * out all pages between the current initialized size
1556 * and the current page. Just use ntfs_readpage() to do
1557 * the zeroing transparently.
1558 */
1559 if (block > iblock) {
1560 // TODO:
1561 // For each page do:
1562 // - read_cache_page()
1563 // Again for each page do:
1564 // - wait_on_page_locked()
1565 // - Check (PageUptodate(page) &&
1566 // !PageError(page))
1567 // Update initialized size in the attribute and
1568 // in the inode.
1569 // Again, for each page do:
1570 // __set_page_dirty_buffers();
1571 // page_cache_release()
1572 // We don't need to wait on the writes.
1573 // Update iblock.
1574 }
1575 /*
1576 * The current page straddles initialized size. Zero
1577 * all non-uptodate buffers and set them uptodate (and
1578 * dirty?). Note, there aren't any non-uptodate buffers
1579 * if the page is uptodate.
1580 * FIXME: For an uptodate page, the buffers may need to
1581 * be written out because they were not initialized on
1582 * disk before.
1583 */
1584 if (!PageUptodate(page)) {
1585 // TODO:
1586 // Zero any non-uptodate buffers up to i_size.
1587 // Set them uptodate and dirty.
1588 }
1589 // TODO:
1590 // Update initialized size in the attribute and in the
1591 // inode (up to i_size).
1592 // Update iblock.
1593 // FIXME: This is inefficient. Try to batch the two
1594 // size changes to happen in one go.
1595 ntfs_error(vol->sb, "Writing beyond initialized size "
1596 "is not supported yet. Sorry.");
1597 err = -EOPNOTSUPP;
1598 goto err_out;
1599 // Do NOT set_buffer_new() BUT DO clear buffer range
1600 // outside write request range.
1601 // set_buffer_uptodate() on complete buffers as well as
1602 // set_buffer_dirty().
1603 }
1604
1605 /* Need to map unmapped buffers. */
1606 if (!buffer_mapped(bh)) {
1607 /* Unmapped buffer. Need to map it. */
1608 bh->b_bdev = vol->sb->s_bdev;
1609
1610 /* Convert block into corresponding vcn and offset. */
1611 vcn = (VCN)block << blocksize_bits >>
1612 vol->cluster_size_bits;
1613 vcn_ofs = ((VCN)block << blocksize_bits) &
1614 vol->cluster_size_mask;
1615
1616 is_retry = FALSE;
1617 if (!rl) {
1618lock_retry_remap:
1619 down_read(&ni->runlist.lock);
1620 rl = ni->runlist.rl;
1621 }
1622 if (likely(rl != NULL)) {
1623 /* Seek to element containing target vcn. */
1624 while (rl->length && rl[1].vcn <= vcn)
1625 rl++;
1626 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
1627 } else
1628 lcn = LCN_RL_NOT_MAPPED;
1629 if (unlikely(lcn < 0)) {
1630 /*
1631 * We extended the attribute allocation above.
1632 * If we hit an ENOENT here it means that the
1633 * allocation was insufficient which is a bug.
1634 */
1635 BUG_ON(lcn == LCN_ENOENT);
1636
1637 /* It is a hole, need to instantiate it. */
1638 if (lcn == LCN_HOLE) {
1639 // TODO: Instantiate the hole.
1640 // clear_buffer_new(bh);
1641 // unmap_underlying_metadata(bh->b_bdev,
1642 // bh->b_blocknr);
1643 // For non-uptodate buffers, need to
1644 // zero out the region outside the
1645 // request in this bh or all bhs,
1646 // depending on what we implemented
1647 // above.
1648 // Need to flush_dcache_page().
1649 // Or could use set_buffer_new()
1650 // instead?
1651 ntfs_error(vol->sb, "Writing into "
1652 "sparse regions is "
1653 "not supported yet. "
1654 "Sorry.");
1655 err = -EOPNOTSUPP;
1656 goto err_out;
1657 } else if (!is_retry &&
1658 lcn == LCN_RL_NOT_MAPPED) {
1659 is_retry = TRUE;
1660 /*
1661 * Attempt to map runlist, dropping
1662 * lock for the duration.
1663 */
1664 up_read(&ni->runlist.lock);
1665 err = ntfs_map_runlist(ni, vcn);
1666 if (likely(!err))
1667 goto lock_retry_remap;
1668 rl = NULL;
1669 lcn = err;
1670 }
1671 /*
1672 * Failed to map the buffer, even after
1673 * retrying.
1674 */
1675 bh->b_blocknr = -1;
1676 ntfs_error(vol->sb, "Failed to write to inode "
1677 "0x%lx, attribute type 0x%x, "
1678 "vcn 0x%llx, offset 0x%x "
1679 "because its location on disk "
1680 "could not be determined%s "
1681 "(error code %lli).",
1682 ni->mft_no, ni->type,
1683 (unsigned long long)vcn,
1684 vcn_ofs, is_retry ? " even "
1685 "after retrying" : "",
1686 (long long)lcn);
1687 if (!err)
1688 err = -EIO;
1689 goto err_out;
1690 }
1691 /* We now have a successful remap, i.e. lcn >= 0. */
1692
1693 /* Setup buffer head to correct block. */
1694 bh->b_blocknr = ((lcn << vol->cluster_size_bits)
1695 + vcn_ofs) >> blocksize_bits;
1696 set_buffer_mapped(bh);
1697
1698 // FIXME: Something analogous to this is needed for
1699 // each newly allocated block, i.e. BH_New.
1700 // FIXME: Might need to take this out of the
1701 // if (!buffer_mapped(bh)) {}, depending on how we
1702 // implement things during the allocated_size and
1703 // initialized_size extension code above.
1704 if (buffer_new(bh)) {
1705 clear_buffer_new(bh);
1706 unmap_underlying_metadata(bh->b_bdev,
1707 bh->b_blocknr);
1708 if (PageUptodate(page)) {
1709 set_buffer_uptodate(bh);
1710 continue;
1711 }
1712 /*
1713 * Page is _not_ uptodate, zero surrounding
1714 * region. NOTE: This is how we decide if to
1715 * zero or not!
1716 */
1717 if (block_end > to || block_start < from) {
1718 void *kaddr;
1719
1720 kaddr = kmap_atomic(page, KM_USER0);
1721 if (block_end > to)
1722 memset(kaddr + to, 0,
1723 block_end - to);
1724 if (block_start < from)
1725 memset(kaddr + block_start, 0,
1726 from -
1727 block_start);
1728 flush_dcache_page(page);
1729 kunmap_atomic(kaddr, KM_USER0);
1730 }
1731 continue;
1732 }
1733 }
1734 /* @bh is mapped, set it uptodate if the page is uptodate. */
1735 if (PageUptodate(page)) {
1736 if (!buffer_uptodate(bh))
1737 set_buffer_uptodate(bh);
1738 continue;
1739 }
1740 /*
1741 * The page is not uptodate. The buffer is mapped. If it is not
1742 * uptodate, and it is only partially being written to, we need
1743 * to read the buffer in before the write, i.e. right now.
1744 */
1745 if (!buffer_uptodate(bh) &&
1746 (block_start < from || block_end > to)) {
1747 ll_rw_block(READ, 1, &bh);
1748 *wait_bh++ = bh;
1749 }
1750 } while (block++, block_start = block_end,
1751 (bh = bh->b_this_page) != head);
1752
1753 /* Release the lock if we took it. */
1754 if (rl) {
1755 up_read(&ni->runlist.lock);
1756 rl = NULL;
1757 }
1758
1759 /* If we issued read requests, let them complete. */
1760 while (wait_bh > wait) {
1761 wait_on_buffer(*--wait_bh);
1762 if (!buffer_uptodate(*wait_bh))
1763 return -EIO;
1764 }
1765
1766 ntfs_debug("Done.");
1767 return 0;
1768err_out:
1769 /*
1770 * Zero out any newly allocated blocks to avoid exposing stale data.
1771 * If BH_New is set, we know that the block was newly allocated in the
1772 * above loop.
1773 * FIXME: What about initialized_size increments? Have we done all the
1774 * required zeroing above? If not this error handling is broken, and
1775 * in particular the if (block_end <= from) check is completely bogus.
1776 */
1777 bh = head;
1778 block_start = 0;
1779 is_retry = FALSE;
1780 do {
1781 block_end = block_start + blocksize;
1782 if (block_end <= from)
1783 continue;
1784 if (block_start >= to)
1785 break;
1786 if (buffer_new(bh)) {
1787 void *kaddr;
1788
1789 clear_buffer_new(bh);
1790 kaddr = kmap_atomic(page, KM_USER0);
1791 memset(kaddr + block_start, 0, bh->b_size);
1792 kunmap_atomic(kaddr, KM_USER0);
1793 set_buffer_uptodate(bh);
1794 mark_buffer_dirty(bh);
1795 is_retry = TRUE;
1796 }
1797 } while (block_start = block_end, (bh = bh->b_this_page) != head);
1798 if (is_retry)
1799 flush_dcache_page(page);
1800 if (rl)
1801 up_read(&ni->runlist.lock);
1802 return err;
1803}
1804
1805/**
1806 * ntfs_prepare_write - prepare a page for receiving data
1807 *
1808 * This is called from generic_file_write() with i_sem held on the inode
1809 * (@page->mapping->host). The @page is locked but not kmap()ped. The source
1810 * data has not yet been copied into the @page.
1811 *
1812 * Need to extend the attribute/fill in holes if necessary, create blocks and
1813 * make partially overwritten blocks uptodate,
1814 *
1815 * i_size is not to be modified yet.
1816 *
1817 * Return 0 on success or -errno on error.
1818 *
1819 * Should be using block_prepare_write() [support for sparse files] or
1820 * cont_prepare_write() [no support for sparse files]. Cannot do that due to
1821 * ntfs specifics but can look at them for implementation guidance.
1822 *
1823 * Note: In the range, @from is inclusive and @to is exclusive, i.e. @from is
1824 * the first byte in the page that will be written to and @to is the first byte
1825 * after the last byte that will be written to.
1826 */
1827static int ntfs_prepare_write(struct file *file, struct page *page,
1828 unsigned from, unsigned to)
1829{
1830 s64 new_size;
f40661be 1831 loff_t i_size;
1da177e4
LT
1832 struct inode *vi = page->mapping->host;
1833 ntfs_inode *base_ni = NULL, *ni = NTFS_I(vi);
1834 ntfs_volume *vol = ni->vol;
1835 ntfs_attr_search_ctx *ctx = NULL;
1836 MFT_RECORD *m = NULL;
1837 ATTR_RECORD *a;
1838 u8 *kaddr;
1839 u32 attr_len;
1840 int err;
1841
1842 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
1843 "0x%lx, from = %u, to = %u.", vi->i_ino, ni->type,
1844 page->index, from, to);
1845 BUG_ON(!PageLocked(page));
1846 BUG_ON(from > PAGE_CACHE_SIZE);
1847 BUG_ON(to > PAGE_CACHE_SIZE);
1848 BUG_ON(from > to);
1849 BUG_ON(NInoMstProtected(ni));
1850 /*
1851 * If a previous ntfs_truncate() failed, repeat it and abort if it
1852 * fails again.
1853 */
1854 if (unlikely(NInoTruncateFailed(ni))) {
1855 down_write(&vi->i_alloc_sem);
1856 err = ntfs_truncate(vi);
1857 up_write(&vi->i_alloc_sem);
1858 if (err || NInoTruncateFailed(ni)) {
1859 if (!err)
1860 err = -EIO;
1861 goto err_out;
1862 }
1863 }
1864 /* If the attribute is not resident, deal with it elsewhere. */
1865 if (NInoNonResident(ni)) {
1866 /*
1867 * Only unnamed $DATA attributes can be compressed, encrypted,
1868 * and/or sparse.
1869 */
1870 if (ni->type == AT_DATA && !ni->name_len) {
1871 /* If file is encrypted, deny access, just like NT4. */
1872 if (NInoEncrypted(ni)) {
1873 ntfs_debug("Denying write access to encrypted "
1874 "file.");
1875 return -EACCES;
1876 }
1877 /* Compressed data streams are handled in compress.c. */
1878 if (NInoCompressed(ni)) {
1879 // TODO: Implement and replace this check with
1880 // return ntfs_write_compressed_block(page);
1881 ntfs_error(vi->i_sb, "Writing to compressed "
1882 "files is not supported yet. "
1883 "Sorry.");
1884 return -EOPNOTSUPP;
1885 }
1886 // TODO: Implement and remove this check.
1887 if (NInoSparse(ni)) {
1888 ntfs_error(vi->i_sb, "Writing to sparse files "
1889 "is not supported yet. Sorry.");
1890 return -EOPNOTSUPP;
1891 }
1892 }
1893 /* Normal data stream. */
1894 return ntfs_prepare_nonresident_write(page, from, to);
1895 }
1896 /*
1897 * Attribute is resident, implying it is not compressed, encrypted, or
1898 * sparse.
1899 */
1900 BUG_ON(page_has_buffers(page));
1901 new_size = ((s64)page->index << PAGE_CACHE_SHIFT) + to;
1902 /* If we do not need to resize the attribute allocation we are done. */
07a4e2da 1903 if (new_size <= i_size_read(vi))
1da177e4 1904 goto done;
1da177e4
LT
1905 /* Map, pin, and lock the (base) mft record. */
1906 if (!NInoAttr(ni))
1907 base_ni = ni;
1908 else
1909 base_ni = ni->ext.base_ntfs_ino;
1910 m = map_mft_record(base_ni);
1911 if (IS_ERR(m)) {
1912 err = PTR_ERR(m);
1913 m = NULL;
1914 ctx = NULL;
1915 goto err_out;
1916 }
1917 ctx = ntfs_attr_get_search_ctx(base_ni, m);
1918 if (unlikely(!ctx)) {
1919 err = -ENOMEM;
1920 goto err_out;
1921 }
1922 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1923 CASE_SENSITIVE, 0, NULL, 0, ctx);
1924 if (unlikely(err)) {
1925 if (err == -ENOENT)
1926 err = -EIO;
1927 goto err_out;
1928 }
1929 m = ctx->mrec;
1930 a = ctx->attr;
1931 /* The total length of the attribute value. */
1932 attr_len = le32_to_cpu(a->data.resident.value_length);
946929d8 1933 /* Fix an eventual previous failure of ntfs_commit_write(). */
f40661be
AA
1934 i_size = i_size_read(vi);
1935 if (unlikely(attr_len > i_size)) {
1936 attr_len = i_size;
946929d8 1937 a->data.resident.value_length = cpu_to_le32(attr_len);
946929d8 1938 }
946929d8
AA
1939 /* If we do not need to resize the attribute allocation we are done. */
1940 if (new_size <= attr_len)
1941 goto done_unm;
1da177e4
LT
1942 /* Check if new size is allowed in $AttrDef. */
1943 err = ntfs_attr_size_bounds_check(vol, ni->type, new_size);
1944 if (unlikely(err)) {
1945 if (err == -ERANGE) {
1946 ntfs_error(vol->sb, "Write would cause the inode "
1947 "0x%lx to exceed the maximum size for "
1948 "its attribute type (0x%x). Aborting "
1949 "write.", vi->i_ino,
1950 le32_to_cpu(ni->type));
1951 } else {
1952 ntfs_error(vol->sb, "Inode 0x%lx has unknown "
1953 "attribute type 0x%x. Aborting "
1954 "write.", vi->i_ino,
1955 le32_to_cpu(ni->type));
1956 err = -EIO;
1957 }
1958 goto err_out2;
1959 }
1960 /*
1961 * Extend the attribute record to be able to store the new attribute
1962 * size.
1963 */
1964 if (new_size >= vol->mft_record_size || ntfs_attr_record_resize(m, a,
1965 le16_to_cpu(a->data.resident.value_offset) +
1966 new_size)) {
1967 /* Not enough space in the mft record. */
1968 ntfs_error(vol->sb, "Not enough space in the mft record for "
1969 "the resized attribute value. This is not "
1970 "supported yet. Aborting write.");
1971 err = -EOPNOTSUPP;
1972 goto err_out2;
1973 }
1974 /*
1975 * We have enough space in the mft record to fit the write. This
1976 * implies the attribute is smaller than the mft record and hence the
1977 * attribute must be in a single page and hence page->index must be 0.
1978 */
1979 BUG_ON(page->index);
1980 /*
1981 * If the beginning of the write is past the old size, enlarge the
1982 * attribute value up to the beginning of the write and fill it with
1983 * zeroes.
1984 */
1985 if (from > attr_len) {
1986 memset((u8*)a + le16_to_cpu(a->data.resident.value_offset) +
1987 attr_len, 0, from - attr_len);
1988 a->data.resident.value_length = cpu_to_le32(from);
1989 /* Zero the corresponding area in the page as well. */
1990 if (PageUptodate(page)) {
1991 kaddr = kmap_atomic(page, KM_USER0);
1992 memset(kaddr + attr_len, 0, from - attr_len);
1993 kunmap_atomic(kaddr, KM_USER0);
1994 flush_dcache_page(page);
1995 }
1996 }
1997 flush_dcache_mft_record_page(ctx->ntfs_ino);
1998 mark_mft_record_dirty(ctx->ntfs_ino);
946929d8 1999done_unm:
1da177e4
LT
2000 ntfs_attr_put_search_ctx(ctx);
2001 unmap_mft_record(base_ni);
2002 /*
2003 * Because resident attributes are handled by memcpy() to/from the
2004 * corresponding MFT record, and because this form of i/o is byte
2005 * aligned rather than block aligned, there is no need to bring the
2006 * page uptodate here as in the non-resident case where we need to
2007 * bring the buffers straddled by the write uptodate before
2008 * generic_file_write() does the copying from userspace.
2009 *
2010 * We thus defer the uptodate bringing of the page region outside the
2011 * region written to to ntfs_commit_write(), which makes the code
2012 * simpler and saves one atomic kmap which is good.
2013 */
2014done:
2015 ntfs_debug("Done.");
2016 return 0;
2017err_out:
2018 if (err == -ENOMEM)
2019 ntfs_warning(vi->i_sb, "Error allocating memory required to "
2020 "prepare the write.");
2021 else {
2022 ntfs_error(vi->i_sb, "Resident attribute prepare write failed "
2023 "with error %i.", err);
2024 NVolSetErrors(vol);
2025 make_bad_inode(vi);
2026 }
2027err_out2:
2028 if (ctx)
2029 ntfs_attr_put_search_ctx(ctx);
2030 if (m)
2031 unmap_mft_record(base_ni);
2032 return err;
2033}
2034
2035/**
2036 * ntfs_commit_nonresident_write -
2037 *
2038 */
2039static int ntfs_commit_nonresident_write(struct page *page,
2040 unsigned from, unsigned to)
2041{
2042 s64 pos = ((s64)page->index << PAGE_CACHE_SHIFT) + to;
2043 struct inode *vi = page->mapping->host;
2044 struct buffer_head *bh, *head;
2045 unsigned int block_start, block_end, blocksize;
2046 BOOL partial;
2047
2048 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
2049 "0x%lx, from = %u, to = %u.", vi->i_ino,
2050 NTFS_I(vi)->type, page->index, from, to);
2051 blocksize = 1 << vi->i_blkbits;
2052
2053 // FIXME: We need a whole slew of special cases in here for compressed
2054 // files for example...
2055 // For now, we know ntfs_prepare_write() would have failed so we can't
2056 // get here in any of the cases which we have to special case, so we
2057 // are just a ripped off, unrolled generic_commit_write().
2058
2059 bh = head = page_buffers(page);
2060 block_start = 0;
2061 partial = FALSE;
2062 do {
2063 block_end = block_start + blocksize;
2064 if (block_end <= from || block_start >= to) {
2065 if (!buffer_uptodate(bh))
2066 partial = TRUE;
2067 } else {
2068 set_buffer_uptodate(bh);
2069 mark_buffer_dirty(bh);
2070 }
2071 } while (block_start = block_end, (bh = bh->b_this_page) != head);
2072 /*
2073 * If this is a partial write which happened to make all buffers
2074 * uptodate then we can optimize away a bogus ->readpage() for the next
2075 * read(). Here we 'discover' whether the page went uptodate as a
2076 * result of this (potentially partial) write.
2077 */
2078 if (!partial)
2079 SetPageUptodate(page);
2080 /*
2081 * Not convinced about this at all. See disparity comment above. For
2082 * now we know ntfs_prepare_write() would have failed in the write
2083 * exceeds i_size case, so this will never trigger which is fine.
2084 */
07a4e2da 2085 if (pos > i_size_read(vi)) {
1da177e4
LT
2086 ntfs_error(vi->i_sb, "Writing beyond the existing file size is "
2087 "not supported yet. Sorry.");
2088 return -EOPNOTSUPP;
2089 // vi->i_size = pos;
2090 // mark_inode_dirty(vi);
2091 }
2092 ntfs_debug("Done.");
2093 return 0;
2094}
2095
2096/**
2097 * ntfs_commit_write - commit the received data
2098 *
2099 * This is called from generic_file_write() with i_sem held on the inode
2100 * (@page->mapping->host). The @page is locked but not kmap()ped. The source
2101 * data has already been copied into the @page. ntfs_prepare_write() has been
2102 * called before the data copied and it returned success so we can take the
2103 * results of various BUG checks and some error handling for granted.
2104 *
2105 * Need to mark modified blocks dirty so they get written out later when
2106 * ntfs_writepage() is invoked by the VM.
2107 *
2108 * Return 0 on success or -errno on error.
2109 *
2110 * Should be using generic_commit_write(). This marks buffers uptodate and
2111 * dirty, sets the page uptodate if all buffers in the page are uptodate, and
2112 * updates i_size if the end of io is beyond i_size. In that case, it also
2113 * marks the inode dirty.
2114 *
2115 * Cannot use generic_commit_write() due to ntfs specialities but can look at
2116 * it for implementation guidance.
2117 *
2118 * If things have gone as outlined in ntfs_prepare_write(), then we do not
2119 * need to do any page content modifications here at all, except in the write
2120 * to resident attribute case, where we need to do the uptodate bringing here
2121 * which we combine with the copying into the mft record which means we save
2122 * one atomic kmap.
2123 */
2124static int ntfs_commit_write(struct file *file, struct page *page,
2125 unsigned from, unsigned to)
2126{
2127 struct inode *vi = page->mapping->host;
2128 ntfs_inode *base_ni, *ni = NTFS_I(vi);
2129 char *kaddr, *kattr;
2130 ntfs_attr_search_ctx *ctx;
2131 MFT_RECORD *m;
2132 ATTR_RECORD *a;
2133 u32 attr_len;
2134 int err;
2135
2136 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
2137 "0x%lx, from = %u, to = %u.", vi->i_ino, ni->type,
2138 page->index, from, to);
2139 /* If the attribute is not resident, deal with it elsewhere. */
2140 if (NInoNonResident(ni)) {
2141 /* Only unnamed $DATA attributes can be compressed/encrypted. */
2142 if (ni->type == AT_DATA && !ni->name_len) {
2143 /* Encrypted files need separate handling. */
2144 if (NInoEncrypted(ni)) {
2145 // We never get here at present!
2146 BUG();
2147 }
2148 /* Compressed data streams are handled in compress.c. */
2149 if (NInoCompressed(ni)) {
2150 // TODO: Implement this!
2151 // return ntfs_write_compressed_block(page);
2152 // We never get here at present!
2153 BUG();
2154 }
2155 }
2156 /* Normal data stream. */
2157 return ntfs_commit_nonresident_write(page, from, to);
2158 }
2159 /*
2160 * Attribute is resident, implying it is not compressed, encrypted, or
2161 * sparse.
2162 */
2163 if (!NInoAttr(ni))
2164 base_ni = ni;
2165 else
2166 base_ni = ni->ext.base_ntfs_ino;
2167 /* Map, pin, and lock the mft record. */
2168 m = map_mft_record(base_ni);
2169 if (IS_ERR(m)) {
2170 err = PTR_ERR(m);
2171 m = NULL;
2172 ctx = NULL;
2173 goto err_out;
2174 }
2175 ctx = ntfs_attr_get_search_ctx(base_ni, m);
2176 if (unlikely(!ctx)) {
2177 err = -ENOMEM;
2178 goto err_out;
2179 }
2180 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
2181 CASE_SENSITIVE, 0, NULL, 0, ctx);
2182 if (unlikely(err)) {
2183 if (err == -ENOENT)
2184 err = -EIO;
2185 goto err_out;
2186 }
2187 a = ctx->attr;
2188 /* The total length of the attribute value. */
2189 attr_len = le32_to_cpu(a->data.resident.value_length);
2190 BUG_ON(from > attr_len);
2191 kattr = (u8*)a + le16_to_cpu(a->data.resident.value_offset);
2192 kaddr = kmap_atomic(page, KM_USER0);
2193 /* Copy the received data from the page to the mft record. */
2194 memcpy(kattr + from, kaddr + from, to - from);
2195 /* Update the attribute length if necessary. */
2196 if (to > attr_len) {
2197 attr_len = to;
2198 a->data.resident.value_length = cpu_to_le32(attr_len);
2199 }
2200 /*
2201 * If the page is not uptodate, bring the out of bounds area(s)
2202 * uptodate by copying data from the mft record to the page.
2203 */
2204 if (!PageUptodate(page)) {
2205 if (from > 0)
2206 memcpy(kaddr, kattr, from);
2207 if (to < attr_len)
2208 memcpy(kaddr + to, kattr + to, attr_len - to);
2209 /* Zero the region outside the end of the attribute value. */
2210 if (attr_len < PAGE_CACHE_SIZE)
2211 memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
2212 /*
2213 * The probability of not having done any of the above is
2214 * extremely small, so we just flush unconditionally.
2215 */
2216 flush_dcache_page(page);
2217 SetPageUptodate(page);
2218 }
2219 kunmap_atomic(kaddr, KM_USER0);
2220 /* Update i_size if necessary. */
07a4e2da
AA
2221 if (i_size_read(vi) < attr_len) {
2222 unsigned long flags;
2223
2224 write_lock_irqsave(&ni->size_lock, flags);
1da177e4
LT
2225 ni->allocated_size = ni->initialized_size = attr_len;
2226 i_size_write(vi, attr_len);
07a4e2da 2227 write_unlock_irqrestore(&ni->size_lock, flags);
1da177e4
LT
2228 }
2229 /* Mark the mft record dirty, so it gets written back. */
2230 flush_dcache_mft_record_page(ctx->ntfs_ino);
2231 mark_mft_record_dirty(ctx->ntfs_ino);
2232 ntfs_attr_put_search_ctx(ctx);
2233 unmap_mft_record(base_ni);
2234 ntfs_debug("Done.");
2235 return 0;
2236err_out:
2237 if (err == -ENOMEM) {
2238 ntfs_warning(vi->i_sb, "Error allocating memory required to "
2239 "commit the write.");
2240 if (PageUptodate(page)) {
2241 ntfs_warning(vi->i_sb, "Page is uptodate, setting "
2242 "dirty so the write will be retried "
2243 "later on by the VM.");
2244 /*
2245 * Put the page on mapping->dirty_pages, but leave its
2246 * buffers' dirty state as-is.
2247 */
2248 __set_page_dirty_nobuffers(page);
2249 err = 0;
2250 } else
2251 ntfs_error(vi->i_sb, "Page is not uptodate. Written "
2252 "data has been lost.");
2253 } else {
2254 ntfs_error(vi->i_sb, "Resident attribute commit write failed "
2255 "with error %i.", err);
2256 NVolSetErrors(ni->vol);
2257 make_bad_inode(vi);
2258 }
2259 if (ctx)
2260 ntfs_attr_put_search_ctx(ctx);
2261 if (m)
2262 unmap_mft_record(base_ni);
2263 return err;
2264}
2265
2266#endif /* NTFS_RW */
2267
2268/**
2269 * ntfs_aops - general address space operations for inodes and attributes
2270 */
2271struct address_space_operations ntfs_aops = {
2272 .readpage = ntfs_readpage, /* Fill page with data. */
2273 .sync_page = block_sync_page, /* Currently, just unplugs the
2274 disk request queue. */
2275#ifdef NTFS_RW
2276 .writepage = ntfs_writepage, /* Write dirty page to disk. */
2277 .prepare_write = ntfs_prepare_write, /* Prepare page and buffers
2278 ready to receive data. */
2279 .commit_write = ntfs_commit_write, /* Commit received data. */
2280#endif /* NTFS_RW */
2281};
2282
2283/**
2284 * ntfs_mst_aops - general address space operations for mst protecteed inodes
2285 * and attributes
2286 */
2287struct address_space_operations ntfs_mst_aops = {
2288 .readpage = ntfs_readpage, /* Fill page with data. */
2289 .sync_page = block_sync_page, /* Currently, just unplugs the
2290 disk request queue. */
2291#ifdef NTFS_RW
2292 .writepage = ntfs_writepage, /* Write dirty page to disk. */
2293 .set_page_dirty = __set_page_dirty_nobuffers, /* Set the page dirty
2294 without touching the buffers
2295 belonging to the page. */
2296#endif /* NTFS_RW */
2297};
2298
2299#ifdef NTFS_RW
2300
2301/**
2302 * mark_ntfs_record_dirty - mark an ntfs record dirty
2303 * @page: page containing the ntfs record to mark dirty
2304 * @ofs: byte offset within @page at which the ntfs record begins
2305 *
2306 * Set the buffers and the page in which the ntfs record is located dirty.
2307 *
2308 * The latter also marks the vfs inode the ntfs record belongs to dirty
2309 * (I_DIRTY_PAGES only).
2310 *
2311 * If the page does not have buffers, we create them and set them uptodate.
2312 * The page may not be locked which is why we need to handle the buffers under
2313 * the mapping->private_lock. Once the buffers are marked dirty we no longer
2314 * need the lock since try_to_free_buffers() does not free dirty buffers.
2315 */
2316void mark_ntfs_record_dirty(struct page *page, const unsigned int ofs) {
2317 struct address_space *mapping = page->mapping;
2318 ntfs_inode *ni = NTFS_I(mapping->host);
2319 struct buffer_head *bh, *head, *buffers_to_free = NULL;
2320 unsigned int end, bh_size, bh_ofs;
2321
2322 BUG_ON(!PageUptodate(page));
2323 end = ofs + ni->itype.index.block_size;
2324 bh_size = 1 << VFS_I(ni)->i_blkbits;
2325 spin_lock(&mapping->private_lock);
2326 if (unlikely(!page_has_buffers(page))) {
2327 spin_unlock(&mapping->private_lock);
2328 bh = head = alloc_page_buffers(page, bh_size, 1);
2329 spin_lock(&mapping->private_lock);
2330 if (likely(!page_has_buffers(page))) {
2331 struct buffer_head *tail;
2332
2333 do {
2334 set_buffer_uptodate(bh);
2335 tail = bh;
2336 bh = bh->b_this_page;
2337 } while (bh);
2338 tail->b_this_page = head;
2339 attach_page_buffers(page, head);
2340 } else
2341 buffers_to_free = bh;
2342 }
2343 bh = head = page_buffers(page);
2344 do {
2345 bh_ofs = bh_offset(bh);
2346 if (bh_ofs + bh_size <= ofs)
2347 continue;
2348 if (unlikely(bh_ofs >= end))
2349 break;
2350 set_buffer_dirty(bh);
2351 } while ((bh = bh->b_this_page) != head);
2352 spin_unlock(&mapping->private_lock);
2353 __set_page_dirty_nobuffers(page);
2354 if (unlikely(buffers_to_free)) {
2355 do {
2356 bh = buffers_to_free->b_this_page;
2357 free_buffer_head(buffers_to_free);
2358 buffers_to_free = bh;
2359 } while (buffers_to_free);
2360 }
2361}
2362
2363#endif /* NTFS_RW */