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