Whamcloud - gitweb
LU-6245 libcfs: remove prim wrappers for libcfs
[fs/lustre-release.git] / lustre / osd-zfs / osd_handler.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.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2012, 2014, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/osd-zfs/osd_handler.c
37  * Top-level entry points into osd module
38  *
39  * Author: Alex Zhuravlev <bzzz@whamcloud.com>
40  * Author: Mike Pershin <tappro@whamcloud.com>
41  * Author: Johann Lombardi <johann@whamcloud.com>
42  */
43
44 #define DEBUG_SUBSYSTEM S_OSD
45
46 #include <lustre_ver.h>
47 #include <libcfs/libcfs.h>
48 #include <obd_support.h>
49 #include <lustre_net.h>
50 #include <obd.h>
51 #include <obd_class.h>
52 #include <lustre_disk.h>
53 #include <lustre_fid.h>
54 #include <lustre_param.h>
55 #include <md_object.h>
56
57 #include "osd_internal.h"
58
59 #include <sys/dnode.h>
60 #include <sys/dbuf.h>
61 #include <sys/spa.h>
62 #include <sys/stat.h>
63 #include <sys/zap.h>
64 #include <sys/spa_impl.h>
65 #include <sys/zfs_znode.h>
66 #include <sys/dmu_tx.h>
67 #include <sys/dmu_objset.h>
68 #include <sys/dsl_prop.h>
69 #include <sys/sa_impl.h>
70 #include <sys/txg.h>
71
72 struct lu_context_key   osd_key;
73
74 /* Slab for OSD object allocation */
75 struct kmem_cache *osd_object_kmem;
76
77 /* Slab to allocate osd_zap_it */
78 struct kmem_cache *osd_zapit_cachep;
79
80 static struct lu_kmem_descr osd_caches[] = {
81         {
82                 .ckd_cache = &osd_object_kmem,
83                 .ckd_name  = "zfs_osd_obj",
84                 .ckd_size  = sizeof(struct osd_object)
85         },
86         {
87                 .ckd_cache = &osd_zapit_cachep,
88                 .ckd_name  = "osd_zapit_cache",
89                 .ckd_size  = sizeof(struct osd_zap_it)
90         },
91         {
92                 .ckd_cache = NULL
93         }
94 };
95
96 static void arc_prune_func(int64_t bytes, void *private)
97 {
98         struct osd_device *od = private;
99         struct lu_site    *site = &od->od_site;
100         struct lu_env      env;
101         int rc;
102
103         rc = lu_env_init(&env, LCT_SHRINKER);
104         if (rc) {
105                 CERROR("%s: can't initialize shrinker env: rc = %d\n",
106                        od->od_svname, rc);
107                 return;
108         }
109
110         lu_site_purge(&env, site, (bytes >> 10));
111
112         lu_env_fini(&env);
113 }
114
115 /*
116  * Concurrency: doesn't access mutable data
117  */
118 static int osd_root_get(const struct lu_env *env,
119                         struct dt_device *dev, struct lu_fid *f)
120 {
121         lu_local_obj_fid(f, OSD_FS_ROOT_OID);
122         return 0;
123 }
124
125 /*
126  * OSD object methods.
127  */
128
129 /*
130  * Concurrency: shouldn't matter.
131  */
132 static void osd_trans_commit_cb(void *cb_data, int error)
133 {
134         struct osd_thandle      *oh = cb_data;
135         struct thandle          *th = &oh->ot_super;
136         struct osd_device       *osd = osd_dt_dev(th->th_dev);
137         struct lu_device        *lud = &th->th_dev->dd_lu_dev;
138         struct dt_txn_commit_cb *dcb, *tmp;
139
140         ENTRY;
141
142         if (error) {
143                 if (error == ECANCELED)
144                         CWARN("%s: transaction @0x%p was aborted\n",
145                               osd_dt_dev(th->th_dev)->od_svname, th);
146                 else
147                         CERROR("%s: transaction @0x%p commit error: rc = %d\n",
148                                 osd_dt_dev(th->th_dev)->od_svname, th, error);
149         }
150
151         dt_txn_hook_commit(th);
152
153         /* call per-transaction callbacks if any */
154         list_for_each_entry_safe(dcb, tmp, &oh->ot_dcb_list, dcb_linkage)
155                 dcb->dcb_func(NULL, th, dcb, error);
156
157         /* Unlike ldiskfs, zfs updates space accounting at commit time.
158          * As a consequence, op_end is called only now to inform the quota slave
159          * component that reserved quota space is now accounted in usage and
160          * should be released. Quota space won't be adjusted at this point since
161          * we can't provide a suitable environment. It will be performed
162          * asynchronously by a lquota thread. */
163         qsd_op_end(NULL, osd->od_quota_slave, &oh->ot_quota_trans);
164
165         lu_device_put(lud);
166         th->th_dev = NULL;
167         lu_context_exit(&th->th_ctx);
168         lu_context_fini(&th->th_ctx);
169         OBD_FREE_PTR(oh);
170
171         EXIT;
172 }
173
174 static int osd_trans_cb_add(struct thandle *th, struct dt_txn_commit_cb *dcb)
175 {
176         struct osd_thandle *oh;
177
178         oh = container_of0(th, struct osd_thandle, ot_super);
179         list_add(&dcb->dcb_linkage, &oh->ot_dcb_list);
180
181         return 0;
182 }
183
184 /*
185  * Concurrency: shouldn't matter.
186  */
187 static int osd_trans_start(const struct lu_env *env, struct dt_device *d,
188                            struct thandle *th)
189 {
190         struct osd_thandle      *oh;
191         int                     rc;
192         ENTRY;
193
194         oh = container_of0(th, struct osd_thandle, ot_super);
195         LASSERT(oh);
196         LASSERT(oh->ot_tx);
197
198         rc = dt_txn_hook_start(env, d, th);
199         if (rc != 0)
200                 RETURN(rc);
201
202         if (oh->ot_write_commit && OBD_FAIL_CHECK(OBD_FAIL_OST_MAPBLK_ENOSPC))
203                 /* Unlike ldiskfs, ZFS checks for available space and returns
204                  * -ENOSPC when assigning txg */
205                 RETURN(-ENOSPC);
206
207         rc = -dmu_tx_assign(oh->ot_tx, TXG_WAIT);
208         if (unlikely(rc != 0)) {
209                 struct osd_device *osd = osd_dt_dev(d);
210                 /* dmu will call commit callback with error code during abort */
211                 if (!lu_device_is_md(&d->dd_lu_dev) && rc == -ENOSPC)
212                         CERROR("%s: failed to start transaction due to ENOSPC. "
213                                "Metadata overhead is underestimated or "
214                                "grant_ratio is too low.\n", osd->od_svname);
215                 else
216                         CERROR("%s: can't assign tx: rc = %d\n",
217                                osd->od_svname, rc);
218         } else {
219                 /* add commit callback */
220                 dmu_tx_callback_register(oh->ot_tx, osd_trans_commit_cb, oh);
221                 oh->ot_assigned = 1;
222                 lu_context_init(&th->th_ctx, th->th_tags);
223                 lu_context_enter(&th->th_ctx);
224                 lu_device_get(&d->dd_lu_dev);
225         }
226
227         RETURN(rc);
228 }
229
230 /*
231  * Concurrency: shouldn't matter.
232  */
233 static int osd_trans_stop(const struct lu_env *env, struct dt_device *dt,
234                           struct thandle *th)
235 {
236         struct osd_device       *osd = osd_dt_dev(th->th_dev);
237         struct osd_thandle      *oh;
238         uint64_t                 txg;
239         int                      rc;
240         ENTRY;
241
242         oh = container_of0(th, struct osd_thandle, ot_super);
243
244         if (oh->ot_assigned == 0) {
245                 LASSERT(oh->ot_tx);
246                 dmu_tx_abort(oh->ot_tx);
247                 osd_object_sa_dirty_rele(oh);
248                 /* there won't be any commit, release reserved quota space now,
249                  * if any */
250                 qsd_op_end(env, osd->od_quota_slave, &oh->ot_quota_trans);
251                 OBD_FREE_PTR(oh);
252                 RETURN(0);
253         }
254
255         /* When doing our own inode accounting, the ZAPs storing per-uid/gid
256          * usage are updated at operation execution time, so we should call
257          * qsd_op_end() straight away. Otherwise (for blk accounting maintained
258          * by ZFS and when #inode is estimated from #blks) accounting is updated
259          * at commit time and the call to qsd_op_end() must be delayed */
260         if (oh->ot_quota_trans.lqt_id_cnt > 0 &&
261                         !oh->ot_quota_trans.lqt_ids[0].lqi_is_blk &&
262                         !osd->od_quota_iused_est)
263                 qsd_op_end(env, osd->od_quota_slave, &oh->ot_quota_trans);
264
265         rc = dt_txn_hook_stop(env, th);
266         if (rc != 0)
267                 CDEBUG(D_OTHER, "%s: transaction hook failed: rc = %d\n",
268                        osd->od_svname, rc);
269
270         LASSERT(oh->ot_tx);
271         txg = oh->ot_tx->tx_txg;
272
273         osd_object_sa_dirty_rele(oh);
274         dmu_tx_commit(oh->ot_tx);
275
276         if (th->th_sync)
277                 txg_wait_synced(dmu_objset_pool(osd->od_os), txg);
278
279         RETURN(rc);
280 }
281
282 static struct thandle *osd_trans_create(const struct lu_env *env,
283                                         struct dt_device *dt)
284 {
285         struct osd_device       *osd = osd_dt_dev(dt);
286         struct osd_thandle      *oh;
287         struct thandle          *th;
288         dmu_tx_t                *tx;
289         ENTRY;
290
291         tx = dmu_tx_create(osd->od_os);
292         if (tx == NULL)
293                 RETURN(ERR_PTR(-ENOMEM));
294
295         /* alloc callback data */
296         OBD_ALLOC_PTR(oh);
297         if (oh == NULL) {
298                 dmu_tx_abort(tx);
299                 RETURN(ERR_PTR(-ENOMEM));
300         }
301
302         oh->ot_tx = tx;
303         INIT_LIST_HEAD(&oh->ot_dcb_list);
304         INIT_LIST_HEAD(&oh->ot_sa_list);
305         sema_init(&oh->ot_sa_lock, 1);
306         memset(&oh->ot_quota_trans, 0, sizeof(oh->ot_quota_trans));
307         th = &oh->ot_super;
308         th->th_dev = dt;
309         th->th_result = 0;
310         th->th_tags = LCT_TX_HANDLE;
311         RETURN(th);
312 }
313
314 /* Estimate the number of objects from a number of blocks */
315 uint64_t osd_objs_count_estimate(uint64_t refdbytes, uint64_t usedobjs,
316                                  uint64_t nrblocks)
317 {
318         uint64_t est_objs, est_refdblocks, est_usedobjs;
319
320         /* Compute an nrblocks estimate based on the actual number of
321          * dnodes that could fit in the space.  Since we don't know the
322          * overhead associated with each dnode (xattrs, SAs, VDEV overhead,
323          * etc) just using DNODE_SHIFT isn't going to give a good estimate.
324          * Instead, compute an estimate based on the average space usage per
325          * dnode, with an upper and lower cap.
326          *
327          * In case there aren't many dnodes or blocks used yet, add a small
328          * correction factor using OSD_DNODE_EST_SHIFT.  This correction
329          * factor gradually disappears as the number of real dnodes grows.
330          * This also avoids the need to check for divide-by-zero later.
331          */
332         CLASSERT(OSD_DNODE_MIN_BLKSHIFT > 0);
333         CLASSERT(OSD_DNODE_EST_BLKSHIFT > 0);
334
335         est_refdblocks = (refdbytes >> SPA_MAXBLOCKSHIFT) +
336                          (OSD_DNODE_EST_COUNT >> OSD_DNODE_EST_BLKSHIFT);
337         est_usedobjs   = usedobjs + OSD_DNODE_EST_COUNT;
338
339         /* Average space/dnode more than maximum dnode size, use max dnode
340          * size to estimate free dnodes from adjusted free blocks count.
341          * OSTs typically use more than one block dnode so this case applies. */
342         if (est_usedobjs <= est_refdblocks * 2) {
343                 est_objs = nrblocks;
344
345         /* Average space/dnode smaller than min dnode size (probably due to
346          * metadnode compression), use min dnode size to estimate the number of
347          * objects.
348          * An MDT typically uses below 512 bytes/dnode so this case applies. */
349         } else if (est_usedobjs >= (est_refdblocks << OSD_DNODE_MIN_BLKSHIFT)) {
350                 est_objs = nrblocks << OSD_DNODE_MIN_BLKSHIFT;
351
352                 /* Between the extremes, we try to use the average size of
353                  * existing dnodes to compute the number of dnodes that fit
354                  * into nrblocks:
355                  *
356                  * est_objs = nrblocks * (est_usedobjs / est_refblocks);
357                  *
358                  * but this may overflow 64 bits or become 0 if not handled well
359                  *
360                  * We know nrblocks is below (64 - 17 = 47) bits from
361                  * SPA_MAXBLKSHIFT, and est_usedobjs is under 48 bits due to
362                  * DN_MAX_OBJECT_SHIFT, which means that multiplying them may
363                  * get as large as 2 ^ 95.
364                  *
365                  * We also know (est_usedobjs / est_refdblocks) is between 2 and
366                  * 256, due to above checks, we can safely compute this first.
367                  * We care more about accuracy on the MDT (many dnodes/block)
368                  * which is good because this is where truncation errors are
369                  * smallest.  This adds 8 bits to nrblocks so we can use 7 bits
370                  * to compute a fixed-point fraction and nrblocks can still fit
371                  * in 64 bits. */
372         } else {
373                 unsigned dnodes_per_block = (est_usedobjs << 7)/est_refdblocks;
374
375                 est_objs = (nrblocks * dnodes_per_block) >> 7;
376         }
377         return est_objs;
378 }
379
380 static int osd_objset_statfs(struct objset *os, struct obd_statfs *osfs)
381 {
382         uint64_t refdbytes, availbytes, usedobjs, availobjs;
383         uint64_t est_availobjs;
384         uint64_t reserved;
385
386         dmu_objset_space(os, &refdbytes, &availbytes, &usedobjs,
387                          &availobjs);
388
389         /*
390          * ZFS allows multiple block sizes.  For statfs, Linux makes no
391          * proper distinction between bsize and frsize.  For calculations
392          * of free and used blocks incorrectly uses bsize instead of frsize,
393          * but bsize is also used as the optimal blocksize.  We return the
394          * largest possible block size as IO size for the optimum performance
395          * and scale the free and used blocks count appropriately.
396          */
397         osfs->os_bsize = 1ULL << SPA_MAXBLOCKSHIFT;
398
399         osfs->os_blocks = (refdbytes + availbytes) >> SPA_MAXBLOCKSHIFT;
400         osfs->os_bfree = availbytes >> SPA_MAXBLOCKSHIFT;
401         osfs->os_bavail = osfs->os_bfree; /* no extra root reservation */
402
403         /* Take replication (i.e. number of copies) into account */
404         osfs->os_bavail /= os->os_copies;
405
406         /*
407          * Reserve some space so we don't run into ENOSPC due to grants not
408          * accounting for metadata overhead in ZFS, and to avoid fragmentation.
409          * Rather than report this via os_bavail (which makes users unhappy if
410          * they can't fill the filesystem 100%), reduce os_blocks as well.
411          *
412          * Reserve 0.78% of total space, at least 4MB for small filesystems,
413          * for internal files to be created/unlinked when space is tight.
414          */
415         CLASSERT(OSD_STATFS_RESERVED_BLKS > 0);
416         if (likely(osfs->os_blocks >=
417                         OSD_STATFS_RESERVED_BLKS << OSD_STATFS_RESERVED_SHIFT))
418                 reserved = osfs->os_blocks >> OSD_STATFS_RESERVED_SHIFT;
419         else
420                 reserved = OSD_STATFS_RESERVED_BLKS;
421
422         osfs->os_blocks -= reserved;
423         osfs->os_bfree  -= MIN(reserved, osfs->os_bfree);
424         osfs->os_bavail -= MIN(reserved, osfs->os_bavail);
425
426         /*
427          * The availobjs value returned from dmu_objset_space() is largely
428          * useless, since it reports the number of objects that might
429          * theoretically still fit into the dataset, independent of minor
430          * issues like how much space is actually available in the pool.
431          * Compute a better estimate in udmu_objs_count_estimate().
432          */
433         est_availobjs = osd_objs_count_estimate(refdbytes, usedobjs,
434                                                 osfs->os_bfree);
435
436         osfs->os_ffree = min(availobjs, est_availobjs);
437         osfs->os_files = osfs->os_ffree + usedobjs;
438
439         /* ZFS XXX: fill in backing dataset FSID/UUID
440            memcpy(osfs->os_fsid, .... );*/
441
442         /* We're a zfs filesystem. */
443         osfs->os_type = UBERBLOCK_MAGIC;
444
445         /* ZFS XXX: fill in appropriate OS_STATE_{DEGRADED,READONLY} flags
446            osfs->os_state = vf_to_stf(vfsp->vfs_flag);
447            if (sb->s_flags & MS_RDONLY)
448            osfs->os_state = OS_STATE_READONLY;
449          */
450
451         osfs->os_namelen = MAXNAMELEN;
452         osfs->os_maxbytes = OBD_OBJECT_EOF;
453
454         return 0;
455 }
456
457 /*
458  * Concurrency: shouldn't matter.
459  */
460 int osd_statfs(const struct lu_env *env, struct dt_device *d,
461                struct obd_statfs *osfs)
462 {
463         struct osd_device *osd = osd_dt_dev(d);
464         int                rc;
465         ENTRY;
466
467         rc = osd_objset_statfs(osd->od_os, osfs);
468         if (unlikely(rc != 0))
469                 RETURN(rc);
470
471         osfs->os_bavail -= min_t(u64,
472                                  OSD_GRANT_FOR_LOCAL_OIDS / osfs->os_bsize,
473                                  osfs->os_bavail);
474         RETURN(0);
475 }
476
477 static int osd_blk_insert_cost(void)
478 {
479         int max_blockshift, nr_blkptrshift;
480
481         /* max_blockshift is the log2 of the number of blocks needed to reach
482          * the maximum filesize (that's to say 2^64) */
483         max_blockshift = DN_MAX_OFFSET_SHIFT - SPA_MAXBLOCKSHIFT;
484
485         /* nr_blkptrshift is the log2 of the number of block pointers that can
486          * be stored in an indirect block */
487         CLASSERT(DN_MAX_INDBLKSHIFT > SPA_BLKPTRSHIFT);
488         nr_blkptrshift = DN_MAX_INDBLKSHIFT - SPA_BLKPTRSHIFT;
489
490         /* max_blockshift / nr_blkptrshift is thus the maximum depth of the
491          * tree. We add +1 for rounding purpose.
492          * The tree depth times the indirect block size gives us the maximum
493          * cost of inserting a block in the tree */
494         return (max_blockshift / nr_blkptrshift + 1) * (1<<DN_MAX_INDBLKSHIFT);
495 }
496
497 /*
498  * Concurrency: doesn't access mutable data.
499  */
500 static void osd_conf_get(const struct lu_env *env,
501                          const struct dt_device *dev,
502                          struct dt_device_param *param)
503 {
504         struct osd_device *osd = osd_dt_dev(dev);
505
506         /*
507          * XXX should be taken from not-yet-existing fs abstraction layer.
508          */
509         param->ddp_max_name_len = MAXNAMELEN;
510         param->ddp_max_nlink    = 1 << 31; /* it's 8byte on a disk */
511         param->ddp_block_shift  = 12; /* XXX */
512         param->ddp_mount_type   = LDD_MT_ZFS;
513
514         param->ddp_mntopts      = MNTOPT_USERXATTR;
515         if (osd->od_posix_acl)
516                 param->ddp_mntopts |= MNTOPT_ACL;
517         param->ddp_max_ea_size  = DXATTR_MAX_ENTRY_SIZE;
518
519         /* for maxbytes, report same value as ZPL */
520         param->ddp_maxbytes     = MAX_LFS_FILESIZE;
521
522         /* Default reserved fraction of the available space that should be kept
523          * for error margin. Unfortunately, there are many factors that can
524          * impact the overhead with zfs, so let's be very cautious for now and
525          * reserve 20% of the available space which is not given out as grant.
526          * This tunable can be changed on a live system via procfs if needed. */
527         param->ddp_grant_reserved = 20;
528
529         /* inodes are dynamically allocated, so we report the per-inode space
530          * consumption to upper layers. This static value is not really accurate
531          * and we should use the same logic as in udmu_objset_statfs() to
532          * estimate the real size consumed by an object */
533         param->ddp_inodespace = OSD_DNODE_EST_COUNT;
534         /* per-fragment overhead to be used by the client code */
535         param->ddp_grant_frag = osd_blk_insert_cost();
536 }
537
538 /*
539  * Concurrency: shouldn't matter.
540  */
541 static int osd_sync(const struct lu_env *env, struct dt_device *d)
542 {
543         struct osd_device  *osd = osd_dt_dev(d);
544         CDEBUG(D_CACHE, "syncing OSD %s\n", LUSTRE_OSD_ZFS_NAME);
545         txg_wait_synced(dmu_objset_pool(osd->od_os), 0ULL);
546         CDEBUG(D_CACHE, "synced OSD %s\n", LUSTRE_OSD_ZFS_NAME);
547         return 0;
548 }
549
550 static int osd_commit_async(const struct lu_env *env, struct dt_device *dev)
551 {
552         struct osd_device *osd = osd_dt_dev(dev);
553         tx_state_t        *tx = &dmu_objset_pool(osd->od_os)->dp_tx;
554         uint64_t           txg;
555
556         mutex_enter(&tx->tx_sync_lock);
557         txg = tx->tx_open_txg + 1;
558         if (tx->tx_quiesce_txg_waiting < txg) {
559                 tx->tx_quiesce_txg_waiting = txg;
560                 cv_broadcast(&tx->tx_quiesce_more_cv);
561         }
562         mutex_exit(&tx->tx_sync_lock);
563
564         return 0;
565 }
566
567 /*
568  * Concurrency: shouldn't matter.
569  */
570 static int osd_ro(const struct lu_env *env, struct dt_device *d)
571 {
572         struct osd_device  *osd = osd_dt_dev(d);
573         ENTRY;
574
575         CERROR("%s: *** setting device %s read-only ***\n",
576                osd->od_svname, LUSTRE_OSD_ZFS_NAME);
577         osd->od_rdonly = 1;
578         spa_freeze(dmu_objset_spa(osd->od_os));
579
580         RETURN(0);
581 }
582
583 static struct dt_device_operations osd_dt_ops = {
584         .dt_root_get            = osd_root_get,
585         .dt_statfs              = osd_statfs,
586         .dt_trans_create        = osd_trans_create,
587         .dt_trans_start         = osd_trans_start,
588         .dt_trans_stop          = osd_trans_stop,
589         .dt_trans_cb_add        = osd_trans_cb_add,
590         .dt_conf_get            = osd_conf_get,
591         .dt_sync                = osd_sync,
592         .dt_commit_async        = osd_commit_async,
593         .dt_ro                  = osd_ro,
594 };
595
596 /*
597  * DMU OSD device type methods
598  */
599 static int osd_type_init(struct lu_device_type *t)
600 {
601         LU_CONTEXT_KEY_INIT(&osd_key);
602         return lu_context_key_register(&osd_key);
603 }
604
605 static void osd_type_fini(struct lu_device_type *t)
606 {
607         lu_context_key_degister(&osd_key);
608 }
609
610 static void *osd_key_init(const struct lu_context *ctx,
611                           struct lu_context_key *key)
612 {
613         struct osd_thread_info *info;
614
615         OBD_ALLOC_PTR(info);
616         if (info != NULL)
617                 info->oti_env = container_of(ctx, struct lu_env, le_ctx);
618         else
619                 info = ERR_PTR(-ENOMEM);
620         return info;
621 }
622
623 static void osd_key_fini(const struct lu_context *ctx,
624                          struct lu_context_key *key, void *data)
625 {
626         struct osd_thread_info *info = data;
627
628         OBD_FREE_PTR(info);
629 }
630
631 static void osd_key_exit(const struct lu_context *ctx,
632                          struct lu_context_key *key, void *data)
633 {
634         struct osd_thread_info *info = data;
635
636         memset(info, 0, sizeof(*info));
637 }
638
639 struct lu_context_key osd_key = {
640         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
641         .lct_init = osd_key_init,
642         .lct_fini = osd_key_fini,
643         .lct_exit = osd_key_exit
644 };
645
646 static void osd_fid_fini(const struct lu_env *env, struct osd_device *osd)
647 {
648         if (osd->od_cl_seq == NULL)
649                 return;
650
651         seq_client_fini(osd->od_cl_seq);
652         OBD_FREE_PTR(osd->od_cl_seq);
653         osd->od_cl_seq = NULL;
654 }
655
656 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
657 {
658         ENTRY;
659
660         /* shutdown quota slave instance associated with the device */
661         if (o->od_quota_slave != NULL) {
662                 qsd_fini(env, o->od_quota_slave);
663                 o->od_quota_slave = NULL;
664         }
665
666         osd_fid_fini(env, o);
667
668         RETURN(0);
669 }
670
671 static void osd_xattr_changed_cb(void *arg, uint64_t newval)
672 {
673         struct osd_device *osd = arg;
674
675         osd->od_xattr_in_sa = (newval == ZFS_XATTR_SA);
676 }
677
678 static int osd_objset_open(struct osd_device *o)
679 {
680         uint64_t        version = ZPL_VERSION;
681         uint64_t        sa_obj;
682         int             rc;
683         ENTRY;
684
685         rc = -dmu_objset_own(o->od_mntdev, DMU_OST_ZFS, B_FALSE, o, &o->od_os);
686         if (rc) {
687                 o->od_os = NULL;
688                 goto out;
689         }
690
691         /* Check ZFS version */
692         rc = -zap_lookup(o->od_os, MASTER_NODE_OBJ,
693                          ZPL_VERSION_STR, 8, 1, &version);
694         if (rc) {
695                 CERROR("%s: Error looking up ZPL VERSION\n", o->od_mntdev);
696                 /*
697                  * We can't return ENOENT because that would mean the objset
698                  * didn't exist.
699                  */
700                 GOTO(out, rc = -EIO);
701         }
702
703         rc = -zap_lookup(o->od_os, MASTER_NODE_OBJ,
704                          ZFS_SA_ATTRS, 8, 1, &sa_obj);
705         if (rc)
706                 GOTO(out, rc);
707
708         rc = -sa_setup(o->od_os, sa_obj, zfs_attr_table,
709                        ZPL_END, &o->z_attr_table);
710         if (rc)
711                 GOTO(out, rc);
712
713         rc = -zap_lookup(o->od_os, MASTER_NODE_OBJ, ZFS_ROOT_OBJ,
714                          8, 1, &o->od_rootid);
715         if (rc) {
716                 CERROR("%s: lookup for root failed: rc = %d\n",
717                         o->od_svname, rc);
718                 GOTO(out, rc);
719         }
720
721         /* Check that user/group usage tracking is supported */
722         if (!dmu_objset_userused_enabled(o->od_os) ||
723             DMU_USERUSED_DNODE(o->od_os)->dn_type != DMU_OT_USERGROUP_USED ||
724             DMU_GROUPUSED_DNODE(o->od_os)->dn_type != DMU_OT_USERGROUP_USED) {
725                 CERROR("%s: Space accounting not supported by this target, "
726                         "aborting\n", o->od_svname);
727                 GOTO(out, -ENOTSUPP);
728         }
729
730 out:
731         if (rc != 0 && o->od_os != NULL)
732                 dmu_objset_disown(o->od_os, o);
733
734         RETURN(rc);
735 }
736
737 static int osd_mount(const struct lu_env *env,
738                      struct osd_device *o, struct lustre_cfg *cfg)
739 {
740         struct dsl_dataset      *ds;
741         char                    *mntdev = lustre_cfg_string(cfg, 1);
742         char                    *svname = lustre_cfg_string(cfg, 4);
743         dmu_buf_t               *rootdb;
744         dsl_pool_t              *dp;
745         const char              *opts;
746         int                      rc;
747         ENTRY;
748
749         if (o->od_os != NULL)
750                 RETURN(0);
751
752         if (mntdev == NULL || svname == NULL)
753                 RETURN(-EINVAL);
754
755         rc = strlcpy(o->od_mntdev, mntdev, sizeof(o->od_mntdev));
756         if (rc >= sizeof(o->od_mntdev))
757                 RETURN(-E2BIG);
758
759         rc = strlcpy(o->od_svname, svname, sizeof(o->od_svname));
760         if (rc >= sizeof(o->od_svname))
761                 RETURN(-E2BIG);
762
763         if (server_name_is_ost(o->od_svname))
764                 o->od_is_ost = 1;
765
766         rc = osd_objset_open(o);
767         if (rc) {
768                 CERROR("%s: can't open objset %s: rc = %d\n", o->od_svname,
769                         o->od_mntdev, rc);
770                 RETURN(rc);
771         }
772
773         ds = dmu_objset_ds(o->od_os);
774         dp = dmu_objset_pool(o->od_os);
775         LASSERT(ds);
776         LASSERT(dp);
777         dsl_pool_config_enter(dp, FTAG);
778         rc = dsl_prop_register(ds, "xattr", osd_xattr_changed_cb, o);
779         dsl_pool_config_exit(dp, FTAG);
780         if (rc)
781                 CWARN("%s: can't register xattr callback, ignore: rc=%d\n",
782                       o->od_svname, rc);
783
784         rc = __osd_obj2dbuf(env, o->od_os, o->od_rootid, &rootdb);
785         if (rc) {
786                 CERROR("%s: obj2dbuf() failed: rc = %d\n", o->od_svname, rc);
787                 dmu_objset_disown(o->od_os, o);
788                 o->od_os = NULL;
789                 RETURN(rc);
790         }
791
792         o->od_root = rootdb->db_object;
793         sa_buf_rele(rootdb, osd_obj_tag);
794
795         /* 1. initialize oi before any file create or file open */
796         rc = osd_oi_init(env, o);
797         if (rc)
798                 GOTO(err, rc);
799
800         rc = lu_site_init(&o->od_site, osd2lu_dev(o));
801         if (rc)
802                 GOTO(err, rc);
803         o->od_site.ls_bottom_dev = osd2lu_dev(o);
804
805         rc = lu_site_init_finish(&o->od_site);
806         if (rc)
807                 GOTO(err, rc);
808
809         rc = osd_convert_root_to_new_seq(env, o);
810         if (rc)
811                 GOTO(err, rc);
812
813         /* Use our own ZAP for inode accounting by default, this can be changed
814          * via procfs to estimate the inode usage from the block usage */
815         o->od_quota_iused_est = 0;
816
817         rc = osd_procfs_init(o, o->od_svname);
818         if (rc)
819                 GOTO(err, rc);
820
821         o->arc_prune_cb = arc_add_prune_callback(arc_prune_func, o);
822
823         /* initialize quota slave instance */
824         o->od_quota_slave = qsd_init(env, o->od_svname, &o->od_dt_dev,
825                                      o->od_proc_entry);
826         if (IS_ERR(o->od_quota_slave)) {
827                 rc = PTR_ERR(o->od_quota_slave);
828                 o->od_quota_slave = NULL;
829                 GOTO(err, rc);
830         }
831
832         /* parse mount option "noacl", and enable ACL by default */
833         opts = lustre_cfg_string(cfg, 3);
834         if (opts == NULL || strstr(opts, "noacl") == NULL)
835                 o->od_posix_acl = 1;
836
837 err:
838         RETURN(rc);
839 }
840
841 static void osd_umount(const struct lu_env *env, struct osd_device *o)
842 {
843         ENTRY;
844
845         if (atomic_read(&o->od_zerocopy_alloc))
846                 CERROR("%s: lost %d allocated page(s)\n", o->od_svname,
847                        atomic_read(&o->od_zerocopy_alloc));
848         if (atomic_read(&o->od_zerocopy_loan))
849                 CERROR("%s: lost %d loaned abuf(s)\n", o->od_svname,
850                        atomic_read(&o->od_zerocopy_loan));
851         if (atomic_read(&o->od_zerocopy_pin))
852                 CERROR("%s: lost %d pinned dbuf(s)\n", o->od_svname,
853                        atomic_read(&o->od_zerocopy_pin));
854
855         if (o->od_os != NULL) {
856                 /* force a txg sync to get all commit callbacks */
857                 txg_wait_synced(dmu_objset_pool(o->od_os), 0ULL);
858
859                 /* close the object set */
860                 dmu_objset_disown(o->od_os, o);
861
862                 o->od_os = NULL;
863         }
864
865         EXIT;
866 }
867
868 static int osd_device_init0(const struct lu_env *env,
869                             struct osd_device *o,
870                             struct lustre_cfg *cfg)
871 {
872         struct lu_device        *l = osd2lu_dev(o);
873         int                      rc;
874
875         /* if the module was re-loaded, env can loose its keys */
876         rc = lu_env_refill((struct lu_env *) env);
877         if (rc)
878                 GOTO(out, rc);
879
880         l->ld_ops = &osd_lu_ops;
881         o->od_dt_dev.dd_ops = &osd_dt_ops;
882
883 out:
884         RETURN(rc);
885 }
886
887 static struct lu_device *osd_device_fini(const struct lu_env *env,
888                                          struct lu_device *dev);
889
890 static struct lu_device *osd_device_alloc(const struct lu_env *env,
891                                           struct lu_device_type *type,
892                                           struct lustre_cfg *cfg)
893 {
894         struct osd_device *dev;
895         int                rc;
896
897         OBD_ALLOC_PTR(dev);
898         if (dev == NULL)
899                 return ERR_PTR(-ENOMEM);
900
901         rc = dt_device_init(&dev->od_dt_dev, type);
902         if (rc == 0) {
903                 rc = osd_device_init0(env, dev, cfg);
904                 if (rc == 0) {
905                         rc = osd_mount(env, dev, cfg);
906                         if (rc)
907                                 osd_device_fini(env, osd2lu_dev(dev));
908                 }
909                 if (rc)
910                         dt_device_fini(&dev->od_dt_dev);
911         }
912
913         if (unlikely(rc != 0))
914                 OBD_FREE_PTR(dev);
915
916         return rc == 0 ? osd2lu_dev(dev) : ERR_PTR(rc);
917 }
918
919 static struct lu_device *osd_device_free(const struct lu_env *env,
920                                          struct lu_device *d)
921 {
922         struct osd_device *o = osd_dev(d);
923         ENTRY;
924
925         /* XXX: make osd top device in order to release reference */
926         d->ld_site->ls_top_dev = d;
927         lu_site_purge(env, d->ld_site, -1);
928         if (!cfs_hash_is_empty(d->ld_site->ls_obj_hash)) {
929                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, D_ERROR, NULL);
930                 lu_site_print(env, d->ld_site, &msgdata, lu_cdebug_printer);
931         }
932         lu_site_fini(&o->od_site);
933         dt_device_fini(&o->od_dt_dev);
934         OBD_FREE_PTR(o);
935
936         RETURN (NULL);
937 }
938
939 static struct lu_device *osd_device_fini(const struct lu_env *env,
940                                          struct lu_device *d)
941 {
942         struct osd_device *o = osd_dev(d);
943         struct dsl_dataset *ds;
944         int                rc;
945         ENTRY;
946
947
948         osd_shutdown(env, o);
949         osd_oi_fini(env, o);
950
951         if (o->od_os) {
952                 ds = dmu_objset_ds(o->od_os);
953                 rc = dsl_prop_unregister(ds, "xattr", osd_xattr_changed_cb, o);
954                 if (rc)
955                         CERROR("%s: dsl_prop_unregister xattr error %d\n",
956                                 o->od_svname, rc);
957                 if (o->arc_prune_cb != NULL) {
958                         arc_remove_prune_callback(o->arc_prune_cb);
959                         o->arc_prune_cb = NULL;
960                 }
961                 osd_sync(env, lu2dt_dev(d));
962                 txg_wait_callbacks(spa_get_dsl(dmu_objset_spa(o->od_os)));
963         }
964
965         rc = osd_procfs_fini(o);
966         if (rc) {
967                 CERROR("proc fini error %d\n", rc);
968                 RETURN(ERR_PTR(rc));
969         }
970
971         if (o->od_os)
972                 osd_umount(env, o);
973
974         RETURN(NULL);
975 }
976
977 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
978                            const char *name, struct lu_device *next)
979 {
980         return 0;
981 }
982
983 /*
984  * To be removed, setup is performed by osd_device_{init,alloc} and
985  * cleanup is performed by osd_device_{fini,free).
986  */
987 static int osd_process_config(const struct lu_env *env,
988                               struct lu_device *d, struct lustre_cfg *cfg)
989 {
990         struct osd_device       *o = osd_dev(d);
991         int                     rc;
992         ENTRY;
993
994         switch(cfg->lcfg_command) {
995         case LCFG_SETUP:
996                 rc = osd_mount(env, o, cfg);
997                 break;
998         case LCFG_CLEANUP:
999                 rc = osd_shutdown(env, o);
1000                 break;
1001         case LCFG_PARAM: {
1002                 LASSERT(&o->od_dt_dev);
1003                 rc = class_process_proc_param(PARAM_OSD, lprocfs_osd_obd_vars,
1004                                               cfg, &o->od_dt_dev);
1005                 if (rc > 0 || rc == -ENOSYS)
1006                         rc = class_process_proc_param(PARAM_OST,
1007                                                       lprocfs_osd_obd_vars,
1008                                                       cfg, &o->od_dt_dev);
1009                 break;
1010         }
1011         default:
1012                 rc = -ENOTTY;
1013         }
1014
1015         RETURN(rc);
1016 }
1017
1018 static int osd_recovery_complete(const struct lu_env *env, struct lu_device *d)
1019 {
1020         struct osd_device       *osd = osd_dev(d);
1021         int                      rc = 0;
1022         ENTRY;
1023
1024         if (osd->od_quota_slave == NULL)
1025                 RETURN(0);
1026
1027         /* start qsd instance on recovery completion, this notifies the quota
1028          * slave code that we are about to process new requests now */
1029         rc = qsd_start(env, osd->od_quota_slave);
1030         RETURN(rc);
1031 }
1032
1033 /*
1034  * we use exports to track all osd users
1035  */
1036 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
1037                            struct obd_device *obd, struct obd_uuid *cluuid,
1038                            struct obd_connect_data *data, void *localdata)
1039 {
1040         struct osd_device    *osd = osd_dev(obd->obd_lu_dev);
1041         struct lustre_handle  conn;
1042         int                   rc;
1043         ENTRY;
1044
1045         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
1046
1047         rc = class_connect(&conn, obd, cluuid);
1048         if (rc)
1049                 RETURN(rc);
1050
1051         *exp = class_conn2export(&conn);
1052
1053         spin_lock(&obd->obd_dev_lock);
1054         osd->od_connects++;
1055         spin_unlock(&obd->obd_dev_lock);
1056
1057         RETURN(0);
1058 }
1059
1060 /*
1061  * once last export (we don't count self-export) disappeared
1062  * osd can be released
1063  */
1064 static int osd_obd_disconnect(struct obd_export *exp)
1065 {
1066         struct obd_device *obd = exp->exp_obd;
1067         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
1068         int                rc, release = 0;
1069         ENTRY;
1070
1071         /* Only disconnect the underlying layers on the final disconnect. */
1072         spin_lock(&obd->obd_dev_lock);
1073         osd->od_connects--;
1074         if (osd->od_connects == 0)
1075                 release = 1;
1076         spin_unlock(&obd->obd_dev_lock);
1077
1078         rc = class_disconnect(exp); /* bz 9811 */
1079
1080         if (rc == 0 && release)
1081                 class_manual_cleanup(obd);
1082         RETURN(rc);
1083 }
1084
1085 static int osd_fid_init(const struct lu_env *env, struct osd_device *osd)
1086 {
1087         struct seq_server_site  *ss = osd_seq_site(osd);
1088         int                     rc;
1089         ENTRY;
1090
1091         if (osd->od_is_ost || osd->od_cl_seq != NULL)
1092                 RETURN(0);
1093
1094         if (unlikely(ss == NULL))
1095                 RETURN(-ENODEV);
1096
1097         OBD_ALLOC_PTR(osd->od_cl_seq);
1098         if (osd->od_cl_seq == NULL)
1099                 RETURN(-ENOMEM);
1100
1101         rc = seq_client_init(osd->od_cl_seq, NULL, LUSTRE_SEQ_METADATA,
1102                              osd->od_svname, ss->ss_server_seq);
1103
1104         if (rc != 0) {
1105                 OBD_FREE_PTR(osd->od_cl_seq);
1106                 osd->od_cl_seq = NULL;
1107         }
1108
1109         RETURN(rc);
1110 }
1111
1112 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
1113                        struct lu_device *dev)
1114 {
1115         struct osd_device       *osd = osd_dev(dev);
1116         int                      rc = 0;
1117         ENTRY;
1118
1119         if (osd->od_quota_slave != NULL) {
1120                 /* set up quota slave objects */
1121                 rc = qsd_prepare(env, osd->od_quota_slave);
1122                 if (rc != 0)
1123                         RETURN(rc);
1124         }
1125
1126         rc = osd_fid_init(env, osd);
1127
1128         RETURN(rc);
1129 }
1130
1131 struct lu_device_operations osd_lu_ops = {
1132         .ldo_object_alloc       = osd_object_alloc,
1133         .ldo_process_config     = osd_process_config,
1134         .ldo_recovery_complete  = osd_recovery_complete,
1135         .ldo_prepare            = osd_prepare,
1136 };
1137
1138 static void osd_type_start(struct lu_device_type *t)
1139 {
1140 }
1141
1142 static void osd_type_stop(struct lu_device_type *t)
1143 {
1144 }
1145
1146 int osd_fid_alloc(const struct lu_env *env, struct obd_export *exp,
1147                   struct lu_fid *fid, struct md_op_data *op_data)
1148 {
1149         struct osd_device *osd = osd_dev(exp->exp_obd->obd_lu_dev);
1150
1151         return seq_client_alloc_fid(env, osd->od_cl_seq, fid);
1152 }
1153
1154 static struct lu_device_type_operations osd_device_type_ops = {
1155         .ldto_init              = osd_type_init,
1156         .ldto_fini              = osd_type_fini,
1157
1158         .ldto_start             = osd_type_start,
1159         .ldto_stop              = osd_type_stop,
1160
1161         .ldto_device_alloc      = osd_device_alloc,
1162         .ldto_device_free       = osd_device_free,
1163
1164         .ldto_device_init       = osd_device_init,
1165         .ldto_device_fini       = osd_device_fini
1166 };
1167
1168 static struct lu_device_type osd_device_type = {
1169         .ldt_tags     = LU_DEVICE_DT,
1170         .ldt_name     = LUSTRE_OSD_ZFS_NAME,
1171         .ldt_ops      = &osd_device_type_ops,
1172         .ldt_ctx_tags = LCT_LOCAL
1173 };
1174
1175
1176 static struct obd_ops osd_obd_device_ops = {
1177         .o_owner       = THIS_MODULE,
1178         .o_connect      = osd_obd_connect,
1179         .o_disconnect   = osd_obd_disconnect,
1180         .o_fid_alloc    = osd_fid_alloc
1181 };
1182
1183 int __init osd_init(void)
1184 {
1185         int rc;
1186
1187         rc = osd_options_init();
1188         if (rc)
1189                 return rc;
1190
1191         rc = lu_kmem_init(osd_caches);
1192         if (rc)
1193                 return rc;
1194
1195         rc = class_register_type(&osd_obd_device_ops, NULL, true, NULL,
1196                                  LUSTRE_OSD_ZFS_NAME, &osd_device_type);
1197         if (rc)
1198                 lu_kmem_fini(osd_caches);
1199         return rc;
1200 }
1201
1202 void __exit osd_exit(void)
1203 {
1204         class_unregister_type(LUSTRE_OSD_ZFS_NAME);
1205         lu_kmem_fini(osd_caches);
1206 }
1207
1208 extern unsigned int osd_oi_count;
1209 CFS_MODULE_PARM(osd_oi_count, "i", int, 0444,
1210                 "Number of Object Index containers to be created, "
1211                 "it's only valid for new filesystem.");
1212
1213 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
1214 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_ZFS_NAME")");
1215 MODULE_VERSION(LUSTRE_VERSION_STRING);
1216 MODULE_LICENSE("GPL");
1217
1218 module_init(osd_init);
1219 module_exit(osd_exit);