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