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