Whamcloud - gitweb
082d7ddef3fb8c0d7e8113c53c9155a9e418b7bf
[fs/lustre-release.git] / lustre / osd-zfs / osd_io.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2016, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/osd-zfs/osd_io.c
33  *
34  * Author: Alex Zhuravlev <bzzz@whamcloud.com>
35  * Author: Mike Pershin <tappro@whamcloud.com>
36  */
37
38 #define DEBUG_SUBSYSTEM S_OSD
39
40 #include <lustre_ver.h>
41 #include <libcfs/libcfs.h>
42 #include <obd_support.h>
43 #include <lustre_net.h>
44 #include <obd.h>
45 #include <obd_class.h>
46 #include <lustre_disk.h>
47 #include <lustre_fid.h>
48 #include <lustre/lustre_idl.h>  /* LLOG_MIN_CHUNK_SIZE definition */
49
50 #include "osd_internal.h"
51
52 #include <sys/dnode.h>
53 #include <sys/dbuf.h>
54 #include <sys/spa.h>
55 #include <sys/stat.h>
56 #include <sys/zap.h>
57 #include <sys/spa_impl.h>
58 #include <sys/zfs_znode.h>
59 #include <sys/dmu_tx.h>
60 #include <sys/dmu_objset.h>
61 #include <sys/dsl_prop.h>
62 #include <sys/sa_impl.h>
63 #include <sys/txg.h>
64
65 static char *osd_0copy_tag = "zerocopy";
66
67
68 static void record_start_io(struct osd_device *osd, int rw, int discont_pages)
69 {
70         struct obd_histogram *h = osd->od_brw_stats.hist;
71
72         if (rw == READ) {
73                 atomic_inc(&osd->od_r_in_flight);
74                 lprocfs_oh_tally(&h[BRW_R_RPC_HIST],
75                                  atomic_read(&osd->od_r_in_flight));
76                 lprocfs_oh_tally(&h[BRW_R_DISCONT_PAGES], discont_pages);
77
78         } else {
79                 atomic_inc(&osd->od_w_in_flight);
80                 lprocfs_oh_tally(&h[BRW_W_RPC_HIST],
81                                  atomic_read(&osd->od_w_in_flight));
82                 lprocfs_oh_tally(&h[BRW_W_DISCONT_PAGES], discont_pages);
83
84         }
85 }
86
87 static void record_end_io(struct osd_device *osd, int rw,
88                           unsigned long elapsed, int disksize, int npages)
89 {
90         struct obd_histogram *h = osd->od_brw_stats.hist;
91
92         if (rw == READ) {
93                 atomic_dec(&osd->od_r_in_flight);
94                 lprocfs_oh_tally_log2(&h[BRW_R_PAGES], npages);
95                 if (disksize > 0)
96                         lprocfs_oh_tally_log2(&h[BRW_R_DISK_IOSIZE], disksize);
97                 if (elapsed)
98                         lprocfs_oh_tally_log2(&h[BRW_R_IO_TIME], elapsed);
99
100         } else {
101                 atomic_dec(&osd->od_w_in_flight);
102                 lprocfs_oh_tally_log2(&h[BRW_W_PAGES], npages);
103                 if (disksize > 0)
104                         lprocfs_oh_tally_log2(&h[BRW_W_DISK_IOSIZE], disksize);
105                 if (elapsed)
106                         lprocfs_oh_tally_log2(&h[BRW_W_IO_TIME], elapsed);
107         }
108 }
109
110 static ssize_t osd_read(const struct lu_env *env, struct dt_object *dt,
111                         struct lu_buf *buf, loff_t *pos)
112 {
113         struct osd_object *obj  = osd_dt_obj(dt);
114         struct osd_device *osd = osd_obj2dev(obj);
115         uint64_t           old_size;
116         int                size = buf->lb_len;
117         int                rc;
118         unsigned long      start;
119
120         LASSERT(dt_object_exists(dt));
121         LASSERT(obj->oo_dn);
122
123         start = cfs_time_current();
124
125         read_lock(&obj->oo_attr_lock);
126         old_size = obj->oo_attr.la_size;
127         read_unlock(&obj->oo_attr_lock);
128
129         if (*pos + size > old_size) {
130                 if (old_size < *pos)
131                         return 0;
132                 else
133                         size = old_size - *pos;
134         }
135
136         record_start_io(osd, READ, 0);
137
138         rc = osd_dmu_read(osd, obj->oo_dn, *pos, size, buf->lb_buf,
139                           DMU_READ_PREFETCH);
140
141         record_end_io(osd, READ, cfs_time_current() - start, size,
142                       size >> PAGE_SHIFT);
143         if (rc == 0) {
144                 rc = size;
145                 *pos += size;
146         }
147         return rc;
148 }
149
150 static ssize_t osd_declare_write(const struct lu_env *env, struct dt_object *dt,
151                                 const struct lu_buf *buf, loff_t pos,
152                                 struct thandle *th)
153 {
154         struct osd_object  *obj  = osd_dt_obj(dt);
155         struct osd_device  *osd = osd_obj2dev(obj);
156         struct osd_thandle *oh;
157         uint64_t            oid;
158         ENTRY;
159
160         oh = container_of0(th, struct osd_thandle, ot_super);
161
162         /* in some cases declare can race with creation (e.g. llog)
163          * and we need to wait till object is initialized. notice
164          * LOHA_EXISTs is supposed to be the last step in the
165          * initialization */
166
167         /* size change (in dnode) will be declared by dmu_tx_hold_write() */
168         if (dt_object_exists(dt))
169                 oid = obj->oo_dn->dn_object;
170         else
171                 oid = DMU_NEW_OBJECT;
172
173         /* XXX: we still miss for append declaration support in ZFS
174          *      -1 means append which is used by llog mostly, llog
175          *      can grow upto LLOG_MIN_CHUNK_SIZE*8 records */
176         if (pos == -1)
177                 pos = max_t(loff_t, 256 * 8 * LLOG_MIN_CHUNK_SIZE,
178                             obj->oo_attr.la_size + (2 << 20));
179         osd_tx_hold_write(oh->ot_tx, oid, obj->oo_dn, pos, buf->lb_len);
180
181         /* dt_declare_write() is usually called for system objects, such
182          * as llog or last_rcvd files. We needn't enforce quota on those
183          * objects, so always set the lqi_space as 0. */
184         RETURN(osd_declare_quota(env, osd, obj->oo_attr.la_uid,
185                                  obj->oo_attr.la_gid, 0, oh, true, NULL,
186                                  false));
187 }
188
189 static ssize_t osd_write(const struct lu_env *env, struct dt_object *dt,
190                         const struct lu_buf *buf, loff_t *pos,
191                         struct thandle *th, int ignore_quota)
192 {
193         struct osd_object  *obj  = osd_dt_obj(dt);
194         struct osd_device  *osd = osd_obj2dev(obj);
195         struct osd_thandle *oh;
196         uint64_t            offset = *pos;
197         int                 rc;
198
199         ENTRY;
200
201         LASSERT(dt_object_exists(dt));
202         LASSERT(obj->oo_dn);
203
204         LASSERT(th != NULL);
205         oh = container_of0(th, struct osd_thandle, ot_super);
206
207         osd_dmu_write(osd, obj->oo_dn, offset, (uint64_t)buf->lb_len,
208                       buf->lb_buf, oh->ot_tx);
209         write_lock(&obj->oo_attr_lock);
210         if (obj->oo_attr.la_size < offset + buf->lb_len) {
211                 obj->oo_attr.la_size = offset + buf->lb_len;
212                 write_unlock(&obj->oo_attr_lock);
213                 /* osd_object_sa_update() will be copying directly from oo_attr
214                  * into dbuf.  any update within a single txg will copy the
215                  * most actual */
216                 rc = osd_object_sa_update(obj, SA_ZPL_SIZE(osd),
217                                         &obj->oo_attr.la_size, 8, oh);
218                 if (unlikely(rc))
219                         GOTO(out, rc);
220         } else {
221                 write_unlock(&obj->oo_attr_lock);
222         }
223
224         *pos += buf->lb_len;
225         rc = buf->lb_len;
226
227 out:
228         RETURN(rc);
229 }
230
231 /*
232  * XXX: for the moment I don't want to use lnb_flags for osd-internal
233  *      purposes as it's not very well defined ...
234  *      instead I use the lowest bit of the address so that:
235  *        arc buffer:  .lnb_data = abuf          (arc we loan for write)
236  *        dbuf buffer: .lnb_data = dbuf | 1      (dbuf we get for read)
237  *        copy buffer: .lnb_page->mapping = obj (page we allocate for write)
238  *
239  *      bzzz, to blame
240  */
241 static int osd_bufs_put(const struct lu_env *env, struct dt_object *dt,
242                         struct niobuf_local *lnb, int npages)
243 {
244         struct osd_object *obj  = osd_dt_obj(dt);
245         struct osd_device *osd = osd_obj2dev(obj);
246         unsigned long      ptr;
247         int                i;
248
249         LASSERT(dt_object_exists(dt));
250         LASSERT(obj->oo_dn);
251
252         for (i = 0; i < npages; i++) {
253                 if (lnb[i].lnb_page == NULL)
254                         continue;
255                 if (lnb[i].lnb_page->mapping == (void *)obj) {
256                         /* this is anonymous page allocated for copy-write */
257                         lnb[i].lnb_page->mapping = NULL;
258                         __free_page(lnb[i].lnb_page);
259                         atomic_dec(&osd->od_zerocopy_alloc);
260                 } else {
261                         /* see comment in osd_bufs_get_read() */
262                         ptr = (unsigned long)lnb[i].lnb_data;
263                         if (ptr & 1UL) {
264                                 ptr &= ~1UL;
265                                 dmu_buf_rele((void *)ptr, osd_0copy_tag);
266                                 atomic_dec(&osd->od_zerocopy_pin);
267                         } else if (lnb[i].lnb_data != NULL) {
268                                 int j, apages, abufsz;
269                                 abufsz = arc_buf_size(lnb[i].lnb_data);
270                                 apages = abufsz / PAGE_SIZE;
271                                 /* these references to pages must be invalidated
272                                  * to prevent access in osd_bufs_put() */
273                                 for (j = 0; j < apages; j++)
274                                         lnb[i + j].lnb_page = NULL;
275                                 dmu_return_arcbuf(lnb[i].lnb_data);
276                                 atomic_dec(&osd->od_zerocopy_loan);
277                         }
278                 }
279                 lnb[i].lnb_page = NULL;
280                 lnb[i].lnb_data = NULL;
281         }
282
283         return 0;
284 }
285
286 static inline struct page *kmem_to_page(void *addr)
287 {
288         LASSERT(!((unsigned long)addr & ~PAGE_MASK));
289         if (is_vmalloc_addr(addr))
290                 return vmalloc_to_page(addr);
291         else
292                 return virt_to_page(addr);
293 }
294
295 /**
296  * Prepare buffers for read.
297  *
298  * The function maps the range described by \a off and \a len to \a lnb array.
299  * dmu_buf_hold_array_by_bonus() finds/creates appropriate ARC buffers, then
300  * we fill \a lnb array with the pages storing ARC buffers. Notice the current
301  * implementationt passes TRUE to dmu_buf_hold_array_by_bonus() to fill ARC
302  * buffers with actual data, I/O is done in the conext of osd_bufs_get_read().
303  * A better implementation would just return the buffers (potentially unfilled)
304  * and subsequent osd_read_prep() would do I/O for many ranges concurrently.
305  *
306  * \param[in] env       environment
307  * \param[in] obj       object
308  * \param[in] off       offset in bytes
309  * \param[in] len       the number of bytes to access
310  * \param[out] lnb      array of local niobufs pointing to the buffers with data
311  *
312  * \retval              0 for success
313  * \retval              negative error number of failure
314  */
315 static int osd_bufs_get_read(const struct lu_env *env, struct osd_object *obj,
316                                 loff_t off, ssize_t len, struct niobuf_local *lnb)
317 {
318         struct osd_device *osd = osd_obj2dev(obj);
319         unsigned long      start = cfs_time_current();
320         int                rc, i, numbufs, npages = 0;
321         dmu_buf_t        **dbp;
322         ENTRY;
323
324         record_start_io(osd, READ, 0);
325
326         /* grab buffers for read:
327          * OSD API let us to grab buffers first, then initiate IO(s)
328          * so that all required IOs will be done in parallel, but at the
329          * moment DMU doesn't provide us with a method to grab buffers.
330          * If we discover this is a vital for good performance we
331          * can get own replacement for dmu_buf_hold_array_by_bonus().
332          */
333         while (len > 0) {
334                 rc = -dmu_buf_hold_array_by_bonus(&obj->oo_dn->dn_bonus->db,
335                                                   off, len, TRUE, osd_0copy_tag,
336                                                   &numbufs, &dbp);
337                 if (unlikely(rc))
338                         GOTO(err, rc);
339
340                 for (i = 0; i < numbufs; i++) {
341                         int bufoff, tocpy, thispage;
342                         void *dbf = dbp[i];
343
344                         LASSERT(len > 0);
345
346                         atomic_inc(&osd->od_zerocopy_pin);
347
348                         bufoff = off - dbp[i]->db_offset;
349                         tocpy = min_t(int, dbp[i]->db_size - bufoff, len);
350
351                         /* kind of trick to differentiate dbuf vs. arcbuf */
352                         LASSERT(((unsigned long)dbp[i] & 1) == 0);
353                         dbf = (void *) ((unsigned long)dbp[i] | 1);
354
355                         while (tocpy > 0) {
356                                 thispage = PAGE_SIZE;
357                                 thispage -= bufoff & (PAGE_SIZE - 1);
358                                 thispage = min(tocpy, thispage);
359
360                                 lnb->lnb_rc = 0;
361                                 lnb->lnb_file_offset = off;
362                                 lnb->lnb_page_offset = bufoff & ~PAGE_MASK;
363                                 lnb->lnb_len = thispage;
364                                 lnb->lnb_page = kmem_to_page(dbp[i]->db_data +
365                                                              bufoff);
366                                 /* mark just a single slot: we need this
367                                  * reference to dbuf to be released once */
368                                 lnb->lnb_data = dbf;
369                                 dbf = NULL;
370
371                                 tocpy -= thispage;
372                                 len -= thispage;
373                                 bufoff += thispage;
374                                 off += thispage;
375
376                                 npages++;
377                                 lnb++;
378                         }
379
380                         /* steal dbuf so dmu_buf_rele_array() can't release
381                          * it */
382                         dbp[i] = NULL;
383                 }
384
385                 dmu_buf_rele_array(dbp, numbufs, osd_0copy_tag);
386         }
387
388         record_end_io(osd, READ, cfs_time_current() - start,
389                       npages * PAGE_SIZE, npages);
390
391         RETURN(npages);
392
393 err:
394         LASSERT(rc < 0);
395         osd_bufs_put(env, &obj->oo_dt, lnb - npages, npages);
396         RETURN(rc);
397 }
398
399 static inline arc_buf_t *osd_request_arcbuf(dnode_t *dn, size_t bs)
400 {
401         arc_buf_t *abuf;
402
403         abuf = dmu_request_arcbuf(&dn->dn_bonus->db, bs);
404         if (unlikely(!abuf))
405                 return ERR_PTR(-ENOMEM);
406
407 #if ZFS_VERSION_CODE < OBD_OCD_VERSION(0, 7, 0, 0)
408         /**
409          * ZFS prior to 0.7.0 doesn't guarantee PAGE_SIZE alignment for zio
410          * blocks smaller than (PAGE_SIZE << 2). This poses a problem of
411          * setting up page array for RDMA transfer. See LU-9305.
412          */
413         if ((unsigned long)abuf->b_data & ~PAGE_MASK) {
414                 dmu_return_arcbuf(abuf);
415                 return NULL;
416         }
417 #endif
418
419         return abuf;
420 }
421
422 static int osd_bufs_get_write(const struct lu_env *env, struct osd_object *obj,
423                                 loff_t off, ssize_t len, struct niobuf_local *lnb)
424 {
425         struct osd_device *osd = osd_obj2dev(obj);
426         int                plen, off_in_block, sz_in_block;
427         int                rc, i = 0, npages = 0;
428         dnode_t *dn = obj->oo_dn;
429         arc_buf_t *abuf;
430         uint32_t bs = dn->dn_datablksz;
431         ENTRY;
432
433         /*
434          * currently only full blocks are subject to zerocopy approach:
435          * so that we're sure nobody is trying to update the same block
436          */
437         while (len > 0) {
438                 LASSERT(npages < PTLRPC_MAX_BRW_PAGES);
439
440                 off_in_block = off & (bs - 1);
441                 sz_in_block = min_t(int, bs - off_in_block, len);
442
443                 abuf = NULL;
444                 if (sz_in_block == bs) {
445                         /* full block, try to use zerocopy */
446                         abuf = osd_request_arcbuf(dn, bs);
447                         if (unlikely(IS_ERR(abuf)))
448                                 GOTO(out_err, rc = PTR_ERR(abuf));
449                 }
450
451                 if (abuf != NULL) {
452                         atomic_inc(&osd->od_zerocopy_loan);
453
454                         /* go over pages arcbuf contains, put them as
455                          * local niobufs for ptlrpc's bulks */
456                         while (sz_in_block > 0) {
457                                 plen = min_t(int, sz_in_block, PAGE_SIZE);
458
459                                 lnb[i].lnb_file_offset = off;
460                                 lnb[i].lnb_page_offset = 0;
461                                 lnb[i].lnb_len = plen;
462                                 lnb[i].lnb_rc = 0;
463                                 if (sz_in_block == bs)
464                                         lnb[i].lnb_data = abuf;
465                                 else
466                                         lnb[i].lnb_data = NULL;
467
468                                 /* this one is not supposed to fail */
469                                 lnb[i].lnb_page = kmem_to_page(abuf->b_data +
470                                                         off_in_block);
471                                 LASSERT(lnb[i].lnb_page);
472
473                                 lprocfs_counter_add(osd->od_stats,
474                                                 LPROC_OSD_ZEROCOPY_IO, 1);
475
476                                 sz_in_block -= plen;
477                                 len -= plen;
478                                 off += plen;
479                                 off_in_block += plen;
480                                 i++;
481                                 npages++;
482                         }
483                 } else {
484                         if (off_in_block == 0 && len < bs &&
485                                         off + len >= obj->oo_attr.la_size)
486                                 lprocfs_counter_add(osd->od_stats,
487                                                 LPROC_OSD_TAIL_IO, 1);
488
489                         /* can't use zerocopy, allocate temp. buffers */
490                         while (sz_in_block > 0) {
491                                 plen = min_t(int, sz_in_block, PAGE_SIZE);
492
493                                 lnb[i].lnb_file_offset = off;
494                                 lnb[i].lnb_page_offset = 0;
495                                 lnb[i].lnb_len = plen;
496                                 lnb[i].lnb_rc = 0;
497                                 lnb[i].lnb_data = NULL;
498
499                                 lnb[i].lnb_page = alloc_page(OSD_GFP_IO);
500                                 if (unlikely(lnb[i].lnb_page == NULL))
501                                         GOTO(out_err, rc = -ENOMEM);
502
503                                 LASSERT(lnb[i].lnb_page->mapping == NULL);
504                                 lnb[i].lnb_page->mapping = (void *)obj;
505
506                                 atomic_inc(&osd->od_zerocopy_alloc);
507                                 lprocfs_counter_add(osd->od_stats,
508                                                 LPROC_OSD_COPY_IO, 1);
509
510                                 sz_in_block -= plen;
511                                 len -= plen;
512                                 off += plen;
513                                 i++;
514                                 npages++;
515                         }
516                 }
517         }
518
519         RETURN(npages);
520
521 out_err:
522         osd_bufs_put(env, &obj->oo_dt, lnb, npages);
523         RETURN(rc);
524 }
525
526 static int osd_bufs_get(const struct lu_env *env, struct dt_object *dt,
527                         loff_t offset, ssize_t len, struct niobuf_local *lnb,
528                         int rw)
529 {
530         struct osd_object *obj  = osd_dt_obj(dt);
531         int                rc;
532
533         LASSERT(dt_object_exists(dt));
534         LASSERT(obj->oo_dn);
535
536         if (rw == 0)
537                 rc = osd_bufs_get_read(env, obj, offset, len, lnb);
538         else
539                 rc = osd_bufs_get_write(env, obj, offset, len, lnb);
540
541         return rc;
542 }
543
544 static int osd_write_prep(const struct lu_env *env, struct dt_object *dt,
545                         struct niobuf_local *lnb, int npages)
546 {
547         struct osd_object *obj = osd_dt_obj(dt);
548
549         LASSERT(dt_object_exists(dt));
550         LASSERT(obj->oo_dn);
551
552         return 0;
553 }
554
555 static inline uint64_t osd_roundup2blocksz(uint64_t size,
556                                            uint64_t offset,
557                                            uint32_t blksz)
558 {
559         LASSERT(blksz > 0);
560
561         size += offset % blksz;
562
563         if (likely(is_power_of_2(blksz)))
564                 return PO2_ROUNDUP_TYPED(size, blksz, uint64_t);
565
566         size += blksz - 1;
567         do_div(size, blksz);
568         return size * blksz;
569 }
570
571 static int osd_declare_write_commit(const struct lu_env *env,
572                                     struct dt_object *dt,
573                                     struct niobuf_local *lnb, int npages,
574                                     struct thandle *th)
575 {
576         struct osd_object  *obj = osd_dt_obj(dt);
577         struct osd_device  *osd = osd_obj2dev(obj);
578         struct osd_thandle *oh;
579         uint64_t            offset = 0;
580         uint32_t            size = 0;
581         uint32_t blksz = obj->oo_dn->dn_datablksz;
582         int                 i, rc, flags = 0;
583         bool                ignore_quota = false, synced = false;
584         long long           space = 0;
585         struct page        *last_page = NULL;
586         unsigned long       discont_pages = 0;
587         ENTRY;
588
589         LASSERT(dt_object_exists(dt));
590         LASSERT(obj->oo_dn);
591
592         LASSERT(lnb);
593         LASSERT(npages > 0);
594
595         oh = container_of0(th, struct osd_thandle, ot_super);
596
597         for (i = 0; i < npages; i++) {
598                 if (last_page && lnb[i].lnb_page->index != (last_page->index + 1))
599                         ++discont_pages;
600                 last_page = lnb[i].lnb_page;
601                 if (lnb[i].lnb_rc)
602                         /* ENOSPC, network RPC error, etc.
603                          * We don't want to book space for pages which will be
604                          * skipped in osd_write_commit(). Hence we skip pages
605                          * with lnb_rc != 0 here too */
606                         continue;
607                 /* ignore quota for the whole request if any page is from
608                  * client cache or written by root.
609                  *
610                  * XXX once we drop the 1.8 client support, the checking
611                  * for whether page is from cache can be simplified as:
612                  * !(lnb[i].flags & OBD_BRW_SYNC)
613                  *
614                  * XXX we could handle this on per-lnb basis as done by
615                  * grant. */
616                 if ((lnb[i].lnb_flags & OBD_BRW_NOQUOTA) ||
617                     (lnb[i].lnb_flags & (OBD_BRW_FROM_GRANT | OBD_BRW_SYNC)) ==
618                     OBD_BRW_FROM_GRANT)
619                         ignore_quota = true;
620                 if (size == 0) {
621                         /* first valid lnb */
622                         offset = lnb[i].lnb_file_offset;
623                         size = lnb[i].lnb_len;
624                         continue;
625                 }
626                 if (offset + size == lnb[i].lnb_file_offset) {
627                         /* this lnb is contiguous to the previous one */
628                         size += lnb[i].lnb_len;
629                         continue;
630                 }
631
632                 osd_tx_hold_write(oh->ot_tx, obj->oo_dn->dn_object,
633                                   obj->oo_dn, offset, size);
634                 /* Estimating space to be consumed by a write is rather
635                  * complicated with ZFS. As a consequence, we don't account for
636                  * indirect blocks and just use as a rough estimate the worse
637                  * case where the old space is being held by a snapshot. Quota
638                  * overrun will be adjusted once the operation is committed, if
639                  * required. */
640                 space += osd_roundup2blocksz(size, offset, blksz);
641
642                 offset = lnb[i].lnb_file_offset;
643                 size = lnb[i].lnb_len;
644         }
645
646         if (size) {
647                 osd_tx_hold_write(oh->ot_tx, obj->oo_dn->dn_object, obj->oo_dn,
648                                   offset, size);
649                 space += osd_roundup2blocksz(size, offset, blksz);
650         }
651
652         oh->ot_write_commit = 1; /* used in osd_trans_start() for fail_loc */
653
654         /* backend zfs filesystem might be configured to store multiple data
655          * copies */
656         space  *= osd->od_os->os_copies;
657         space   = toqb(space);
658         CDEBUG(D_QUOTA, "writing %d pages, reserving %lldK of quota space\n",
659                npages, space);
660
661         record_start_io(osd, WRITE, discont_pages);
662 retry:
663         /* acquire quota space if needed */
664         rc = osd_declare_quota(env, osd, obj->oo_attr.la_uid,
665                                obj->oo_attr.la_gid, space, oh, true, &flags,
666                                ignore_quota);
667
668         if (!synced && rc == -EDQUOT && (flags & QUOTA_FL_SYNC) != 0) {
669                 dt_sync(env, th->th_dev);
670                 synced = true;
671                 CDEBUG(D_QUOTA, "retry after sync\n");
672                 flags = 0;
673                 goto retry;
674         }
675
676         /* we need only to store the overquota flags in the first lnb for
677          * now, once we support multiple objects BRW, this code needs be
678          * revised. */
679         if (flags & QUOTA_FL_OVER_USRQUOTA)
680                 lnb[0].lnb_flags |= OBD_BRW_OVER_USRQUOTA;
681         if (flags & QUOTA_FL_OVER_GRPQUOTA)
682                 lnb[0].lnb_flags |= OBD_BRW_OVER_GRPQUOTA;
683
684         RETURN(rc);
685 }
686
687 /**
688  * Policy to grow ZFS block size by write pattern.
689  * For sequential write, it grows block size gradually until it reaches the
690  * maximum blocksize the dataset can support. Otherwise, it will pick a
691  * a block size by the writing region of this I/O.
692  */
693 static int osd_grow_blocksize(struct osd_object *obj, struct osd_thandle *oh,
694                               uint64_t start, uint64_t end)
695 {
696         struct osd_device       *osd = osd_obj2dev(obj);
697         dnode_t *dn = obj->oo_dn;
698         uint32_t                 blksz;
699         int                      rc = 0;
700
701         ENTRY;
702
703         if (dn->dn_maxblkid > 0) /* can't change block size */
704                 GOTO(out, rc);
705
706         if (dn->dn_datablksz >= osd->od_max_blksz)
707                 GOTO(out, rc);
708
709         down_write(&obj->oo_guard);
710
711         blksz = dn->dn_datablksz;
712         if (blksz >= osd->od_max_blksz) /* check again after grabbing lock */
713                 GOTO(out_unlock, rc);
714
715         /* now ZFS can support up to 16MB block size, and if the write
716          * is sequential, it just increases the block size gradually */
717         if (start <= blksz) { /* sequential */
718                 blksz = (uint32_t)min_t(uint64_t, osd->od_max_blksz, end);
719         } else { /* sparse, pick a block size by write region */
720                 blksz = (uint32_t)min_t(uint64_t, osd->od_max_blksz,
721                                         end - start);
722         }
723
724         if (!is_power_of_2(blksz))
725                 blksz = size_roundup_power2(blksz);
726
727         if (blksz > dn->dn_datablksz) {
728                 rc = -dmu_object_set_blocksize(osd->od_os, dn->dn_object,
729                                                blksz, 0, oh->ot_tx);
730                 LASSERT(ergo(rc == 0, dn->dn_datablksz >= blksz));
731                 if (rc < 0)
732                         CDEBUG(D_INODE, "object "DFID": change block size"
733                                "%u -> %u error rc = %d\n",
734                                PFID(lu_object_fid(&obj->oo_dt.do_lu)),
735                                dn->dn_datablksz, blksz, rc);
736         }
737         EXIT;
738 out_unlock:
739         up_write(&obj->oo_guard);
740 out:
741         return rc;
742 }
743
744 static int osd_write_commit(const struct lu_env *env, struct dt_object *dt,
745                         struct niobuf_local *lnb, int npages,
746                         struct thandle *th)
747 {
748         struct osd_object  *obj  = osd_dt_obj(dt);
749         struct osd_device  *osd = osd_obj2dev(obj);
750         struct osd_thandle *oh;
751         uint64_t            new_size = 0;
752         int                 i, rc = 0;
753         unsigned long      iosize = 0;
754         ENTRY;
755
756         LASSERT(dt_object_exists(dt));
757         LASSERT(obj->oo_dn);
758
759         LASSERT(th != NULL);
760         oh = container_of0(th, struct osd_thandle, ot_super);
761
762         /* adjust block size. Assume the buffers are sorted. */
763         (void)osd_grow_blocksize(obj, oh, lnb[0].lnb_file_offset,
764                                  lnb[npages - 1].lnb_file_offset +
765                                  lnb[npages - 1].lnb_len);
766
767         /* LU-8791: take oo_guard to avoid the deadlock that changing block
768          * size and assigning arcbuf take place at the same time.
769          *
770          * Thread 1:
771          * osd_write_commit()
772          *  -> osd_grow_blocksize() with osd_object::oo_guard held
773          *   -> dmu_object_set_blocksize()
774          *    -> dnode_set_blksz(), with dnode_t::dn_struct_rwlock
775          *       write lock held
776          *     -> dbuf_new_size()
777          *      -> dmu_buf_will_dirty()
778          *       -> dbuf_read()
779          *        -> wait for the dbuf state to change
780          * Thread 2:
781          * osd_write_commit()
782          *  -> dmu_assign_arcbuf()
783          *   -> dbuf_assign_arcbuf(), set dbuf state to DB_FILL
784          *    -> dbuf_dirty()
785          *     -> try to hold the read lock of dnode_t::dn_struct_rwlock
786          *
787          * By taking the read lock, it can avoid thread 2 to enter into the
788          * critical section of assigning the arcbuf, while thread 1 is
789          * changing the block size.
790          */
791         down_read(&obj->oo_guard);
792         for (i = 0; i < npages; i++) {
793                 CDEBUG(D_INODE, "write %u bytes at %u\n",
794                         (unsigned) lnb[i].lnb_len,
795                         (unsigned) lnb[i].lnb_file_offset);
796
797                 if (lnb[i].lnb_rc) {
798                         /* ENOSPC, network RPC error, etc.
799                          * Unlike ldiskfs, zfs allocates new blocks on rewrite,
800                          * so we skip this page if lnb_rc is set to -ENOSPC */
801                         CDEBUG(D_INODE, "obj "DFID": skipping lnb[%u]: rc=%d\n",
802                                 PFID(lu_object_fid(&dt->do_lu)), i,
803                                 lnb[i].lnb_rc);
804                         continue;
805                 }
806
807                 if (new_size < lnb[i].lnb_file_offset + lnb[i].lnb_len)
808                         new_size = lnb[i].lnb_file_offset + lnb[i].lnb_len;
809                 if (lnb[i].lnb_page == NULL)
810                         continue;
811
812                 if (lnb[i].lnb_page->mapping == (void *)obj) {
813                         osd_dmu_write(osd, obj->oo_dn, lnb[i].lnb_file_offset,
814                                       lnb[i].lnb_len, kmap(lnb[i].lnb_page),
815                                       oh->ot_tx);
816                         kunmap(lnb[i].lnb_page);
817                         iosize += lnb[i].lnb_len;
818                 } else if (lnb[i].lnb_data) {
819                         int j, apages, abufsz;
820                         LASSERT(((unsigned long)lnb[i].lnb_data & 1) == 0);
821                         /* buffer loaned for zerocopy, try to use it.
822                          * notice that dmu_assign_arcbuf() is smart
823                          * enough to recognize changed blocksize
824                          * in this case it fallbacks to dmu_write() */
825                         abufsz = arc_buf_size(lnb[i].lnb_data);
826                         LASSERT(abufsz & PAGE_MASK);
827                         apages = abufsz / PAGE_SIZE;
828                         LASSERT(i + apages <= npages);
829                         /* these references to pages must be invalidated
830                          * to prevent access in osd_bufs_put() */
831                         for (j = 0; j < apages; j++)
832                                 lnb[i + j].lnb_page = NULL;
833                         dmu_assign_arcbuf(&obj->oo_dn->dn_bonus->db,
834                                           lnb[i].lnb_file_offset,
835                                           lnb[i].lnb_data, oh->ot_tx);
836                         /* drop the reference, otherwise osd_put_bufs()
837                          * will be releasing it - bad! */
838                         lnb[i].lnb_data = NULL;
839                         atomic_dec(&osd->od_zerocopy_loan);
840                         iosize += abufsz;
841                 }
842
843         }
844         up_read(&obj->oo_guard);
845
846         if (unlikely(new_size == 0)) {
847                 /* no pages to write, no transno is needed */
848                 th->th_local = 1;
849                 /* it is important to return 0 even when all lnb_rc == -ENOSPC
850                  * since ofd_commitrw_write() retries several times on ENOSPC */
851                 record_end_io(osd, WRITE, 0, 0, 0);
852                 RETURN(0);
853         }
854
855         write_lock(&obj->oo_attr_lock);
856         if (obj->oo_attr.la_size < new_size) {
857                 obj->oo_attr.la_size = new_size;
858                 write_unlock(&obj->oo_attr_lock);
859                 /* osd_object_sa_update() will be copying directly from
860                  * oo_attr into dbuf. any update within a single txg will copy
861                  * the most actual */
862                 rc = osd_object_sa_update(obj, SA_ZPL_SIZE(osd),
863                                           &obj->oo_attr.la_size, 8, oh);
864         } else {
865                 write_unlock(&obj->oo_attr_lock);
866         }
867
868         record_end_io(osd, WRITE, 0, iosize, npages);
869
870         RETURN(rc);
871 }
872
873 static int osd_read_prep(const struct lu_env *env, struct dt_object *dt,
874                         struct niobuf_local *lnb, int npages)
875 {
876         struct osd_object *obj  = osd_dt_obj(dt);
877         int                i;
878         loff_t             eof;
879
880         LASSERT(dt_object_exists(dt));
881         LASSERT(obj->oo_dn);
882
883         read_lock(&obj->oo_attr_lock);
884         eof = obj->oo_attr.la_size;
885         read_unlock(&obj->oo_attr_lock);
886
887         for (i = 0; i < npages; i++) {
888                 if (unlikely(lnb[i].lnb_rc < 0))
889                         continue;
890
891                 lnb[i].lnb_rc = lnb[i].lnb_len;
892
893                 if (lnb[i].lnb_file_offset + lnb[i].lnb_len >= eof) {
894                         if (eof <= lnb[i].lnb_file_offset)
895                                 lnb[i].lnb_rc = 0;
896                         else
897                                 lnb[i].lnb_rc = eof - lnb[i].lnb_file_offset;
898
899                         /* all subsequent rc should be 0 */
900                         while (++i < npages)
901                                 lnb[i].lnb_rc = 0;
902                         break;
903                 }
904         }
905
906         return 0;
907 }
908
909 /*
910  * Punch/truncate an object
911  *
912  *      IN:     db  - dmu_buf of the object to free data in.
913  *              off - start of section to free.
914  *              len - length of section to free (DMU_OBJECT_END => to EOF).
915  *
916  *      RETURN: 0 if success
917  *              error code if failure
918  *
919  * The transaction passed to this routine must have
920  * dmu_tx_hold_sa() and if off < size, dmu_tx_hold_free()
921  * called and then assigned to a transaction group.
922  */
923 static int __osd_object_punch(objset_t *os, dnode_t *dn, dmu_tx_t *tx,
924                                 uint64_t size, uint64_t off, uint64_t len)
925 {
926         int rc = 0;
927
928         /* Assert that the transaction has been assigned to a
929            transaction group. */
930         LASSERT(tx->tx_txg != 0);
931         /*
932          * Nothing to do if file already at desired length.
933          */
934         if (len == DMU_OBJECT_END && size == off)
935                 return 0;
936
937         /* XXX: dnode_free_range() can be used to save on dnode lookup */
938         if (off < size)
939                 dmu_free_range(os, dn->dn_object, off, len, tx);
940
941         return rc;
942 }
943
944 static int osd_punch(const struct lu_env *env, struct dt_object *dt,
945                         __u64 start, __u64 end, struct thandle *th)
946 {
947         struct osd_object  *obj = osd_dt_obj(dt);
948         struct osd_device  *osd = osd_obj2dev(obj);
949         struct osd_thandle *oh;
950         __u64               len;
951         int                 rc = 0;
952         ENTRY;
953
954         LASSERT(dt_object_exists(dt));
955         LASSERT(osd_invariant(obj));
956
957         LASSERT(th != NULL);
958         oh = container_of0(th, struct osd_thandle, ot_super);
959
960         write_lock(&obj->oo_attr_lock);
961         /* truncate */
962         if (end == OBD_OBJECT_EOF || end >= obj->oo_attr.la_size)
963                 len = DMU_OBJECT_END;
964         else
965                 len = end - start;
966         write_unlock(&obj->oo_attr_lock);
967
968         rc = __osd_object_punch(osd->od_os, obj->oo_dn, oh->ot_tx,
969                                 obj->oo_attr.la_size, start, len);
970         /* set new size */
971         if (len == DMU_OBJECT_END) {
972                 write_lock(&obj->oo_attr_lock);
973                 obj->oo_attr.la_size = start;
974                 write_unlock(&obj->oo_attr_lock);
975                 rc = osd_object_sa_update(obj, SA_ZPL_SIZE(osd),
976                                           &obj->oo_attr.la_size, 8, oh);
977         }
978         RETURN(rc);
979 }
980
981 static int osd_declare_punch(const struct lu_env *env, struct dt_object *dt,
982                         __u64 start, __u64 end, struct thandle *handle)
983 {
984         struct osd_object  *obj = osd_dt_obj(dt);
985         struct osd_device  *osd = osd_obj2dev(obj);
986         struct osd_thandle *oh;
987         __u64               len;
988         ENTRY;
989
990         oh = container_of0(handle, struct osd_thandle, ot_super);
991
992         read_lock(&obj->oo_attr_lock);
993         if (end == OBD_OBJECT_EOF || end >= obj->oo_attr.la_size)
994                 len = DMU_OBJECT_END;
995         else
996                 len = end - start;
997
998         /* declare we'll free some blocks ... */
999         if (start < obj->oo_attr.la_size) {
1000                 read_unlock(&obj->oo_attr_lock);
1001                 dmu_tx_hold_free(oh->ot_tx, obj->oo_dn->dn_object, start, len);
1002         } else {
1003                 read_unlock(&obj->oo_attr_lock);
1004         }
1005
1006         RETURN(osd_declare_quota(env, osd, obj->oo_attr.la_uid,
1007                                  obj->oo_attr.la_gid, 0, oh, true, NULL,
1008                                  false));
1009 }
1010
1011 static int osd_ladvise(const struct lu_env *env, struct dt_object *dt,
1012                        __u64 start, __u64 end, enum lu_ladvise_type advice)
1013 {
1014         int     rc;
1015         ENTRY;
1016
1017         switch (advice) {
1018         default:
1019                 rc = -ENOTSUPP;
1020                 break;
1021         }
1022
1023         RETURN(rc);
1024 }
1025
1026 struct dt_body_operations osd_body_ops = {
1027         .dbo_read                       = osd_read,
1028         .dbo_declare_write              = osd_declare_write,
1029         .dbo_write                      = osd_write,
1030         .dbo_bufs_get                   = osd_bufs_get,
1031         .dbo_bufs_put                   = osd_bufs_put,
1032         .dbo_write_prep                 = osd_write_prep,
1033         .dbo_declare_write_commit       = osd_declare_write_commit,
1034         .dbo_write_commit               = osd_write_commit,
1035         .dbo_read_prep                  = osd_read_prep,
1036         .dbo_declare_punch              = osd_declare_punch,
1037         .dbo_punch                      = osd_punch,
1038         .dbo_ladvise                    = osd_ladvise,
1039 };