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