Merge tag 'driver-core-4.9-rc3' of git://git.kernel.org/pub/scm/linux/kernel/git...
[cascardo/linux.git] / fs / xfs / xfs_iomap.c
1 /*
2  * Copyright (c) 2000-2006 Silicon Graphics, Inc.
3  * Copyright (c) 2016 Christoph Hellwig.
4  * All Rights Reserved.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it would be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write the Free Software Foundation,
17  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18  */
19 #include <linux/iomap.h>
20 #include "xfs.h"
21 #include "xfs_fs.h"
22 #include "xfs_shared.h"
23 #include "xfs_format.h"
24 #include "xfs_log_format.h"
25 #include "xfs_trans_resv.h"
26 #include "xfs_mount.h"
27 #include "xfs_defer.h"
28 #include "xfs_inode.h"
29 #include "xfs_btree.h"
30 #include "xfs_bmap_btree.h"
31 #include "xfs_bmap.h"
32 #include "xfs_bmap_util.h"
33 #include "xfs_error.h"
34 #include "xfs_trans.h"
35 #include "xfs_trans_space.h"
36 #include "xfs_iomap.h"
37 #include "xfs_trace.h"
38 #include "xfs_icache.h"
39 #include "xfs_quota.h"
40 #include "xfs_dquot_item.h"
41 #include "xfs_dquot.h"
42 #include "xfs_reflink.h"
43
44
45 #define XFS_WRITEIO_ALIGN(mp,off)       (((off) >> mp->m_writeio_log) \
46                                                 << mp->m_writeio_log)
47
48 void
49 xfs_bmbt_to_iomap(
50         struct xfs_inode        *ip,
51         struct iomap            *iomap,
52         struct xfs_bmbt_irec    *imap)
53 {
54         struct xfs_mount        *mp = ip->i_mount;
55
56         if (imap->br_startblock == HOLESTARTBLOCK) {
57                 iomap->blkno = IOMAP_NULL_BLOCK;
58                 iomap->type = IOMAP_HOLE;
59         } else if (imap->br_startblock == DELAYSTARTBLOCK) {
60                 iomap->blkno = IOMAP_NULL_BLOCK;
61                 iomap->type = IOMAP_DELALLOC;
62         } else {
63                 iomap->blkno = xfs_fsb_to_db(ip, imap->br_startblock);
64                 if (imap->br_state == XFS_EXT_UNWRITTEN)
65                         iomap->type = IOMAP_UNWRITTEN;
66                 else
67                         iomap->type = IOMAP_MAPPED;
68         }
69         iomap->offset = XFS_FSB_TO_B(mp, imap->br_startoff);
70         iomap->length = XFS_FSB_TO_B(mp, imap->br_blockcount);
71         iomap->bdev = xfs_find_bdev_for_inode(VFS_I(ip));
72 }
73
74 xfs_extlen_t
75 xfs_eof_alignment(
76         struct xfs_inode        *ip,
77         xfs_extlen_t            extsize)
78 {
79         struct xfs_mount        *mp = ip->i_mount;
80         xfs_extlen_t            align = 0;
81
82         if (!XFS_IS_REALTIME_INODE(ip)) {
83                 /*
84                  * Round up the allocation request to a stripe unit
85                  * (m_dalign) boundary if the file size is >= stripe unit
86                  * size, and we are allocating past the allocation eof.
87                  *
88                  * If mounted with the "-o swalloc" option the alignment is
89                  * increased from the strip unit size to the stripe width.
90                  */
91                 if (mp->m_swidth && (mp->m_flags & XFS_MOUNT_SWALLOC))
92                         align = mp->m_swidth;
93                 else if (mp->m_dalign)
94                         align = mp->m_dalign;
95
96                 if (align && XFS_ISIZE(ip) < XFS_FSB_TO_B(mp, align))
97                         align = 0;
98         }
99
100         /*
101          * Always round up the allocation request to an extent boundary
102          * (when file on a real-time subvolume or has di_extsize hint).
103          */
104         if (extsize) {
105                 if (align)
106                         align = roundup_64(align, extsize);
107                 else
108                         align = extsize;
109         }
110
111         return align;
112 }
113
114 STATIC int
115 xfs_iomap_eof_align_last_fsb(
116         struct xfs_inode        *ip,
117         xfs_extlen_t            extsize,
118         xfs_fileoff_t           *last_fsb)
119 {
120         xfs_extlen_t            align = xfs_eof_alignment(ip, extsize);
121
122         if (align) {
123                 xfs_fileoff_t   new_last_fsb = roundup_64(*last_fsb, align);
124                 int             eof, error;
125
126                 error = xfs_bmap_eof(ip, new_last_fsb, XFS_DATA_FORK, &eof);
127                 if (error)
128                         return error;
129                 if (eof)
130                         *last_fsb = new_last_fsb;
131         }
132         return 0;
133 }
134
135 STATIC int
136 xfs_alert_fsblock_zero(
137         xfs_inode_t     *ip,
138         xfs_bmbt_irec_t *imap)
139 {
140         xfs_alert_tag(ip->i_mount, XFS_PTAG_FSBLOCK_ZERO,
141                         "Access to block zero in inode %llu "
142                         "start_block: %llx start_off: %llx "
143                         "blkcnt: %llx extent-state: %x",
144                 (unsigned long long)ip->i_ino,
145                 (unsigned long long)imap->br_startblock,
146                 (unsigned long long)imap->br_startoff,
147                 (unsigned long long)imap->br_blockcount,
148                 imap->br_state);
149         return -EFSCORRUPTED;
150 }
151
152 int
153 xfs_iomap_write_direct(
154         xfs_inode_t     *ip,
155         xfs_off_t       offset,
156         size_t          count,
157         xfs_bmbt_irec_t *imap,
158         int             nmaps)
159 {
160         xfs_mount_t     *mp = ip->i_mount;
161         xfs_fileoff_t   offset_fsb;
162         xfs_fileoff_t   last_fsb;
163         xfs_filblks_t   count_fsb, resaligned;
164         xfs_fsblock_t   firstfsb;
165         xfs_extlen_t    extsz, temp;
166         int             nimaps;
167         int             quota_flag;
168         int             rt;
169         xfs_trans_t     *tp;
170         struct xfs_defer_ops dfops;
171         uint            qblocks, resblks, resrtextents;
172         int             error;
173         int             lockmode;
174         int             bmapi_flags = XFS_BMAPI_PREALLOC;
175         uint            tflags = 0;
176
177         rt = XFS_IS_REALTIME_INODE(ip);
178         extsz = xfs_get_extsz_hint(ip);
179         lockmode = XFS_ILOCK_SHARED;    /* locked by caller */
180
181         ASSERT(xfs_isilocked(ip, lockmode));
182
183         offset_fsb = XFS_B_TO_FSBT(mp, offset);
184         last_fsb = XFS_B_TO_FSB(mp, ((xfs_ufsize_t)(offset + count)));
185         if ((offset + count) > XFS_ISIZE(ip)) {
186                 /*
187                  * Assert that the in-core extent list is present since this can
188                  * call xfs_iread_extents() and we only have the ilock shared.
189                  * This should be safe because the lock was held around a bmapi
190                  * call in the caller and we only need it to access the in-core
191                  * list.
192                  */
193                 ASSERT(XFS_IFORK_PTR(ip, XFS_DATA_FORK)->if_flags &
194                                                                 XFS_IFEXTENTS);
195                 error = xfs_iomap_eof_align_last_fsb(ip, extsz, &last_fsb);
196                 if (error)
197                         goto out_unlock;
198         } else {
199                 if (nmaps && (imap->br_startblock == HOLESTARTBLOCK))
200                         last_fsb = MIN(last_fsb, (xfs_fileoff_t)
201                                         imap->br_blockcount +
202                                         imap->br_startoff);
203         }
204         count_fsb = last_fsb - offset_fsb;
205         ASSERT(count_fsb > 0);
206
207         resaligned = count_fsb;
208         if (unlikely(extsz)) {
209                 if ((temp = do_mod(offset_fsb, extsz)))
210                         resaligned += temp;
211                 if ((temp = do_mod(resaligned, extsz)))
212                         resaligned += extsz - temp;
213         }
214
215         if (unlikely(rt)) {
216                 resrtextents = qblocks = resaligned;
217                 resrtextents /= mp->m_sb.sb_rextsize;
218                 resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
219                 quota_flag = XFS_QMOPT_RES_RTBLKS;
220         } else {
221                 resrtextents = 0;
222                 resblks = qblocks = XFS_DIOSTRAT_SPACE_RES(mp, resaligned);
223                 quota_flag = XFS_QMOPT_RES_REGBLKS;
224         }
225
226         /*
227          * Drop the shared lock acquired by the caller, attach the dquot if
228          * necessary and move on to transaction setup.
229          */
230         xfs_iunlock(ip, lockmode);
231         error = xfs_qm_dqattach(ip, 0);
232         if (error)
233                 return error;
234
235         /*
236          * For DAX, we do not allocate unwritten extents, but instead we zero
237          * the block before we commit the transaction.  Ideally we'd like to do
238          * this outside the transaction context, but if we commit and then crash
239          * we may not have zeroed the blocks and this will be exposed on
240          * recovery of the allocation. Hence we must zero before commit.
241          *
242          * Further, if we are mapping unwritten extents here, we need to zero
243          * and convert them to written so that we don't need an unwritten extent
244          * callback for DAX. This also means that we need to be able to dip into
245          * the reserve block pool for bmbt block allocation if there is no space
246          * left but we need to do unwritten extent conversion.
247          */
248         if (IS_DAX(VFS_I(ip))) {
249                 bmapi_flags = XFS_BMAPI_CONVERT | XFS_BMAPI_ZERO;
250                 if (ISUNWRITTEN(imap)) {
251                         tflags |= XFS_TRANS_RESERVE;
252                         resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0) << 1;
253                 }
254         }
255         error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, resblks, resrtextents,
256                         tflags, &tp);
257         if (error)
258                 return error;
259
260         lockmode = XFS_ILOCK_EXCL;
261         xfs_ilock(ip, lockmode);
262
263         error = xfs_trans_reserve_quota_nblks(tp, ip, qblocks, 0, quota_flag);
264         if (error)
265                 goto out_trans_cancel;
266
267         xfs_trans_ijoin(tp, ip, 0);
268
269         /*
270          * From this point onwards we overwrite the imap pointer that the
271          * caller gave to us.
272          */
273         xfs_defer_init(&dfops, &firstfsb);
274         nimaps = 1;
275         error = xfs_bmapi_write(tp, ip, offset_fsb, count_fsb,
276                                 bmapi_flags, &firstfsb, resblks, imap,
277                                 &nimaps, &dfops);
278         if (error)
279                 goto out_bmap_cancel;
280
281         /*
282          * Complete the transaction
283          */
284         error = xfs_defer_finish(&tp, &dfops, NULL);
285         if (error)
286                 goto out_bmap_cancel;
287
288         error = xfs_trans_commit(tp);
289         if (error)
290                 goto out_unlock;
291
292         /*
293          * Copy any maps to caller's array and return any error.
294          */
295         if (nimaps == 0) {
296                 error = -ENOSPC;
297                 goto out_unlock;
298         }
299
300         if (!(imap->br_startblock || XFS_IS_REALTIME_INODE(ip)))
301                 error = xfs_alert_fsblock_zero(ip, imap);
302
303 out_unlock:
304         xfs_iunlock(ip, lockmode);
305         return error;
306
307 out_bmap_cancel:
308         xfs_defer_cancel(&dfops);
309         xfs_trans_unreserve_quota_nblks(tp, ip, (long)qblocks, 0, quota_flag);
310 out_trans_cancel:
311         xfs_trans_cancel(tp);
312         goto out_unlock;
313 }
314
315 STATIC bool
316 xfs_quota_need_throttle(
317         struct xfs_inode *ip,
318         int type,
319         xfs_fsblock_t alloc_blocks)
320 {
321         struct xfs_dquot *dq = xfs_inode_dquot(ip, type);
322
323         if (!dq || !xfs_this_quota_on(ip->i_mount, type))
324                 return false;
325
326         /* no hi watermark, no throttle */
327         if (!dq->q_prealloc_hi_wmark)
328                 return false;
329
330         /* under the lo watermark, no throttle */
331         if (dq->q_res_bcount + alloc_blocks < dq->q_prealloc_lo_wmark)
332                 return false;
333
334         return true;
335 }
336
337 STATIC void
338 xfs_quota_calc_throttle(
339         struct xfs_inode *ip,
340         int type,
341         xfs_fsblock_t *qblocks,
342         int *qshift,
343         int64_t *qfreesp)
344 {
345         int64_t freesp;
346         int shift = 0;
347         struct xfs_dquot *dq = xfs_inode_dquot(ip, type);
348
349         /* no dq, or over hi wmark, squash the prealloc completely */
350         if (!dq || dq->q_res_bcount >= dq->q_prealloc_hi_wmark) {
351                 *qblocks = 0;
352                 *qfreesp = 0;
353                 return;
354         }
355
356         freesp = dq->q_prealloc_hi_wmark - dq->q_res_bcount;
357         if (freesp < dq->q_low_space[XFS_QLOWSP_5_PCNT]) {
358                 shift = 2;
359                 if (freesp < dq->q_low_space[XFS_QLOWSP_3_PCNT])
360                         shift += 2;
361                 if (freesp < dq->q_low_space[XFS_QLOWSP_1_PCNT])
362                         shift += 2;
363         }
364
365         if (freesp < *qfreesp)
366                 *qfreesp = freesp;
367
368         /* only overwrite the throttle values if we are more aggressive */
369         if ((freesp >> shift) < (*qblocks >> *qshift)) {
370                 *qblocks = freesp;
371                 *qshift = shift;
372         }
373 }
374
375 /*
376  * If we are doing a write at the end of the file and there are no allocations
377  * past this one, then extend the allocation out to the file system's write
378  * iosize.
379  *
380  * If we don't have a user specified preallocation size, dynamically increase
381  * the preallocation size as the size of the file grows.  Cap the maximum size
382  * at a single extent or less if the filesystem is near full. The closer the
383  * filesystem is to full, the smaller the maximum prealocation.
384  *
385  * As an exception we don't do any preallocation at all if the file is smaller
386  * than the minimum preallocation and we are using the default dynamic
387  * preallocation scheme, as it is likely this is the only write to the file that
388  * is going to be done.
389  *
390  * We clean up any extra space left over when the file is closed in
391  * xfs_inactive().
392  */
393 STATIC xfs_fsblock_t
394 xfs_iomap_prealloc_size(
395         struct xfs_inode        *ip,
396         loff_t                  offset,
397         loff_t                  count,
398         xfs_extnum_t            idx,
399         struct xfs_bmbt_irec    *prev)
400 {
401         struct xfs_mount        *mp = ip->i_mount;
402         xfs_fileoff_t           offset_fsb = XFS_B_TO_FSBT(mp, offset);
403         int                     shift = 0;
404         int64_t                 freesp;
405         xfs_fsblock_t           qblocks;
406         int                     qshift = 0;
407         xfs_fsblock_t           alloc_blocks = 0;
408
409         if (offset + count <= XFS_ISIZE(ip))
410                 return 0;
411
412         if (!(mp->m_flags & XFS_MOUNT_DFLT_IOSIZE) &&
413             (XFS_ISIZE(ip) < XFS_FSB_TO_B(mp, mp->m_writeio_blocks)))
414                 return 0;
415
416         /*
417          * If an explicit allocsize is set, the file is small, or we
418          * are writing behind a hole, then use the minimum prealloc:
419          */
420         if ((mp->m_flags & XFS_MOUNT_DFLT_IOSIZE) ||
421             XFS_ISIZE(ip) < XFS_FSB_TO_B(mp, mp->m_dalign) ||
422             idx == 0 ||
423             prev->br_startoff + prev->br_blockcount < offset_fsb)
424                 return mp->m_writeio_blocks;
425
426         /*
427          * Determine the initial size of the preallocation. We are beyond the
428          * current EOF here, but we need to take into account whether this is
429          * a sparse write or an extending write when determining the
430          * preallocation size.  Hence we need to look up the extent that ends
431          * at the current write offset and use the result to determine the
432          * preallocation size.
433          *
434          * If the extent is a hole, then preallocation is essentially disabled.
435          * Otherwise we take the size of the preceding data extent as the basis
436          * for the preallocation size. If the size of the extent is greater than
437          * half the maximum extent length, then use the current offset as the
438          * basis. This ensures that for large files the preallocation size
439          * always extends to MAXEXTLEN rather than falling short due to things
440          * like stripe unit/width alignment of real extents.
441          */
442         if (prev->br_blockcount <= (MAXEXTLEN >> 1))
443                 alloc_blocks = prev->br_blockcount << 1;
444         else
445                 alloc_blocks = XFS_B_TO_FSB(mp, offset);
446         if (!alloc_blocks)
447                 goto check_writeio;
448         qblocks = alloc_blocks;
449
450         /*
451          * MAXEXTLEN is not a power of two value but we round the prealloc down
452          * to the nearest power of two value after throttling. To prevent the
453          * round down from unconditionally reducing the maximum supported prealloc
454          * size, we round up first, apply appropriate throttling, round down and
455          * cap the value to MAXEXTLEN.
456          */
457         alloc_blocks = XFS_FILEOFF_MIN(roundup_pow_of_two(MAXEXTLEN),
458                                        alloc_blocks);
459
460         freesp = percpu_counter_read_positive(&mp->m_fdblocks);
461         if (freesp < mp->m_low_space[XFS_LOWSP_5_PCNT]) {
462                 shift = 2;
463                 if (freesp < mp->m_low_space[XFS_LOWSP_4_PCNT])
464                         shift++;
465                 if (freesp < mp->m_low_space[XFS_LOWSP_3_PCNT])
466                         shift++;
467                 if (freesp < mp->m_low_space[XFS_LOWSP_2_PCNT])
468                         shift++;
469                 if (freesp < mp->m_low_space[XFS_LOWSP_1_PCNT])
470                         shift++;
471         }
472
473         /*
474          * Check each quota to cap the prealloc size, provide a shift value to
475          * throttle with and adjust amount of available space.
476          */
477         if (xfs_quota_need_throttle(ip, XFS_DQ_USER, alloc_blocks))
478                 xfs_quota_calc_throttle(ip, XFS_DQ_USER, &qblocks, &qshift,
479                                         &freesp);
480         if (xfs_quota_need_throttle(ip, XFS_DQ_GROUP, alloc_blocks))
481                 xfs_quota_calc_throttle(ip, XFS_DQ_GROUP, &qblocks, &qshift,
482                                         &freesp);
483         if (xfs_quota_need_throttle(ip, XFS_DQ_PROJ, alloc_blocks))
484                 xfs_quota_calc_throttle(ip, XFS_DQ_PROJ, &qblocks, &qshift,
485                                         &freesp);
486
487         /*
488          * The final prealloc size is set to the minimum of free space available
489          * in each of the quotas and the overall filesystem.
490          *
491          * The shift throttle value is set to the maximum value as determined by
492          * the global low free space values and per-quota low free space values.
493          */
494         alloc_blocks = MIN(alloc_blocks, qblocks);
495         shift = MAX(shift, qshift);
496
497         if (shift)
498                 alloc_blocks >>= shift;
499         /*
500          * rounddown_pow_of_two() returns an undefined result if we pass in
501          * alloc_blocks = 0.
502          */
503         if (alloc_blocks)
504                 alloc_blocks = rounddown_pow_of_two(alloc_blocks);
505         if (alloc_blocks > MAXEXTLEN)
506                 alloc_blocks = MAXEXTLEN;
507
508         /*
509          * If we are still trying to allocate more space than is
510          * available, squash the prealloc hard. This can happen if we
511          * have a large file on a small filesystem and the above
512          * lowspace thresholds are smaller than MAXEXTLEN.
513          */
514         while (alloc_blocks && alloc_blocks >= freesp)
515                 alloc_blocks >>= 4;
516 check_writeio:
517         if (alloc_blocks < mp->m_writeio_blocks)
518                 alloc_blocks = mp->m_writeio_blocks;
519         trace_xfs_iomap_prealloc_size(ip, alloc_blocks, shift,
520                                       mp->m_writeio_blocks);
521         return alloc_blocks;
522 }
523
524 static int
525 xfs_file_iomap_begin_delay(
526         struct inode            *inode,
527         loff_t                  offset,
528         loff_t                  count,
529         unsigned                flags,
530         struct iomap            *iomap)
531 {
532         struct xfs_inode        *ip = XFS_I(inode);
533         struct xfs_mount        *mp = ip->i_mount;
534         struct xfs_ifork        *ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK);
535         xfs_fileoff_t           offset_fsb = XFS_B_TO_FSBT(mp, offset);
536         xfs_fileoff_t           maxbytes_fsb =
537                 XFS_B_TO_FSB(mp, mp->m_super->s_maxbytes);
538         xfs_fileoff_t           end_fsb, orig_end_fsb;
539         int                     error = 0, eof = 0;
540         struct xfs_bmbt_irec    got;
541         struct xfs_bmbt_irec    prev;
542         xfs_extnum_t            idx;
543
544         ASSERT(!XFS_IS_REALTIME_INODE(ip));
545         ASSERT(!xfs_get_extsz_hint(ip));
546
547         xfs_ilock(ip, XFS_ILOCK_EXCL);
548
549         if (unlikely(XFS_TEST_ERROR(
550             (XFS_IFORK_FORMAT(ip, XFS_DATA_FORK) != XFS_DINODE_FMT_EXTENTS &&
551              XFS_IFORK_FORMAT(ip, XFS_DATA_FORK) != XFS_DINODE_FMT_BTREE),
552              mp, XFS_ERRTAG_BMAPIFORMAT, XFS_RANDOM_BMAPIFORMAT))) {
553                 XFS_ERROR_REPORT(__func__, XFS_ERRLEVEL_LOW, mp);
554                 error = -EFSCORRUPTED;
555                 goto out_unlock;
556         }
557
558         XFS_STATS_INC(mp, xs_blk_mapw);
559
560         if (!(ifp->if_flags & XFS_IFEXTENTS)) {
561                 error = xfs_iread_extents(NULL, ip, XFS_DATA_FORK);
562                 if (error)
563                         goto out_unlock;
564         }
565
566         xfs_bmap_search_extents(ip, offset_fsb, XFS_DATA_FORK, &eof, &idx,
567                         &got, &prev);
568         if (!eof && got.br_startoff <= offset_fsb) {
569                 if (xfs_is_reflink_inode(ip)) {
570                         bool            shared;
571
572                         end_fsb = min(XFS_B_TO_FSB(mp, offset + count),
573                                         maxbytes_fsb);
574                         xfs_trim_extent(&got, offset_fsb, end_fsb - offset_fsb);
575                         error = xfs_reflink_reserve_cow(ip, &got, &shared);
576                         if (error)
577                                 goto out_unlock;
578                 }
579
580                 trace_xfs_iomap_found(ip, offset, count, 0, &got);
581                 goto done;
582         }
583
584         error = xfs_qm_dqattach_locked(ip, 0);
585         if (error)
586                 goto out_unlock;
587
588         /*
589          * We cap the maximum length we map here to MAX_WRITEBACK_PAGES pages
590          * to keep the chunks of work done where somewhat symmetric with the
591          * work writeback does. This is a completely arbitrary number pulled
592          * out of thin air as a best guess for initial testing.
593          *
594          * Note that the values needs to be less than 32-bits wide until
595          * the lower level functions are updated.
596          */
597         count = min_t(loff_t, count, 1024 * PAGE_SIZE);
598         end_fsb = orig_end_fsb =
599                 min(XFS_B_TO_FSB(mp, offset + count), maxbytes_fsb);
600
601         if (eof) {
602                 xfs_fsblock_t   prealloc_blocks;
603
604                 prealloc_blocks =
605                         xfs_iomap_prealloc_size(ip, offset, count, idx, &prev);
606                 if (prealloc_blocks) {
607                         xfs_extlen_t    align;
608                         xfs_off_t       end_offset;
609
610                         end_offset = XFS_WRITEIO_ALIGN(mp, offset + count - 1);
611                         end_fsb = XFS_B_TO_FSBT(mp, end_offset) +
612                                 prealloc_blocks;
613
614                         align = xfs_eof_alignment(ip, 0);
615                         if (align)
616                                 end_fsb = roundup_64(end_fsb, align);
617
618                         end_fsb = min(end_fsb, maxbytes_fsb);
619                         ASSERT(end_fsb > offset_fsb);
620                 }
621         }
622
623 retry:
624         error = xfs_bmapi_reserve_delalloc(ip, XFS_DATA_FORK, offset_fsb,
625                         end_fsb - offset_fsb, &got,
626                         &prev, &idx, eof);
627         switch (error) {
628         case 0:
629                 break;
630         case -ENOSPC:
631         case -EDQUOT:
632                 /* retry without any preallocation */
633                 trace_xfs_delalloc_enospc(ip, offset, count);
634                 if (end_fsb != orig_end_fsb) {
635                         end_fsb = orig_end_fsb;
636                         goto retry;
637                 }
638                 /*FALLTHRU*/
639         default:
640                 goto out_unlock;
641         }
642
643         /*
644          * Tag the inode as speculatively preallocated so we can reclaim this
645          * space on demand, if necessary.
646          */
647         if (end_fsb != orig_end_fsb)
648                 xfs_inode_set_eofblocks_tag(ip);
649
650         trace_xfs_iomap_alloc(ip, offset, count, 0, &got);
651 done:
652         if (isnullstartblock(got.br_startblock))
653                 got.br_startblock = DELAYSTARTBLOCK;
654
655         if (!got.br_startblock) {
656                 error = xfs_alert_fsblock_zero(ip, &got);
657                 if (error)
658                         goto out_unlock;
659         }
660
661         xfs_bmbt_to_iomap(ip, iomap, &got);
662
663 out_unlock:
664         xfs_iunlock(ip, XFS_ILOCK_EXCL);
665         return error;
666 }
667
668 /*
669  * Pass in a delayed allocate extent, convert it to real extents;
670  * return to the caller the extent we create which maps on top of
671  * the originating callers request.
672  *
673  * Called without a lock on the inode.
674  *
675  * We no longer bother to look at the incoming map - all we have to
676  * guarantee is that whatever we allocate fills the required range.
677  */
678 int
679 xfs_iomap_write_allocate(
680         xfs_inode_t     *ip,
681         int             whichfork,
682         xfs_off_t       offset,
683         xfs_bmbt_irec_t *imap)
684 {
685         xfs_mount_t     *mp = ip->i_mount;
686         xfs_fileoff_t   offset_fsb, last_block;
687         xfs_fileoff_t   end_fsb, map_start_fsb;
688         xfs_fsblock_t   first_block;
689         struct xfs_defer_ops    dfops;
690         xfs_filblks_t   count_fsb;
691         xfs_trans_t     *tp;
692         int             nimaps;
693         int             error = 0;
694         int             flags = 0;
695         int             nres;
696
697         if (whichfork == XFS_COW_FORK)
698                 flags |= XFS_BMAPI_COWFORK;
699
700         /*
701          * Make sure that the dquots are there.
702          */
703         error = xfs_qm_dqattach(ip, 0);
704         if (error)
705                 return error;
706
707         offset_fsb = XFS_B_TO_FSBT(mp, offset);
708         count_fsb = imap->br_blockcount;
709         map_start_fsb = imap->br_startoff;
710
711         XFS_STATS_ADD(mp, xs_xstrat_bytes, XFS_FSB_TO_B(mp, count_fsb));
712
713         while (count_fsb != 0) {
714                 /*
715                  * Set up a transaction with which to allocate the
716                  * backing store for the file.  Do allocations in a
717                  * loop until we get some space in the range we are
718                  * interested in.  The other space that might be allocated
719                  * is in the delayed allocation extent on which we sit
720                  * but before our buffer starts.
721                  */
722                 nimaps = 0;
723                 while (nimaps == 0) {
724                         nres = XFS_EXTENTADD_SPACE_RES(mp, XFS_DATA_FORK);
725                         /*
726                          * We have already reserved space for the extent and any
727                          * indirect blocks when creating the delalloc extent,
728                          * there is no need to reserve space in this transaction
729                          * again.
730                          */
731                         error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, 0,
732                                         0, XFS_TRANS_RESERVE, &tp);
733                         if (error)
734                                 return error;
735
736                         xfs_ilock(ip, XFS_ILOCK_EXCL);
737                         xfs_trans_ijoin(tp, ip, 0);
738
739                         xfs_defer_init(&dfops, &first_block);
740
741                         /*
742                          * it is possible that the extents have changed since
743                          * we did the read call as we dropped the ilock for a
744                          * while. We have to be careful about truncates or hole
745                          * punchs here - we are not allowed to allocate
746                          * non-delalloc blocks here.
747                          *
748                          * The only protection against truncation is the pages
749                          * for the range we are being asked to convert are
750                          * locked and hence a truncate will block on them
751                          * first.
752                          *
753                          * As a result, if we go beyond the range we really
754                          * need and hit an delalloc extent boundary followed by
755                          * a hole while we have excess blocks in the map, we
756                          * will fill the hole incorrectly and overrun the
757                          * transaction reservation.
758                          *
759                          * Using a single map prevents this as we are forced to
760                          * check each map we look for overlap with the desired
761                          * range and abort as soon as we find it. Also, given
762                          * that we only return a single map, having one beyond
763                          * what we can return is probably a bit silly.
764                          *
765                          * We also need to check that we don't go beyond EOF;
766                          * this is a truncate optimisation as a truncate sets
767                          * the new file size before block on the pages we
768                          * currently have locked under writeback. Because they
769                          * are about to be tossed, we don't need to write them
770                          * back....
771                          */
772                         nimaps = 1;
773                         end_fsb = XFS_B_TO_FSB(mp, XFS_ISIZE(ip));
774                         error = xfs_bmap_last_offset(ip, &last_block,
775                                                         XFS_DATA_FORK);
776                         if (error)
777                                 goto trans_cancel;
778
779                         last_block = XFS_FILEOFF_MAX(last_block, end_fsb);
780                         if ((map_start_fsb + count_fsb) > last_block) {
781                                 count_fsb = last_block - map_start_fsb;
782                                 if (count_fsb == 0) {
783                                         error = -EAGAIN;
784                                         goto trans_cancel;
785                                 }
786                         }
787
788                         /*
789                          * From this point onwards we overwrite the imap
790                          * pointer that the caller gave to us.
791                          */
792                         error = xfs_bmapi_write(tp, ip, map_start_fsb,
793                                                 count_fsb, flags, &first_block,
794                                                 nres, imap, &nimaps,
795                                                 &dfops);
796                         if (error)
797                                 goto trans_cancel;
798
799                         error = xfs_defer_finish(&tp, &dfops, NULL);
800                         if (error)
801                                 goto trans_cancel;
802
803                         error = xfs_trans_commit(tp);
804                         if (error)
805                                 goto error0;
806
807                         xfs_iunlock(ip, XFS_ILOCK_EXCL);
808                 }
809
810                 /*
811                  * See if we were able to allocate an extent that
812                  * covers at least part of the callers request
813                  */
814                 if (!(imap->br_startblock || XFS_IS_REALTIME_INODE(ip)))
815                         return xfs_alert_fsblock_zero(ip, imap);
816
817                 if ((offset_fsb >= imap->br_startoff) &&
818                     (offset_fsb < (imap->br_startoff +
819                                    imap->br_blockcount))) {
820                         XFS_STATS_INC(mp, xs_xstrat_quick);
821                         return 0;
822                 }
823
824                 /*
825                  * So far we have not mapped the requested part of the
826                  * file, just surrounding data, try again.
827                  */
828                 count_fsb -= imap->br_blockcount;
829                 map_start_fsb = imap->br_startoff + imap->br_blockcount;
830         }
831
832 trans_cancel:
833         xfs_defer_cancel(&dfops);
834         xfs_trans_cancel(tp);
835 error0:
836         xfs_iunlock(ip, XFS_ILOCK_EXCL);
837         return error;
838 }
839
840 int
841 xfs_iomap_write_unwritten(
842         xfs_inode_t     *ip,
843         xfs_off_t       offset,
844         xfs_off_t       count)
845 {
846         xfs_mount_t     *mp = ip->i_mount;
847         xfs_fileoff_t   offset_fsb;
848         xfs_filblks_t   count_fsb;
849         xfs_filblks_t   numblks_fsb;
850         xfs_fsblock_t   firstfsb;
851         int             nimaps;
852         xfs_trans_t     *tp;
853         xfs_bmbt_irec_t imap;
854         struct xfs_defer_ops dfops;
855         xfs_fsize_t     i_size;
856         uint            resblks;
857         int             error;
858
859         trace_xfs_unwritten_convert(ip, offset, count);
860
861         offset_fsb = XFS_B_TO_FSBT(mp, offset);
862         count_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)offset + count);
863         count_fsb = (xfs_filblks_t)(count_fsb - offset_fsb);
864
865         /*
866          * Reserve enough blocks in this transaction for two complete extent
867          * btree splits.  We may be converting the middle part of an unwritten
868          * extent and in this case we will insert two new extents in the btree
869          * each of which could cause a full split.
870          *
871          * This reservation amount will be used in the first call to
872          * xfs_bmbt_split() to select an AG with enough space to satisfy the
873          * rest of the operation.
874          */
875         resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0) << 1;
876
877         do {
878                 /*
879                  * Set up a transaction to convert the range of extents
880                  * from unwritten to real. Do allocations in a loop until
881                  * we have covered the range passed in.
882                  *
883                  * Note that we can't risk to recursing back into the filesystem
884                  * here as we might be asked to write out the same inode that we
885                  * complete here and might deadlock on the iolock.
886                  */
887                 error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, resblks, 0,
888                                 XFS_TRANS_RESERVE | XFS_TRANS_NOFS, &tp);
889                 if (error)
890                         return error;
891
892                 xfs_ilock(ip, XFS_ILOCK_EXCL);
893                 xfs_trans_ijoin(tp, ip, 0);
894
895                 /*
896                  * Modify the unwritten extent state of the buffer.
897                  */
898                 xfs_defer_init(&dfops, &firstfsb);
899                 nimaps = 1;
900                 error = xfs_bmapi_write(tp, ip, offset_fsb, count_fsb,
901                                         XFS_BMAPI_CONVERT, &firstfsb, resblks,
902                                         &imap, &nimaps, &dfops);
903                 if (error)
904                         goto error_on_bmapi_transaction;
905
906                 /*
907                  * Log the updated inode size as we go.  We have to be careful
908                  * to only log it up to the actual write offset if it is
909                  * halfway into a block.
910                  */
911                 i_size = XFS_FSB_TO_B(mp, offset_fsb + count_fsb);
912                 if (i_size > offset + count)
913                         i_size = offset + count;
914
915                 i_size = xfs_new_eof(ip, i_size);
916                 if (i_size) {
917                         ip->i_d.di_size = i_size;
918                         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
919                 }
920
921                 error = xfs_defer_finish(&tp, &dfops, NULL);
922                 if (error)
923                         goto error_on_bmapi_transaction;
924
925                 error = xfs_trans_commit(tp);
926                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
927                 if (error)
928                         return error;
929
930                 if (!(imap.br_startblock || XFS_IS_REALTIME_INODE(ip)))
931                         return xfs_alert_fsblock_zero(ip, &imap);
932
933                 if ((numblks_fsb = imap.br_blockcount) == 0) {
934                         /*
935                          * The numblks_fsb value should always get
936                          * smaller, otherwise the loop is stuck.
937                          */
938                         ASSERT(imap.br_blockcount);
939                         break;
940                 }
941                 offset_fsb += numblks_fsb;
942                 count_fsb -= numblks_fsb;
943         } while (count_fsb > 0);
944
945         return 0;
946
947 error_on_bmapi_transaction:
948         xfs_defer_cancel(&dfops);
949         xfs_trans_cancel(tp);
950         xfs_iunlock(ip, XFS_ILOCK_EXCL);
951         return error;
952 }
953
954 static inline bool imap_needs_alloc(struct inode *inode,
955                 struct xfs_bmbt_irec *imap, int nimaps)
956 {
957         return !nimaps ||
958                 imap->br_startblock == HOLESTARTBLOCK ||
959                 imap->br_startblock == DELAYSTARTBLOCK ||
960                 (IS_DAX(inode) && ISUNWRITTEN(imap));
961 }
962
963 static int
964 xfs_file_iomap_begin(
965         struct inode            *inode,
966         loff_t                  offset,
967         loff_t                  length,
968         unsigned                flags,
969         struct iomap            *iomap)
970 {
971         struct xfs_inode        *ip = XFS_I(inode);
972         struct xfs_mount        *mp = ip->i_mount;
973         struct xfs_bmbt_irec    imap;
974         xfs_fileoff_t           offset_fsb, end_fsb;
975         int                     nimaps = 1, error = 0;
976         bool                    shared = false, trimmed = false;
977         unsigned                lockmode;
978
979         if (XFS_FORCED_SHUTDOWN(mp))
980                 return -EIO;
981
982         if ((flags & IOMAP_WRITE) && !IS_DAX(inode) &&
983                    !xfs_get_extsz_hint(ip)) {
984                 /* Reserve delalloc blocks for regular writeback. */
985                 return xfs_file_iomap_begin_delay(inode, offset, length, flags,
986                                 iomap);
987         }
988
989         /*
990          * COW writes will allocate delalloc space, so we need to make sure
991          * to take the lock exclusively here.
992          */
993         if ((flags & (IOMAP_WRITE | IOMAP_ZERO)) && xfs_is_reflink_inode(ip)) {
994                 lockmode = XFS_ILOCK_EXCL;
995                 xfs_ilock(ip, XFS_ILOCK_EXCL);
996         } else {
997                 lockmode = xfs_ilock_data_map_shared(ip);
998         }
999
1000         ASSERT(offset <= mp->m_super->s_maxbytes);
1001         if ((xfs_fsize_t)offset + length > mp->m_super->s_maxbytes)
1002                 length = mp->m_super->s_maxbytes - offset;
1003         offset_fsb = XFS_B_TO_FSBT(mp, offset);
1004         end_fsb = XFS_B_TO_FSB(mp, offset + length);
1005
1006         error = xfs_bmapi_read(ip, offset_fsb, end_fsb - offset_fsb, &imap,
1007                                &nimaps, 0);
1008         if (error)
1009                 goto out_unlock;
1010
1011         if (flags & IOMAP_REPORT) {
1012                 /* Trim the mapping to the nearest shared extent boundary. */
1013                 error = xfs_reflink_trim_around_shared(ip, &imap, &shared,
1014                                 &trimmed);
1015                 if (error)
1016                         goto out_unlock;
1017         }
1018
1019         if ((flags & (IOMAP_WRITE | IOMAP_ZERO)) && xfs_is_reflink_inode(ip)) {
1020                 error = xfs_reflink_reserve_cow(ip, &imap, &shared);
1021                 if (error)
1022                         goto out_unlock;
1023
1024                 end_fsb = imap.br_startoff + imap.br_blockcount;
1025                 length = XFS_FSB_TO_B(mp, end_fsb) - offset;
1026         }
1027
1028         if ((flags & IOMAP_WRITE) && imap_needs_alloc(inode, &imap, nimaps)) {
1029                 /*
1030                  * We cap the maximum length we map here to MAX_WRITEBACK_PAGES
1031                  * pages to keep the chunks of work done where somewhat symmetric
1032                  * with the work writeback does. This is a completely arbitrary
1033                  * number pulled out of thin air as a best guess for initial
1034                  * testing.
1035                  *
1036                  * Note that the values needs to be less than 32-bits wide until
1037                  * the lower level functions are updated.
1038                  */
1039                 length = min_t(loff_t, length, 1024 * PAGE_SIZE);
1040                 /*
1041                  * xfs_iomap_write_direct() expects the shared lock. It
1042                  * is unlocked on return.
1043                  */
1044                 if (lockmode == XFS_ILOCK_EXCL)
1045                         xfs_ilock_demote(ip, lockmode);
1046                 error = xfs_iomap_write_direct(ip, offset, length, &imap,
1047                                 nimaps);
1048                 if (error)
1049                         return error;
1050
1051                 iomap->flags = IOMAP_F_NEW;
1052                 trace_xfs_iomap_alloc(ip, offset, length, 0, &imap);
1053         } else {
1054                 ASSERT(nimaps);
1055
1056                 xfs_iunlock(ip, lockmode);
1057                 trace_xfs_iomap_found(ip, offset, length, 0, &imap);
1058         }
1059
1060         xfs_bmbt_to_iomap(ip, iomap, &imap);
1061         if (shared)
1062                 iomap->flags |= IOMAP_F_SHARED;
1063         return 0;
1064 out_unlock:
1065         xfs_iunlock(ip, lockmode);
1066         return error;
1067 }
1068
1069 static int
1070 xfs_file_iomap_end_delalloc(
1071         struct xfs_inode        *ip,
1072         loff_t                  offset,
1073         loff_t                  length,
1074         ssize_t                 written)
1075 {
1076         struct xfs_mount        *mp = ip->i_mount;
1077         xfs_fileoff_t           start_fsb;
1078         xfs_fileoff_t           end_fsb;
1079         int                     error = 0;
1080
1081         start_fsb = XFS_B_TO_FSB(mp, offset + written);
1082         end_fsb = XFS_B_TO_FSB(mp, offset + length);
1083
1084         /*
1085          * Trim back delalloc blocks if we didn't manage to write the whole
1086          * range reserved.
1087          *
1088          * We don't need to care about racing delalloc as we hold i_mutex
1089          * across the reserve/allocate/unreserve calls. If there are delalloc
1090          * blocks in the range, they are ours.
1091          */
1092         if (start_fsb < end_fsb) {
1093                 xfs_ilock(ip, XFS_ILOCK_EXCL);
1094                 error = xfs_bmap_punch_delalloc_range(ip, start_fsb,
1095                                                end_fsb - start_fsb);
1096                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1097
1098                 if (error && !XFS_FORCED_SHUTDOWN(mp)) {
1099                         xfs_alert(mp, "%s: unable to clean up ino %lld",
1100                                 __func__, ip->i_ino);
1101                         return error;
1102                 }
1103         }
1104
1105         return 0;
1106 }
1107
1108 static int
1109 xfs_file_iomap_end(
1110         struct inode            *inode,
1111         loff_t                  offset,
1112         loff_t                  length,
1113         ssize_t                 written,
1114         unsigned                flags,
1115         struct iomap            *iomap)
1116 {
1117         if ((flags & IOMAP_WRITE) && iomap->type == IOMAP_DELALLOC)
1118                 return xfs_file_iomap_end_delalloc(XFS_I(inode), offset,
1119                                 length, written);
1120         return 0;
1121 }
1122
1123 struct iomap_ops xfs_iomap_ops = {
1124         .iomap_begin            = xfs_file_iomap_begin,
1125         .iomap_end              = xfs_file_iomap_end,
1126 };
1127
1128 static int
1129 xfs_xattr_iomap_begin(
1130         struct inode            *inode,
1131         loff_t                  offset,
1132         loff_t                  length,
1133         unsigned                flags,
1134         struct iomap            *iomap)
1135 {
1136         struct xfs_inode        *ip = XFS_I(inode);
1137         struct xfs_mount        *mp = ip->i_mount;
1138         xfs_fileoff_t           offset_fsb = XFS_B_TO_FSBT(mp, offset);
1139         xfs_fileoff_t           end_fsb = XFS_B_TO_FSB(mp, offset + length);
1140         struct xfs_bmbt_irec    imap;
1141         int                     nimaps = 1, error = 0;
1142         unsigned                lockmode;
1143
1144         if (XFS_FORCED_SHUTDOWN(mp))
1145                 return -EIO;
1146
1147         lockmode = xfs_ilock_data_map_shared(ip);
1148
1149         /* if there are no attribute fork or extents, return ENOENT */
1150         if (XFS_IFORK_Q(ip) || !ip->i_d.di_anextents) {
1151                 error = -ENOENT;
1152                 goto out_unlock;
1153         }
1154
1155         ASSERT(ip->i_d.di_aformat != XFS_DINODE_FMT_LOCAL);
1156         error = xfs_bmapi_read(ip, offset_fsb, end_fsb - offset_fsb, &imap,
1157                                &nimaps, XFS_BMAPI_ENTIRE | XFS_BMAPI_ATTRFORK);
1158 out_unlock:
1159         xfs_iunlock(ip, lockmode);
1160
1161         if (!error) {
1162                 ASSERT(nimaps);
1163                 xfs_bmbt_to_iomap(ip, iomap, &imap);
1164         }
1165
1166         return error;
1167 }
1168
1169 struct iomap_ops xfs_xattr_iomap_ops = {
1170         .iomap_begin            = xfs_xattr_iomap_begin,
1171 };