Merge branch 'master' of /usr/src/ntfs-2.6/
[linux-2.6-block.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 *
b6ad6c52 5 * Copyright (c) 2001-2005 Anton Altaparmakov
1da177e4
LT
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>
b4012a98 30#include <linux/bit_spinlock.h>
1da177e4
LT
31
32#include "aops.h"
33#include "attrib.h"
34#include "debug.h"
35#include "inode.h"
36#include "mft.h"
37#include "runlist.h"
38#include "types.h"
39#include "ntfs.h"
40
41/**
42 * ntfs_end_buffer_async_read - async io completion for reading attributes
43 * @bh: buffer head on which io is completed
44 * @uptodate: whether @bh is now uptodate or not
45 *
46 * Asynchronous I/O completion handler for reading pages belonging to the
47 * attribute address space of an inode. The inodes can either be files or
48 * directories or they can be fake inodes describing some attribute.
49 *
50 * If NInoMstProtected(), perform the post read mst fixups when all IO on the
51 * page has been completed and mark the page uptodate or set the error bit on
52 * the page. To determine the size of the records that need fixing up, we
53 * cheat a little bit by setting the index_block_size in ntfs_inode to the ntfs
54 * record size, and index_block_size_bits, to the log(base 2) of the ntfs
55 * record size.
56 */
57static void ntfs_end_buffer_async_read(struct buffer_head *bh, int uptodate)
58{
1da177e4 59 unsigned long flags;
e604635c 60 struct buffer_head *first, *tmp;
1da177e4 61 struct page *page;
f6098cf4 62 struct inode *vi;
1da177e4
LT
63 ntfs_inode *ni;
64 int page_uptodate = 1;
65
66 page = bh->b_page;
f6098cf4
AA
67 vi = page->mapping->host;
68 ni = NTFS_I(vi);
1da177e4
LT
69
70 if (likely(uptodate)) {
f6098cf4
AA
71 loff_t i_size;
72 s64 file_ofs, init_size;
1da177e4
LT
73
74 set_buffer_uptodate(bh);
75
76 file_ofs = ((s64)page->index << PAGE_CACHE_SHIFT) +
77 bh_offset(bh);
07a4e2da 78 read_lock_irqsave(&ni->size_lock, flags);
f6098cf4
AA
79 init_size = ni->initialized_size;
80 i_size = i_size_read(vi);
07a4e2da 81 read_unlock_irqrestore(&ni->size_lock, flags);
f6098cf4
AA
82 if (unlikely(init_size > i_size)) {
83 /* Race with shrinking truncate. */
84 init_size = i_size;
85 }
1da177e4 86 /* Check for the current buffer head overflowing. */
f6098cf4
AA
87 if (unlikely(file_ofs + bh->b_size > init_size)) {
88 u8 *kaddr;
89 int ofs;
90
91 ofs = 0;
92 if (file_ofs < init_size)
93 ofs = init_size - file_ofs;
94 kaddr = kmap_atomic(page, KM_BIO_SRC_IRQ);
95 memset(kaddr + bh_offset(bh) + ofs, 0,
96 bh->b_size - ofs);
97 kunmap_atomic(kaddr, KM_BIO_SRC_IRQ);
1da177e4 98 flush_dcache_page(page);
1da177e4
LT
99 }
100 } else {
101 clear_buffer_uptodate(bh);
e604635c 102 SetPageError(page);
f6098cf4
AA
103 ntfs_error(ni->vol->sb, "Buffer I/O error, logical block "
104 "0x%llx.", (unsigned long long)bh->b_blocknr);
1da177e4 105 }
e604635c
AA
106 first = page_buffers(page);
107 local_irq_save(flags);
108 bit_spin_lock(BH_Uptodate_Lock, &first->b_state);
1da177e4
LT
109 clear_buffer_async_read(bh);
110 unlock_buffer(bh);
111 tmp = bh;
112 do {
113 if (!buffer_uptodate(tmp))
114 page_uptodate = 0;
115 if (buffer_async_read(tmp)) {
116 if (likely(buffer_locked(tmp)))
117 goto still_busy;
118 /* Async buffers must be locked. */
119 BUG();
120 }
121 tmp = tmp->b_this_page;
122 } while (tmp != bh);
e604635c
AA
123 bit_spin_unlock(BH_Uptodate_Lock, &first->b_state);
124 local_irq_restore(flags);
1da177e4
LT
125 /*
126 * If none of the buffers had errors then we can set the page uptodate,
127 * but we first have to perform the post read mst fixups, if the
128 * attribute is mst protected, i.e. if NInoMstProteced(ni) is true.
129 * Note we ignore fixup errors as those are detected when
130 * map_mft_record() is called which gives us per record granularity
131 * rather than per page granularity.
132 */
133 if (!NInoMstProtected(ni)) {
134 if (likely(page_uptodate && !PageError(page)))
135 SetPageUptodate(page);
136 } else {
f6098cf4 137 u8 *kaddr;
1da177e4
LT
138 unsigned int i, recs;
139 u32 rec_size;
140
141 rec_size = ni->itype.index.block_size;
142 recs = PAGE_CACHE_SIZE / rec_size;
143 /* Should have been verified before we got here... */
144 BUG_ON(!recs);
f6098cf4 145 kaddr = kmap_atomic(page, KM_BIO_SRC_IRQ);
1da177e4 146 for (i = 0; i < recs; i++)
f6098cf4 147 post_read_mst_fixup((NTFS_RECORD*)(kaddr +
1da177e4 148 i * rec_size), rec_size);
f6098cf4 149 kunmap_atomic(kaddr, KM_BIO_SRC_IRQ);
1da177e4 150 flush_dcache_page(page);
b6ad6c52 151 if (likely(page_uptodate && !PageError(page)))
1da177e4
LT
152 SetPageUptodate(page);
153 }
154 unlock_page(page);
155 return;
156still_busy:
e604635c
AA
157 bit_spin_unlock(BH_Uptodate_Lock, &first->b_state);
158 local_irq_restore(flags);
1da177e4
LT
159 return;
160}
161
162/**
163 * ntfs_read_block - fill a @page of an address space with data
164 * @page: page cache page to fill with data
165 *
166 * Fill the page @page of the address space belonging to the @page->host inode.
167 * We read each buffer asynchronously and when all buffers are read in, our io
168 * completion handler ntfs_end_buffer_read_async(), if required, automatically
169 * applies the mst fixups to the page before finally marking it uptodate and
170 * unlocking it.
171 *
172 * We only enforce allocated_size limit because i_size is checked for in
173 * generic_file_read().
174 *
175 * Return 0 on success and -errno on error.
176 *
177 * Contains an adapted version of fs/buffer.c::block_read_full_page().
178 */
179static int ntfs_read_block(struct page *page)
180{
f6098cf4 181 loff_t i_size;
1da177e4
LT
182 VCN vcn;
183 LCN lcn;
f6098cf4
AA
184 s64 init_size;
185 struct inode *vi;
1da177e4
LT
186 ntfs_inode *ni;
187 ntfs_volume *vol;
188 runlist_element *rl;
189 struct buffer_head *bh, *head, *arr[MAX_BUF_PER_PAGE];
190 sector_t iblock, lblock, zblock;
07a4e2da 191 unsigned long flags;
1da177e4
LT
192 unsigned int blocksize, vcn_ofs;
193 int i, nr;
194 unsigned char blocksize_bits;
195
f6098cf4
AA
196 vi = page->mapping->host;
197 ni = NTFS_I(vi);
1da177e4
LT
198 vol = ni->vol;
199
200 /* $MFT/$DATA must have its complete runlist in memory at all times. */
201 BUG_ON(!ni->runlist.rl && !ni->mft_no && !NInoAttr(ni));
202
203 blocksize_bits = VFS_I(ni)->i_blkbits;
204 blocksize = 1 << blocksize_bits;
205
a01ac532 206 if (!page_has_buffers(page)) {
1da177e4 207 create_empty_buffers(page, blocksize, 0);
a01ac532
AA
208 if (unlikely(!page_has_buffers(page))) {
209 unlock_page(page);
210 return -ENOMEM;
211 }
1da177e4 212 }
a01ac532
AA
213 bh = head = page_buffers(page);
214 BUG_ON(!bh);
1da177e4 215
f6098cf4
AA
216 /*
217 * We may be racing with truncate. To avoid some of the problems we
218 * now take a snapshot of the various sizes and use those for the whole
219 * of the function. In case of an extending truncate it just means we
220 * may leave some buffers unmapped which are now allocated. This is
221 * not a problem since these buffers will just get mapped when a write
222 * occurs. In case of a shrinking truncate, we will detect this later
223 * on due to the runlist being incomplete and if the page is being
224 * fully truncated, truncate will throw it away as soon as we unlock
225 * it so no need to worry what we do with it.
226 */
1da177e4 227 iblock = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
07a4e2da 228 read_lock_irqsave(&ni->size_lock, flags);
1da177e4 229 lblock = (ni->allocated_size + blocksize - 1) >> blocksize_bits;
f6098cf4
AA
230 init_size = ni->initialized_size;
231 i_size = i_size_read(vi);
07a4e2da 232 read_unlock_irqrestore(&ni->size_lock, flags);
f6098cf4
AA
233 if (unlikely(init_size > i_size)) {
234 /* Race with shrinking truncate. */
235 init_size = i_size;
236 }
237 zblock = (init_size + blocksize - 1) >> blocksize_bits;
1da177e4
LT
238
239 /* Loop through all the buffers in the page. */
240 rl = NULL;
241 nr = i = 0;
242 do {
243 u8 *kaddr;
8273d5d4 244 int err;
1da177e4
LT
245
246 if (unlikely(buffer_uptodate(bh)))
247 continue;
248 if (unlikely(buffer_mapped(bh))) {
249 arr[nr++] = bh;
250 continue;
251 }
8273d5d4 252 err = 0;
1da177e4
LT
253 bh->b_bdev = vol->sb->s_bdev;
254 /* Is the block within the allowed limits? */
255 if (iblock < lblock) {
256 BOOL is_retry = FALSE;
257
258 /* Convert iblock into corresponding vcn and offset. */
259 vcn = (VCN)iblock << blocksize_bits >>
260 vol->cluster_size_bits;
261 vcn_ofs = ((VCN)iblock << blocksize_bits) &
262 vol->cluster_size_mask;
263 if (!rl) {
264lock_retry_remap:
265 down_read(&ni->runlist.lock);
266 rl = ni->runlist.rl;
267 }
268 if (likely(rl != NULL)) {
269 /* Seek to element containing target vcn. */
270 while (rl->length && rl[1].vcn <= vcn)
271 rl++;
272 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
273 } else
274 lcn = LCN_RL_NOT_MAPPED;
275 /* Successful remap. */
276 if (lcn >= 0) {
277 /* Setup buffer head to correct block. */
278 bh->b_blocknr = ((lcn << vol->cluster_size_bits)
279 + vcn_ofs) >> blocksize_bits;
280 set_buffer_mapped(bh);
281 /* Only read initialized data blocks. */
282 if (iblock < zblock) {
283 arr[nr++] = bh;
284 continue;
285 }
286 /* Fully non-initialized data block, zero it. */
287 goto handle_zblock;
288 }
289 /* It is a hole, need to zero it. */
290 if (lcn == LCN_HOLE)
291 goto handle_hole;
292 /* If first try and runlist unmapped, map and retry. */
293 if (!is_retry && lcn == LCN_RL_NOT_MAPPED) {
1da177e4
LT
294 is_retry = TRUE;
295 /*
296 * Attempt to map runlist, dropping lock for
297 * the duration.
298 */
299 up_read(&ni->runlist.lock);
300 err = ntfs_map_runlist(ni, vcn);
301 if (likely(!err))
302 goto lock_retry_remap;
303 rl = NULL;
9f993fe4
AA
304 } else if (!rl)
305 up_read(&ni->runlist.lock);
8273d5d4
AA
306 /*
307 * If buffer is outside the runlist, treat it as a
308 * hole. This can happen due to concurrent truncate
309 * for example.
310 */
311 if (err == -ENOENT || lcn == LCN_ENOENT) {
312 err = 0;
313 goto handle_hole;
314 }
1da177e4 315 /* Hard error, zero out region. */
8273d5d4
AA
316 if (!err)
317 err = -EIO;
1da177e4
LT
318 bh->b_blocknr = -1;
319 SetPageError(page);
320 ntfs_error(vol->sb, "Failed to read from inode 0x%lx, "
321 "attribute type 0x%x, vcn 0x%llx, "
322 "offset 0x%x because its location on "
323 "disk could not be determined%s "
8273d5d4 324 "(error code %i).", ni->mft_no,
1da177e4
LT
325 ni->type, (unsigned long long)vcn,
326 vcn_ofs, is_retry ? " even after "
8273d5d4 327 "retrying" : "", err);
1da177e4
LT
328 }
329 /*
330 * Either iblock was outside lblock limits or
331 * ntfs_rl_vcn_to_lcn() returned error. Just zero that portion
332 * of the page and set the buffer uptodate.
333 */
334handle_hole:
335 bh->b_blocknr = -1UL;
336 clear_buffer_mapped(bh);
337handle_zblock:
338 kaddr = kmap_atomic(page, KM_USER0);
339 memset(kaddr + i * blocksize, 0, blocksize);
1da177e4 340 kunmap_atomic(kaddr, KM_USER0);
8273d5d4
AA
341 flush_dcache_page(page);
342 if (likely(!err))
343 set_buffer_uptodate(bh);
1da177e4
LT
344 } while (i++, iblock++, (bh = bh->b_this_page) != head);
345
346 /* Release the lock if we took it. */
347 if (rl)
348 up_read(&ni->runlist.lock);
349
350 /* Check we have at least one buffer ready for i/o. */
351 if (nr) {
352 struct buffer_head *tbh;
353
354 /* Lock the buffers. */
355 for (i = 0; i < nr; i++) {
356 tbh = arr[i];
357 lock_buffer(tbh);
358 tbh->b_end_io = ntfs_end_buffer_async_read;
359 set_buffer_async_read(tbh);
360 }
361 /* Finally, start i/o on the buffers. */
362 for (i = 0; i < nr; i++) {
363 tbh = arr[i];
364 if (likely(!buffer_uptodate(tbh)))
365 submit_bh(READ, tbh);
366 else
367 ntfs_end_buffer_async_read(tbh, 1);
368 }
369 return 0;
370 }
371 /* No i/o was scheduled on any of the buffers. */
372 if (likely(!PageError(page)))
373 SetPageUptodate(page);
374 else /* Signal synchronous i/o error. */
375 nr = -EIO;
376 unlock_page(page);
377 return nr;
378}
379
380/**
381 * ntfs_readpage - fill a @page of a @file with data from the device
382 * @file: open file to which the page @page belongs or NULL
383 * @page: page cache page to fill with data
384 *
385 * For non-resident attributes, ntfs_readpage() fills the @page of the open
386 * file @file by calling the ntfs version of the generic block_read_full_page()
387 * function, ntfs_read_block(), which in turn creates and reads in the buffers
388 * associated with the page asynchronously.
389 *
390 * For resident attributes, OTOH, ntfs_readpage() fills @page by copying the
391 * data from the mft record (which at this stage is most likely in memory) and
392 * fills the remainder with zeroes. Thus, in this case, I/O is synchronous, as
393 * even if the mft record is not cached at this point in time, we need to wait
394 * for it to be read in before we can do the copy.
395 *
396 * Return 0 on success and -errno on error.
397 */
398static int ntfs_readpage(struct file *file, struct page *page)
399{
f6098cf4
AA
400 loff_t i_size;
401 struct inode *vi;
1da177e4
LT
402 ntfs_inode *ni, *base_ni;
403 u8 *kaddr;
404 ntfs_attr_search_ctx *ctx;
405 MFT_RECORD *mrec;
b6ad6c52 406 unsigned long flags;
1da177e4
LT
407 u32 attr_len;
408 int err = 0;
409
905685f6 410retry_readpage:
1da177e4
LT
411 BUG_ON(!PageLocked(page));
412 /*
413 * This can potentially happen because we clear PageUptodate() during
414 * ntfs_writepage() of MstProtected() attributes.
415 */
416 if (PageUptodate(page)) {
417 unlock_page(page);
418 return 0;
419 }
f6098cf4
AA
420 vi = page->mapping->host;
421 ni = NTFS_I(vi);
311120ec
AA
422 /*
423 * Only $DATA attributes can be encrypted and only unnamed $DATA
424 * attributes can be compressed. Index root can have the flags set but
425 * this means to create compressed/encrypted files, not that the
4e64c886
AA
426 * attribute is compressed/encrypted. Note we need to check for
427 * AT_INDEX_ALLOCATION since this is the type of both directory and
428 * index inodes.
311120ec 429 */
4e64c886 430 if (ni->type != AT_INDEX_ALLOCATION) {
311120ec
AA
431 /* If attribute is encrypted, deny access, just like NT4. */
432 if (NInoEncrypted(ni)) {
433 BUG_ON(ni->type != AT_DATA);
434 err = -EACCES;
435 goto err_out;
436 }
437 /* Compressed data streams are handled in compress.c. */
438 if (NInoNonResident(ni) && NInoCompressed(ni)) {
439 BUG_ON(ni->type != AT_DATA);
440 BUG_ON(ni->name_len);
441 return ntfs_read_compressed_block(page);
442 }
443 }
1da177e4
LT
444 /* NInoNonResident() == NInoIndexAllocPresent() */
445 if (NInoNonResident(ni)) {
311120ec 446 /* Normal, non-resident data stream. */
1da177e4
LT
447 return ntfs_read_block(page);
448 }
449 /*
450 * Attribute is resident, implying it is not compressed or encrypted.
451 * This also means the attribute is smaller than an mft record and
452 * hence smaller than a page, so can simply zero out any pages with
311120ec
AA
453 * index above 0. Note the attribute can actually be marked compressed
454 * but if it is resident the actual data is not compressed so we are
455 * ok to ignore the compressed flag here.
1da177e4 456 */
b6ad6c52 457 if (unlikely(page->index > 0)) {
1da177e4
LT
458 kaddr = kmap_atomic(page, KM_USER0);
459 memset(kaddr, 0, PAGE_CACHE_SIZE);
460 flush_dcache_page(page);
461 kunmap_atomic(kaddr, KM_USER0);
462 goto done;
463 }
464 if (!NInoAttr(ni))
465 base_ni = ni;
466 else
467 base_ni = ni->ext.base_ntfs_ino;
468 /* Map, pin, and lock the mft record. */
469 mrec = map_mft_record(base_ni);
470 if (IS_ERR(mrec)) {
471 err = PTR_ERR(mrec);
472 goto err_out;
473 }
905685f6
AA
474 /*
475 * If a parallel write made the attribute non-resident, drop the mft
476 * record and retry the readpage.
477 */
478 if (unlikely(NInoNonResident(ni))) {
479 unmap_mft_record(base_ni);
480 goto retry_readpage;
481 }
1da177e4
LT
482 ctx = ntfs_attr_get_search_ctx(base_ni, mrec);
483 if (unlikely(!ctx)) {
484 err = -ENOMEM;
485 goto unm_err_out;
486 }
487 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
488 CASE_SENSITIVE, 0, NULL, 0, ctx);
489 if (unlikely(err))
490 goto put_unm_err_out;
491 attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
b6ad6c52
AA
492 read_lock_irqsave(&ni->size_lock, flags);
493 if (unlikely(attr_len > ni->initialized_size))
494 attr_len = ni->initialized_size;
f6098cf4 495 i_size = i_size_read(vi);
b6ad6c52 496 read_unlock_irqrestore(&ni->size_lock, flags);
f6098cf4
AA
497 if (unlikely(attr_len > i_size)) {
498 /* Race with shrinking truncate. */
499 attr_len = i_size;
500 }
1da177e4
LT
501 kaddr = kmap_atomic(page, KM_USER0);
502 /* Copy the data to the page. */
503 memcpy(kaddr, (u8*)ctx->attr +
504 le16_to_cpu(ctx->attr->data.resident.value_offset),
505 attr_len);
506 /* Zero the remainder of the page. */
507 memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
508 flush_dcache_page(page);
509 kunmap_atomic(kaddr, KM_USER0);
510put_unm_err_out:
511 ntfs_attr_put_search_ctx(ctx);
512unm_err_out:
513 unmap_mft_record(base_ni);
514done:
515 SetPageUptodate(page);
516err_out:
517 unlock_page(page);
518 return err;
519}
520
521#ifdef NTFS_RW
522
523/**
524 * ntfs_write_block - write a @page to the backing store
525 * @page: page cache page to write out
526 * @wbc: writeback control structure
527 *
528 * This function is for writing pages belonging to non-resident, non-mst
529 * protected attributes to their backing store.
530 *
531 * For a page with buffers, map and write the dirty buffers asynchronously
532 * under page writeback. For a page without buffers, create buffers for the
533 * page, then proceed as above.
534 *
535 * If a page doesn't have buffers the page dirty state is definitive. If a page
536 * does have buffers, the page dirty state is just a hint, and the buffer dirty
537 * state is definitive. (A hint which has rules: dirty buffers against a clean
538 * page is illegal. Other combinations are legal and need to be handled. In
539 * particular a dirty page containing clean buffers for example.)
540 *
541 * Return 0 on success and -errno on error.
542 *
543 * Based on ntfs_read_block() and __block_write_full_page().
544 */
545static int ntfs_write_block(struct page *page, struct writeback_control *wbc)
546{
547 VCN vcn;
548 LCN lcn;
07a4e2da
AA
549 s64 initialized_size;
550 loff_t i_size;
1da177e4
LT
551 sector_t block, dblock, iblock;
552 struct inode *vi;
553 ntfs_inode *ni;
554 ntfs_volume *vol;
555 runlist_element *rl;
556 struct buffer_head *bh, *head;
07a4e2da 557 unsigned long flags;
1da177e4
LT
558 unsigned int blocksize, vcn_ofs;
559 int err;
560 BOOL need_end_writeback;
561 unsigned char blocksize_bits;
562
563 vi = page->mapping->host;
564 ni = NTFS_I(vi);
565 vol = ni->vol;
566
567 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
568 "0x%lx.", ni->mft_no, ni->type, page->index);
569
570 BUG_ON(!NInoNonResident(ni));
571 BUG_ON(NInoMstProtected(ni));
572
573 blocksize_bits = vi->i_blkbits;
574 blocksize = 1 << blocksize_bits;
575
576 if (!page_has_buffers(page)) {
577 BUG_ON(!PageUptodate(page));
578 create_empty_buffers(page, blocksize,
579 (1 << BH_Uptodate) | (1 << BH_Dirty));
a01ac532
AA
580 if (unlikely(!page_has_buffers(page))) {
581 ntfs_warning(vol->sb, "Error allocating page "
582 "buffers. Redirtying page so we try "
583 "again later.");
584 /*
585 * Put the page back on mapping->dirty_pages, but leave
586 * its buffers' dirty state as-is.
587 */
588 redirty_page_for_writepage(wbc, page);
589 unlock_page(page);
590 return 0;
591 }
1da177e4
LT
592 }
593 bh = head = page_buffers(page);
a01ac532 594 BUG_ON(!bh);
1da177e4
LT
595
596 /* NOTE: Different naming scheme to ntfs_read_block()! */
597
598 /* The first block in the page. */
599 block = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
600
07a4e2da
AA
601 read_lock_irqsave(&ni->size_lock, flags);
602 i_size = i_size_read(vi);
603 initialized_size = ni->initialized_size;
604 read_unlock_irqrestore(&ni->size_lock, flags);
605
1da177e4 606 /* The first out of bounds block for the data size. */
07a4e2da 607 dblock = (i_size + blocksize - 1) >> blocksize_bits;
1da177e4
LT
608
609 /* The last (fully or partially) initialized block. */
07a4e2da 610 iblock = initialized_size >> blocksize_bits;
1da177e4
LT
611
612 /*
613 * Be very careful. We have no exclusion from __set_page_dirty_buffers
614 * here, and the (potentially unmapped) buffers may become dirty at
615 * any time. If a buffer becomes dirty here after we've inspected it
616 * then we just miss that fact, and the page stays dirty.
617 *
618 * Buffers outside i_size may be dirtied by __set_page_dirty_buffers;
619 * handle that here by just cleaning them.
620 */
621
622 /*
623 * Loop through all the buffers in the page, mapping all the dirty
624 * buffers to disk addresses and handling any aliases from the
625 * underlying block device's mapping.
626 */
627 rl = NULL;
628 err = 0;
629 do {
630 BOOL is_retry = FALSE;
631
632 if (unlikely(block >= dblock)) {
633 /*
634 * Mapped buffers outside i_size will occur, because
635 * this page can be outside i_size when there is a
636 * truncate in progress. The contents of such buffers
637 * were zeroed by ntfs_writepage().
638 *
639 * FIXME: What about the small race window where
640 * ntfs_writepage() has not done any clearing because
641 * the page was within i_size but before we get here,
642 * vmtruncate() modifies i_size?
643 */
644 clear_buffer_dirty(bh);
645 set_buffer_uptodate(bh);
646 continue;
647 }
648
649 /* Clean buffers are not written out, so no need to map them. */
650 if (!buffer_dirty(bh))
651 continue;
652
653 /* Make sure we have enough initialized size. */
654 if (unlikely((block >= iblock) &&
07a4e2da 655 (initialized_size < i_size))) {
1da177e4
LT
656 /*
657 * If this page is fully outside initialized size, zero
658 * out all pages between the current initialized size
659 * and the current page. Just use ntfs_readpage() to do
660 * the zeroing transparently.
661 */
662 if (block > iblock) {
663 // TODO:
664 // For each page do:
665 // - read_cache_page()
666 // Again for each page do:
667 // - wait_on_page_locked()
668 // - Check (PageUptodate(page) &&
669 // !PageError(page))
670 // Update initialized size in the attribute and
671 // in the inode.
672 // Again, for each page do:
673 // __set_page_dirty_buffers();
674 // page_cache_release()
675 // We don't need to wait on the writes.
676 // Update iblock.
677 }
678 /*
679 * The current page straddles initialized size. Zero
680 * all non-uptodate buffers and set them uptodate (and
681 * dirty?). Note, there aren't any non-uptodate buffers
682 * if the page is uptodate.
683 * FIXME: For an uptodate page, the buffers may need to
684 * be written out because they were not initialized on
685 * disk before.
686 */
687 if (!PageUptodate(page)) {
688 // TODO:
689 // Zero any non-uptodate buffers up to i_size.
690 // Set them uptodate and dirty.
691 }
692 // TODO:
693 // Update initialized size in the attribute and in the
694 // inode (up to i_size).
695 // Update iblock.
696 // FIXME: This is inefficient. Try to batch the two
697 // size changes to happen in one go.
698 ntfs_error(vol->sb, "Writing beyond initialized size "
699 "is not supported yet. Sorry.");
700 err = -EOPNOTSUPP;
701 break;
702 // Do NOT set_buffer_new() BUT DO clear buffer range
703 // outside write request range.
704 // set_buffer_uptodate() on complete buffers as well as
705 // set_buffer_dirty().
706 }
707
708 /* No need to map buffers that are already mapped. */
709 if (buffer_mapped(bh))
710 continue;
711
712 /* Unmapped, dirty buffer. Need to map it. */
713 bh->b_bdev = vol->sb->s_bdev;
714
715 /* Convert block into corresponding vcn and offset. */
716 vcn = (VCN)block << blocksize_bits;
717 vcn_ofs = vcn & vol->cluster_size_mask;
718 vcn >>= vol->cluster_size_bits;
719 if (!rl) {
720lock_retry_remap:
721 down_read(&ni->runlist.lock);
722 rl = ni->runlist.rl;
723 }
724 if (likely(rl != NULL)) {
725 /* Seek to element containing target vcn. */
726 while (rl->length && rl[1].vcn <= vcn)
727 rl++;
728 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
729 } else
730 lcn = LCN_RL_NOT_MAPPED;
731 /* Successful remap. */
732 if (lcn >= 0) {
733 /* Setup buffer head to point to correct block. */
734 bh->b_blocknr = ((lcn << vol->cluster_size_bits) +
735 vcn_ofs) >> blocksize_bits;
736 set_buffer_mapped(bh);
737 continue;
738 }
739 /* It is a hole, need to instantiate it. */
740 if (lcn == LCN_HOLE) {
8dcdebaf
AA
741 u8 *kaddr;
742 unsigned long *bpos, *bend;
743
744 /* Check if the buffer is zero. */
745 kaddr = kmap_atomic(page, KM_USER0);
746 bpos = (unsigned long *)(kaddr + bh_offset(bh));
747 bend = (unsigned long *)((u8*)bpos + blocksize);
748 do {
749 if (unlikely(*bpos))
750 break;
751 } while (likely(++bpos < bend));
752 kunmap_atomic(kaddr, KM_USER0);
753 if (bpos == bend) {
754 /*
755 * Buffer is zero and sparse, no need to write
756 * it.
757 */
758 bh->b_blocknr = -1;
759 clear_buffer_dirty(bh);
760 continue;
761 }
1da177e4
LT
762 // TODO: Instantiate the hole.
763 // clear_buffer_new(bh);
764 // unmap_underlying_metadata(bh->b_bdev, bh->b_blocknr);
765 ntfs_error(vol->sb, "Writing into sparse regions is "
766 "not supported yet. Sorry.");
767 err = -EOPNOTSUPP;
768 break;
769 }
770 /* If first try and runlist unmapped, map and retry. */
771 if (!is_retry && lcn == LCN_RL_NOT_MAPPED) {
772 is_retry = TRUE;
773 /*
774 * Attempt to map runlist, dropping lock for
775 * the duration.
776 */
777 up_read(&ni->runlist.lock);
778 err = ntfs_map_runlist(ni, vcn);
779 if (likely(!err))
780 goto lock_retry_remap;
781 rl = NULL;
9f993fe4
AA
782 } else if (!rl)
783 up_read(&ni->runlist.lock);
8273d5d4
AA
784 /*
785 * If buffer is outside the runlist, truncate has cut it out
786 * of the runlist. Just clean and clear the buffer and set it
787 * uptodate so it can get discarded by the VM.
788 */
789 if (err == -ENOENT || lcn == LCN_ENOENT) {
790 u8 *kaddr;
791
792 bh->b_blocknr = -1;
793 clear_buffer_dirty(bh);
794 kaddr = kmap_atomic(page, KM_USER0);
795 memset(kaddr + bh_offset(bh), 0, blocksize);
796 kunmap_atomic(kaddr, KM_USER0);
797 flush_dcache_page(page);
798 set_buffer_uptodate(bh);
799 err = 0;
800 continue;
801 }
1da177e4 802 /* Failed to map the buffer, even after retrying. */
8273d5d4
AA
803 if (!err)
804 err = -EIO;
1da177e4
LT
805 bh->b_blocknr = -1;
806 ntfs_error(vol->sb, "Failed to write to inode 0x%lx, "
807 "attribute type 0x%x, vcn 0x%llx, offset 0x%x "
808 "because its location on disk could not be "
8273d5d4 809 "determined%s (error code %i).", ni->mft_no,
1da177e4
LT
810 ni->type, (unsigned long long)vcn,
811 vcn_ofs, is_retry ? " even after "
8273d5d4 812 "retrying" : "", err);
1da177e4
LT
813 break;
814 } while (block++, (bh = bh->b_this_page) != head);
815
816 /* Release the lock if we took it. */
817 if (rl)
818 up_read(&ni->runlist.lock);
819
820 /* For the error case, need to reset bh to the beginning. */
821 bh = head;
822
54b02eb0 823 /* Just an optimization, so ->readpage() is not called later. */
1da177e4
LT
824 if (unlikely(!PageUptodate(page))) {
825 int uptodate = 1;
826 do {
827 if (!buffer_uptodate(bh)) {
828 uptodate = 0;
829 bh = head;
830 break;
831 }
832 } while ((bh = bh->b_this_page) != head);
833 if (uptodate)
834 SetPageUptodate(page);
835 }
836
837 /* Setup all mapped, dirty buffers for async write i/o. */
838 do {
1da177e4
LT
839 if (buffer_mapped(bh) && buffer_dirty(bh)) {
840 lock_buffer(bh);
841 if (test_clear_buffer_dirty(bh)) {
842 BUG_ON(!buffer_uptodate(bh));
843 mark_buffer_async_write(bh);
844 } else
845 unlock_buffer(bh);
846 } else if (unlikely(err)) {
847 /*
848 * For the error case. The buffer may have been set
849 * dirty during attachment to a dirty page.
850 */
851 if (err != -ENOMEM)
852 clear_buffer_dirty(bh);
853 }
854 } while ((bh = bh->b_this_page) != head);
855
856 if (unlikely(err)) {
857 // TODO: Remove the -EOPNOTSUPP check later on...
858 if (unlikely(err == -EOPNOTSUPP))
859 err = 0;
860 else if (err == -ENOMEM) {
861 ntfs_warning(vol->sb, "Error allocating memory. "
862 "Redirtying page so we try again "
863 "later.");
864 /*
865 * Put the page back on mapping->dirty_pages, but
866 * leave its buffer's dirty state as-is.
867 */
868 redirty_page_for_writepage(wbc, page);
869 err = 0;
870 } else
871 SetPageError(page);
872 }
873
874 BUG_ON(PageWriteback(page));
875 set_page_writeback(page); /* Keeps try_to_free_buffers() away. */
1da177e4 876
54b02eb0 877 /* Submit the prepared buffers for i/o. */
1da177e4
LT
878 need_end_writeback = TRUE;
879 do {
880 struct buffer_head *next = bh->b_this_page;
881 if (buffer_async_write(bh)) {
882 submit_bh(WRITE, bh);
883 need_end_writeback = FALSE;
884 }
1da177e4
LT
885 bh = next;
886 } while (bh != head);
54b02eb0 887 unlock_page(page);
1da177e4
LT
888
889 /* If no i/o was started, need to end_page_writeback(). */
890 if (unlikely(need_end_writeback))
891 end_page_writeback(page);
892
893 ntfs_debug("Done.");
894 return err;
895}
896
897/**
898 * ntfs_write_mst_block - write a @page to the backing store
899 * @page: page cache page to write out
900 * @wbc: writeback control structure
901 *
902 * This function is for writing pages belonging to non-resident, mst protected
903 * attributes to their backing store. The only supported attributes are index
904 * allocation and $MFT/$DATA. Both directory inodes and index inodes are
905 * supported for the index allocation case.
906 *
907 * The page must remain locked for the duration of the write because we apply
908 * the mst fixups, write, and then undo the fixups, so if we were to unlock the
909 * page before undoing the fixups, any other user of the page will see the
910 * page contents as corrupt.
911 *
912 * We clear the page uptodate flag for the duration of the function to ensure
913 * exclusion for the $MFT/$DATA case against someone mapping an mft record we
914 * are about to apply the mst fixups to.
915 *
916 * Return 0 on success and -errno on error.
917 *
918 * Based on ntfs_write_block(), ntfs_mft_writepage(), and
919 * write_mft_record_nolock().
920 */
921static int ntfs_write_mst_block(struct page *page,
922 struct writeback_control *wbc)
923{
924 sector_t block, dblock, rec_block;
925 struct inode *vi = page->mapping->host;
926 ntfs_inode *ni = NTFS_I(vi);
927 ntfs_volume *vol = ni->vol;
928 u8 *kaddr;
1da177e4
LT
929 unsigned int rec_size = ni->itype.index.block_size;
930 ntfs_inode *locked_nis[PAGE_CACHE_SIZE / rec_size];
931 struct buffer_head *bh, *head, *tbh, *rec_start_bh;
d53ee322 932 struct buffer_head *bhs[MAX_BUF_PER_PAGE];
1da177e4 933 runlist_element *rl;
d53ee322
AA
934 int i, nr_locked_nis, nr_recs, nr_bhs, max_bhs, bhs_per_rec, err, err2;
935 unsigned bh_size, rec_size_bits;
1da177e4 936 BOOL sync, is_mft, page_is_dirty, rec_is_dirty;
d53ee322 937 unsigned char bh_size_bits;
1da177e4
LT
938
939 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
940 "0x%lx.", vi->i_ino, ni->type, page->index);
941 BUG_ON(!NInoNonResident(ni));
942 BUG_ON(!NInoMstProtected(ni));
943 is_mft = (S_ISREG(vi->i_mode) && !vi->i_ino);
944 /*
945 * NOTE: ntfs_write_mst_block() would be called for $MFTMirr if a page
946 * in its page cache were to be marked dirty. However this should
947 * never happen with the current driver and considering we do not
948 * handle this case here we do want to BUG(), at least for now.
949 */
950 BUG_ON(!(is_mft || S_ISDIR(vi->i_mode) ||
951 (NInoAttr(ni) && ni->type == AT_INDEX_ALLOCATION)));
d53ee322
AA
952 bh_size_bits = vi->i_blkbits;
953 bh_size = 1 << bh_size_bits;
954 max_bhs = PAGE_CACHE_SIZE / bh_size;
1da177e4 955 BUG_ON(!max_bhs);
d53ee322 956 BUG_ON(max_bhs > MAX_BUF_PER_PAGE);
1da177e4
LT
957
958 /* Were we called for sync purposes? */
959 sync = (wbc->sync_mode == WB_SYNC_ALL);
960
961 /* Make sure we have mapped buffers. */
1da177e4
LT
962 bh = head = page_buffers(page);
963 BUG_ON(!bh);
964
965 rec_size_bits = ni->itype.index.block_size_bits;
966 BUG_ON(!(PAGE_CACHE_SIZE >> rec_size_bits));
967 bhs_per_rec = rec_size >> bh_size_bits;
968 BUG_ON(!bhs_per_rec);
969
970 /* The first block in the page. */
971 rec_block = block = (sector_t)page->index <<
972 (PAGE_CACHE_SHIFT - bh_size_bits);
973
974 /* The first out of bounds block for the data size. */
07a4e2da 975 dblock = (i_size_read(vi) + bh_size - 1) >> bh_size_bits;
1da177e4
LT
976
977 rl = NULL;
978 err = err2 = nr_bhs = nr_recs = nr_locked_nis = 0;
979 page_is_dirty = rec_is_dirty = FALSE;
980 rec_start_bh = NULL;
981 do {
982 BOOL is_retry = FALSE;
983
984 if (likely(block < rec_block)) {
985 if (unlikely(block >= dblock)) {
986 clear_buffer_dirty(bh);
946929d8 987 set_buffer_uptodate(bh);
1da177e4
LT
988 continue;
989 }
990 /*
991 * This block is not the first one in the record. We
992 * ignore the buffer's dirty state because we could
993 * have raced with a parallel mark_ntfs_record_dirty().
994 */
995 if (!rec_is_dirty)
996 continue;
997 if (unlikely(err2)) {
998 if (err2 != -ENOMEM)
999 clear_buffer_dirty(bh);
1000 continue;
1001 }
1002 } else /* if (block == rec_block) */ {
1003 BUG_ON(block > rec_block);
1004 /* This block is the first one in the record. */
1005 rec_block += bhs_per_rec;
1006 err2 = 0;
1007 if (unlikely(block >= dblock)) {
1008 clear_buffer_dirty(bh);
1009 continue;
1010 }
1011 if (!buffer_dirty(bh)) {
1012 /* Clean records are not written out. */
1013 rec_is_dirty = FALSE;
1014 continue;
1015 }
1016 rec_is_dirty = TRUE;
1017 rec_start_bh = bh;
1018 }
1019 /* Need to map the buffer if it is not mapped already. */
1020 if (unlikely(!buffer_mapped(bh))) {
1021 VCN vcn;
1022 LCN lcn;
1023 unsigned int vcn_ofs;
1024
481d0374 1025 bh->b_bdev = vol->sb->s_bdev;
1da177e4
LT
1026 /* Obtain the vcn and offset of the current block. */
1027 vcn = (VCN)block << bh_size_bits;
1028 vcn_ofs = vcn & vol->cluster_size_mask;
1029 vcn >>= vol->cluster_size_bits;
1030 if (!rl) {
1031lock_retry_remap:
1032 down_read(&ni->runlist.lock);
1033 rl = ni->runlist.rl;
1034 }
1035 if (likely(rl != NULL)) {
1036 /* Seek to element containing target vcn. */
1037 while (rl->length && rl[1].vcn <= vcn)
1038 rl++;
1039 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
1040 } else
1041 lcn = LCN_RL_NOT_MAPPED;
1042 /* Successful remap. */
1043 if (likely(lcn >= 0)) {
1044 /* Setup buffer head to correct block. */
1045 bh->b_blocknr = ((lcn <<
1046 vol->cluster_size_bits) +
1047 vcn_ofs) >> bh_size_bits;
1048 set_buffer_mapped(bh);
1049 } else {
1050 /*
1051 * Remap failed. Retry to map the runlist once
1052 * unless we are working on $MFT which always
1053 * has the whole of its runlist in memory.
1054 */
1055 if (!is_mft && !is_retry &&
1056 lcn == LCN_RL_NOT_MAPPED) {
1057 is_retry = TRUE;
1058 /*
1059 * Attempt to map runlist, dropping
1060 * lock for the duration.
1061 */
1062 up_read(&ni->runlist.lock);
1063 err2 = ntfs_map_runlist(ni, vcn);
1064 if (likely(!err2))
1065 goto lock_retry_remap;
1066 if (err2 == -ENOMEM)
1067 page_is_dirty = TRUE;
1068 lcn = err2;
9f993fe4 1069 } else {
1da177e4 1070 err2 = -EIO;
9f993fe4
AA
1071 if (!rl)
1072 up_read(&ni->runlist.lock);
1073 }
1da177e4
LT
1074 /* Hard error. Abort writing this record. */
1075 if (!err || err == -ENOMEM)
1076 err = err2;
1077 bh->b_blocknr = -1;
1078 ntfs_error(vol->sb, "Cannot write ntfs record "
1079 "0x%llx (inode 0x%lx, "
1080 "attribute type 0x%x) because "
1081 "its location on disk could "
1082 "not be determined (error "
8907547d
RD
1083 "code %lli).",
1084 (long long)block <<
1da177e4
LT
1085 bh_size_bits >>
1086 vol->mft_record_size_bits,
1087 ni->mft_no, ni->type,
1088 (long long)lcn);
1089 /*
1090 * If this is not the first buffer, remove the
1091 * buffers in this record from the list of
1092 * buffers to write and clear their dirty bit
1093 * if not error -ENOMEM.
1094 */
1095 if (rec_start_bh != bh) {
1096 while (bhs[--nr_bhs] != rec_start_bh)
1097 ;
1098 if (err2 != -ENOMEM) {
1099 do {
1100 clear_buffer_dirty(
1101 rec_start_bh);
1102 } while ((rec_start_bh =
1103 rec_start_bh->
1104 b_this_page) !=
1105 bh);
1106 }
1107 }
1108 continue;
1109 }
1110 }
1111 BUG_ON(!buffer_uptodate(bh));
1112 BUG_ON(nr_bhs >= max_bhs);
1113 bhs[nr_bhs++] = bh;
1114 } while (block++, (bh = bh->b_this_page) != head);
1115 if (unlikely(rl))
1116 up_read(&ni->runlist.lock);
1117 /* If there were no dirty buffers, we are done. */
1118 if (!nr_bhs)
1119 goto done;
1120 /* Map the page so we can access its contents. */
1121 kaddr = kmap(page);
1122 /* Clear the page uptodate flag whilst the mst fixups are applied. */
1123 BUG_ON(!PageUptodate(page));
1124 ClearPageUptodate(page);
1125 for (i = 0; i < nr_bhs; i++) {
1126 unsigned int ofs;
1127
1128 /* Skip buffers which are not at the beginning of records. */
1129 if (i % bhs_per_rec)
1130 continue;
1131 tbh = bhs[i];
1132 ofs = bh_offset(tbh);
1133 if (is_mft) {
1134 ntfs_inode *tni;
1135 unsigned long mft_no;
1136
1137 /* Get the mft record number. */
1138 mft_no = (((s64)page->index << PAGE_CACHE_SHIFT) + ofs)
1139 >> rec_size_bits;
1140 /* Check whether to write this mft record. */
1141 tni = NULL;
1142 if (!ntfs_may_write_mft_record(vol, mft_no,
1143 (MFT_RECORD*)(kaddr + ofs), &tni)) {
1144 /*
1145 * The record should not be written. This
1146 * means we need to redirty the page before
1147 * returning.
1148 */
1149 page_is_dirty = TRUE;
1150 /*
1151 * Remove the buffers in this mft record from
1152 * the list of buffers to write.
1153 */
1154 do {
1155 bhs[i] = NULL;
1156 } while (++i % bhs_per_rec);
1157 continue;
1158 }
1159 /*
1160 * The record should be written. If a locked ntfs
1161 * inode was returned, add it to the array of locked
1162 * ntfs inodes.
1163 */
1164 if (tni)
1165 locked_nis[nr_locked_nis++] = tni;
1166 }
1167 /* Apply the mst protection fixups. */
1168 err2 = pre_write_mst_fixup((NTFS_RECORD*)(kaddr + ofs),
1169 rec_size);
1170 if (unlikely(err2)) {
1171 if (!err || err == -ENOMEM)
1172 err = -EIO;
1173 ntfs_error(vol->sb, "Failed to apply mst fixups "
1174 "(inode 0x%lx, attribute type 0x%x, "
1175 "page index 0x%lx, page offset 0x%x)!"
1176 " Unmount and run chkdsk.", vi->i_ino,
1177 ni->type, page->index, ofs);
1178 /*
1179 * Mark all the buffers in this record clean as we do
1180 * not want to write corrupt data to disk.
1181 */
1182 do {
1183 clear_buffer_dirty(bhs[i]);
1184 bhs[i] = NULL;
1185 } while (++i % bhs_per_rec);
1186 continue;
1187 }
1188 nr_recs++;
1189 }
1190 /* If no records are to be written out, we are done. */
1191 if (!nr_recs)
1192 goto unm_done;
1193 flush_dcache_page(page);
1194 /* Lock buffers and start synchronous write i/o on them. */
1195 for (i = 0; i < nr_bhs; i++) {
1196 tbh = bhs[i];
1197 if (!tbh)
1198 continue;
1199 if (unlikely(test_set_buffer_locked(tbh)))
1200 BUG();
1201 /* The buffer dirty state is now irrelevant, just clean it. */
1202 clear_buffer_dirty(tbh);
1203 BUG_ON(!buffer_uptodate(tbh));
1204 BUG_ON(!buffer_mapped(tbh));
1205 get_bh(tbh);
1206 tbh->b_end_io = end_buffer_write_sync;
1207 submit_bh(WRITE, tbh);
1208 }
1209 /* Synchronize the mft mirror now if not @sync. */
1210 if (is_mft && !sync)
1211 goto do_mirror;
1212do_wait:
1213 /* Wait on i/o completion of buffers. */
1214 for (i = 0; i < nr_bhs; i++) {
1215 tbh = bhs[i];
1216 if (!tbh)
1217 continue;
1218 wait_on_buffer(tbh);
1219 if (unlikely(!buffer_uptodate(tbh))) {
1220 ntfs_error(vol->sb, "I/O error while writing ntfs "
1221 "record buffer (inode 0x%lx, "
1222 "attribute type 0x%x, page index "
1223 "0x%lx, page offset 0x%lx)! Unmount "
1224 "and run chkdsk.", vi->i_ino, ni->type,
1225 page->index, bh_offset(tbh));
1226 if (!err || err == -ENOMEM)
1227 err = -EIO;
1228 /*
1229 * Set the buffer uptodate so the page and buffer
1230 * states do not become out of sync.
1231 */
1232 set_buffer_uptodate(tbh);
1233 }
1234 }
1235 /* If @sync, now synchronize the mft mirror. */
1236 if (is_mft && sync) {
1237do_mirror:
1238 for (i = 0; i < nr_bhs; i++) {
1239 unsigned long mft_no;
1240 unsigned int ofs;
1241
1242 /*
1243 * Skip buffers which are not at the beginning of
1244 * records.
1245 */
1246 if (i % bhs_per_rec)
1247 continue;
1248 tbh = bhs[i];
1249 /* Skip removed buffers (and hence records). */
1250 if (!tbh)
1251 continue;
1252 ofs = bh_offset(tbh);
1253 /* Get the mft record number. */
1254 mft_no = (((s64)page->index << PAGE_CACHE_SHIFT) + ofs)
1255 >> rec_size_bits;
1256 if (mft_no < vol->mftmirr_size)
1257 ntfs_sync_mft_mirror(vol, mft_no,
1258 (MFT_RECORD*)(kaddr + ofs),
1259 sync);
1260 }
1261 if (!sync)
1262 goto do_wait;
1263 }
1264 /* Remove the mst protection fixups again. */
1265 for (i = 0; i < nr_bhs; i++) {
1266 if (!(i % bhs_per_rec)) {
1267 tbh = bhs[i];
1268 if (!tbh)
1269 continue;
1270 post_write_mst_fixup((NTFS_RECORD*)(kaddr +
1271 bh_offset(tbh)));
1272 }
1273 }
1274 flush_dcache_page(page);
1275unm_done:
1276 /* Unlock any locked inodes. */
1277 while (nr_locked_nis-- > 0) {
1278 ntfs_inode *tni, *base_tni;
1279
1280 tni = locked_nis[nr_locked_nis];
1281 /* Get the base inode. */
1282 down(&tni->extent_lock);
1283 if (tni->nr_extents >= 0)
1284 base_tni = tni;
1285 else {
1286 base_tni = tni->ext.base_ntfs_ino;
1287 BUG_ON(!base_tni);
1288 }
1289 up(&tni->extent_lock);
1290 ntfs_debug("Unlocking %s inode 0x%lx.",
1291 tni == base_tni ? "base" : "extent",
1292 tni->mft_no);
1293 up(&tni->mrec_lock);
1294 atomic_dec(&tni->count);
1295 iput(VFS_I(base_tni));
1296 }
1297 SetPageUptodate(page);
1298 kunmap(page);
1299done:
1300 if (unlikely(err && err != -ENOMEM)) {
1301 /*
1302 * Set page error if there is only one ntfs record in the page.
1303 * Otherwise we would loose per-record granularity.
1304 */
1305 if (ni->itype.index.block_size == PAGE_CACHE_SIZE)
1306 SetPageError(page);
1307 NVolSetErrors(vol);
1308 }
1309 if (page_is_dirty) {
1310 ntfs_debug("Page still contains one or more dirty ntfs "
1311 "records. Redirtying the page starting at "
1312 "record 0x%lx.", page->index <<
1313 (PAGE_CACHE_SHIFT - rec_size_bits));
1314 redirty_page_for_writepage(wbc, page);
1315 unlock_page(page);
1316 } else {
1317 /*
1318 * Keep the VM happy. This must be done otherwise the
1319 * radix-tree tag PAGECACHE_TAG_DIRTY remains set even though
1320 * the page is clean.
1321 */
1322 BUG_ON(PageWriteback(page));
1323 set_page_writeback(page);
1324 unlock_page(page);
1325 end_page_writeback(page);
1326 }
1327 if (likely(!err))
1328 ntfs_debug("Done.");
1329 return err;
1330}
1331
1332/**
1333 * ntfs_writepage - write a @page to the backing store
1334 * @page: page cache page to write out
1335 * @wbc: writeback control structure
1336 *
1337 * This is called from the VM when it wants to have a dirty ntfs page cache
1338 * page cleaned. The VM has already locked the page and marked it clean.
1339 *
1340 * For non-resident attributes, ntfs_writepage() writes the @page by calling
1341 * the ntfs version of the generic block_write_full_page() function,
1342 * ntfs_write_block(), which in turn if necessary creates and writes the
1343 * buffers associated with the page asynchronously.
1344 *
1345 * For resident attributes, OTOH, ntfs_writepage() writes the @page by copying
1346 * the data to the mft record (which at this stage is most likely in memory).
1347 * The mft record is then marked dirty and written out asynchronously via the
1348 * vfs inode dirty code path for the inode the mft record belongs to or via the
1349 * vm page dirty code path for the page the mft record is in.
1350 *
1351 * Based on ntfs_readpage() and fs/buffer.c::block_write_full_page().
1352 *
1353 * Return 0 on success and -errno on error.
1354 */
1355static int ntfs_writepage(struct page *page, struct writeback_control *wbc)
1356{
1357 loff_t i_size;
149f0c52
AA
1358 struct inode *vi = page->mapping->host;
1359 ntfs_inode *base_ni = NULL, *ni = NTFS_I(vi);
1da177e4 1360 char *kaddr;
149f0c52
AA
1361 ntfs_attr_search_ctx *ctx = NULL;
1362 MFT_RECORD *m = NULL;
1da177e4
LT
1363 u32 attr_len;
1364 int err;
1365
905685f6 1366retry_writepage:
1da177e4 1367 BUG_ON(!PageLocked(page));
1da177e4 1368 i_size = i_size_read(vi);
1da177e4
LT
1369 /* Is the page fully outside i_size? (truncate in progress) */
1370 if (unlikely(page->index >= (i_size + PAGE_CACHE_SIZE - 1) >>
1371 PAGE_CACHE_SHIFT)) {
1372 /*
1373 * The page may have dirty, unmapped buffers. Make them
1374 * freeable here, so the page does not leak.
1375 */
1376 block_invalidatepage(page, 0);
1377 unlock_page(page);
1378 ntfs_debug("Write outside i_size - truncated?");
1379 return 0;
1380 }
bd45fdd2
AA
1381 /*
1382 * Only $DATA attributes can be encrypted and only unnamed $DATA
1383 * attributes can be compressed. Index root can have the flags set but
1384 * this means to create compressed/encrypted files, not that the
4e64c886
AA
1385 * attribute is compressed/encrypted. Note we need to check for
1386 * AT_INDEX_ALLOCATION since this is the type of both directory and
1387 * index inodes.
bd45fdd2 1388 */
4e64c886 1389 if (ni->type != AT_INDEX_ALLOCATION) {
bd45fdd2
AA
1390 /* If file is encrypted, deny access, just like NT4. */
1391 if (NInoEncrypted(ni)) {
1392 unlock_page(page);
1393 BUG_ON(ni->type != AT_DATA);
1394 ntfs_debug("Denying write access to encrypted "
1395 "file.");
1396 return -EACCES;
1397 }
1398 /* Compressed data streams are handled in compress.c. */
1399 if (NInoNonResident(ni) && NInoCompressed(ni)) {
1400 BUG_ON(ni->type != AT_DATA);
1401 BUG_ON(ni->name_len);
1402 // TODO: Implement and replace this with
1403 // return ntfs_write_compressed_block(page);
1404 unlock_page(page);
1405 ntfs_error(vi->i_sb, "Writing to compressed files is "
1406 "not supported yet. Sorry.");
1407 return -EOPNOTSUPP;
1408 }
1409 // TODO: Implement and remove this check.
1410 if (NInoNonResident(ni) && NInoSparse(ni)) {
1411 unlock_page(page);
1412 ntfs_error(vi->i_sb, "Writing to sparse files is not "
1413 "supported yet. Sorry.");
1414 return -EOPNOTSUPP;
1415 }
1416 }
1da177e4
LT
1417 /* NInoNonResident() == NInoIndexAllocPresent() */
1418 if (NInoNonResident(ni)) {
1da177e4
LT
1419 /* We have to zero every time due to mmap-at-end-of-file. */
1420 if (page->index >= (i_size >> PAGE_CACHE_SHIFT)) {
1421 /* The page straddles i_size. */
1422 unsigned int ofs = i_size & ~PAGE_CACHE_MASK;
1423 kaddr = kmap_atomic(page, KM_USER0);
1424 memset(kaddr + ofs, 0, PAGE_CACHE_SIZE - ofs);
1da177e4 1425 kunmap_atomic(kaddr, KM_USER0);
f6098cf4 1426 flush_dcache_page(page);
1da177e4
LT
1427 }
1428 /* Handle mst protected attributes. */
1429 if (NInoMstProtected(ni))
1430 return ntfs_write_mst_block(page, wbc);
bd45fdd2 1431 /* Normal, non-resident data stream. */
1da177e4
LT
1432 return ntfs_write_block(page, wbc);
1433 }
1434 /*
bd45fdd2
AA
1435 * Attribute is resident, implying it is not compressed, encrypted, or
1436 * mst protected. This also means the attribute is smaller than an mft
1437 * record and hence smaller than a page, so can simply return error on
1438 * any pages with index above 0. Note the attribute can actually be
1439 * marked compressed but if it is resident the actual data is not
1440 * compressed so we are ok to ignore the compressed flag here.
1da177e4
LT
1441 */
1442 BUG_ON(page_has_buffers(page));
1443 BUG_ON(!PageUptodate(page));
1444 if (unlikely(page->index > 0)) {
1445 ntfs_error(vi->i_sb, "BUG()! page->index (0x%lx) > 0. "
1446 "Aborting write.", page->index);
1447 BUG_ON(PageWriteback(page));
1448 set_page_writeback(page);
1449 unlock_page(page);
1450 end_page_writeback(page);
1451 return -EIO;
1452 }
1453 if (!NInoAttr(ni))
1454 base_ni = ni;
1455 else
1456 base_ni = ni->ext.base_ntfs_ino;
1457 /* Map, pin, and lock the mft record. */
1458 m = map_mft_record(base_ni);
1459 if (IS_ERR(m)) {
1460 err = PTR_ERR(m);
1461 m = NULL;
1462 ctx = NULL;
1463 goto err_out;
1464 }
905685f6
AA
1465 /*
1466 * If a parallel write made the attribute non-resident, drop the mft
1467 * record and retry the writepage.
1468 */
1469 if (unlikely(NInoNonResident(ni))) {
1470 unmap_mft_record(base_ni);
1471 goto retry_writepage;
1472 }
1da177e4
LT
1473 ctx = ntfs_attr_get_search_ctx(base_ni, m);
1474 if (unlikely(!ctx)) {
1475 err = -ENOMEM;
1476 goto err_out;
1477 }
1478 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1479 CASE_SENSITIVE, 0, NULL, 0, ctx);
1480 if (unlikely(err))
1481 goto err_out;
1482 /*
1483 * Keep the VM happy. This must be done otherwise the radix-tree tag
1484 * PAGECACHE_TAG_DIRTY remains set even though the page is clean.
1485 */
1486 BUG_ON(PageWriteback(page));
1487 set_page_writeback(page);
1488 unlock_page(page);
1da177e4 1489 attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
07a4e2da 1490 i_size = i_size_read(vi);
1da177e4 1491 if (unlikely(attr_len > i_size)) {
f6098cf4 1492 /* Race with shrinking truncate or a failed truncate. */
1da177e4 1493 attr_len = i_size;
f6098cf4
AA
1494 /*
1495 * If the truncate failed, fix it up now. If a concurrent
1496 * truncate, we do its job, so it does not have to do anything.
1497 */
1498 err = ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr,
1499 attr_len);
1500 /* Shrinking cannot fail. */
1501 BUG_ON(err);
1da177e4 1502 }
f40661be 1503 kaddr = kmap_atomic(page, KM_USER0);
1da177e4
LT
1504 /* Copy the data from the page to the mft record. */
1505 memcpy((u8*)ctx->attr +
1506 le16_to_cpu(ctx->attr->data.resident.value_offset),
1507 kaddr, attr_len);
1da177e4
LT
1508 /* Zero out of bounds area in the page cache page. */
1509 memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
1da177e4 1510 kunmap_atomic(kaddr, KM_USER0);
f6098cf4
AA
1511 flush_dcache_mft_record_page(ctx->ntfs_ino);
1512 flush_dcache_page(page);
1513 /* We are done with the page. */
1da177e4 1514 end_page_writeback(page);
f6098cf4 1515 /* Finally, mark the mft record dirty, so it gets written back. */
1da177e4
LT
1516 mark_mft_record_dirty(ctx->ntfs_ino);
1517 ntfs_attr_put_search_ctx(ctx);
1518 unmap_mft_record(base_ni);
1519 return 0;
1520err_out:
1521 if (err == -ENOMEM) {
1522 ntfs_warning(vi->i_sb, "Error allocating memory. Redirtying "
1523 "page so we try again later.");
1524 /*
1525 * Put the page back on mapping->dirty_pages, but leave its
1526 * buffers' dirty state as-is.
1527 */
1528 redirty_page_for_writepage(wbc, page);
1529 err = 0;
1530 } else {
1531 ntfs_error(vi->i_sb, "Resident attribute write failed with "
149f0c52 1532 "error %i.", err);
1da177e4 1533 SetPageError(page);
149f0c52
AA
1534 NVolSetErrors(ni->vol);
1535 make_bad_inode(vi);
1da177e4
LT
1536 }
1537 unlock_page(page);
1538 if (ctx)
1539 ntfs_attr_put_search_ctx(ctx);
1540 if (m)
1541 unmap_mft_record(base_ni);
1542 return err;
1543}
1544
1da177e4
LT
1545#endif /* NTFS_RW */
1546
1547/**
1548 * ntfs_aops - general address space operations for inodes and attributes
1549 */
1550struct address_space_operations ntfs_aops = {
1551 .readpage = ntfs_readpage, /* Fill page with data. */
1552 .sync_page = block_sync_page, /* Currently, just unplugs the
1553 disk request queue. */
1554#ifdef NTFS_RW
1555 .writepage = ntfs_writepage, /* Write dirty page to disk. */
1da177e4
LT
1556#endif /* NTFS_RW */
1557};
1558
1559/**
1560 * ntfs_mst_aops - general address space operations for mst protecteed inodes
1561 * and attributes
1562 */
1563struct address_space_operations ntfs_mst_aops = {
1564 .readpage = ntfs_readpage, /* Fill page with data. */
1565 .sync_page = block_sync_page, /* Currently, just unplugs the
1566 disk request queue. */
1567#ifdef NTFS_RW
1568 .writepage = ntfs_writepage, /* Write dirty page to disk. */
1569 .set_page_dirty = __set_page_dirty_nobuffers, /* Set the page dirty
1570 without touching the buffers
1571 belonging to the page. */
1572#endif /* NTFS_RW */
1573};
1574
1575#ifdef NTFS_RW
1576
1577/**
1578 * mark_ntfs_record_dirty - mark an ntfs record dirty
1579 * @page: page containing the ntfs record to mark dirty
1580 * @ofs: byte offset within @page at which the ntfs record begins
1581 *
1582 * Set the buffers and the page in which the ntfs record is located dirty.
1583 *
1584 * The latter also marks the vfs inode the ntfs record belongs to dirty
1585 * (I_DIRTY_PAGES only).
1586 *
1587 * If the page does not have buffers, we create them and set them uptodate.
1588 * The page may not be locked which is why we need to handle the buffers under
1589 * the mapping->private_lock. Once the buffers are marked dirty we no longer
1590 * need the lock since try_to_free_buffers() does not free dirty buffers.
1591 */
1592void mark_ntfs_record_dirty(struct page *page, const unsigned int ofs) {
1593 struct address_space *mapping = page->mapping;
1594 ntfs_inode *ni = NTFS_I(mapping->host);
1595 struct buffer_head *bh, *head, *buffers_to_free = NULL;
1596 unsigned int end, bh_size, bh_ofs;
1597
1598 BUG_ON(!PageUptodate(page));
1599 end = ofs + ni->itype.index.block_size;
1600 bh_size = 1 << VFS_I(ni)->i_blkbits;
1601 spin_lock(&mapping->private_lock);
1602 if (unlikely(!page_has_buffers(page))) {
1603 spin_unlock(&mapping->private_lock);
1604 bh = head = alloc_page_buffers(page, bh_size, 1);
1605 spin_lock(&mapping->private_lock);
1606 if (likely(!page_has_buffers(page))) {
1607 struct buffer_head *tail;
1608
1609 do {
1610 set_buffer_uptodate(bh);
1611 tail = bh;
1612 bh = bh->b_this_page;
1613 } while (bh);
1614 tail->b_this_page = head;
1615 attach_page_buffers(page, head);
1616 } else
1617 buffers_to_free = bh;
1618 }
1619 bh = head = page_buffers(page);
a01ac532 1620 BUG_ON(!bh);
1da177e4
LT
1621 do {
1622 bh_ofs = bh_offset(bh);
1623 if (bh_ofs + bh_size <= ofs)
1624 continue;
1625 if (unlikely(bh_ofs >= end))
1626 break;
1627 set_buffer_dirty(bh);
1628 } while ((bh = bh->b_this_page) != head);
1629 spin_unlock(&mapping->private_lock);
1630 __set_page_dirty_nobuffers(page);
1631 if (unlikely(buffers_to_free)) {
1632 do {
1633 bh = buffers_to_free->b_this_page;
1634 free_buffer_head(buffers_to_free);
1635 buffers_to_free = bh;
1636 } while (buffers_to_free);
1637 }
1638}
1639
1640#endif /* NTFS_RW */