Whamcloud - gitweb
ca2eae07c88f4ede83404ecd9819aa305525a3af
[fs/lustre-release.git] / lustre / mdd / mdd_device.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) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/mdd/mdd_device.c
32  *
33  * Lustre Metadata Server (mdd) routines
34  *
35  * Author: Wang Di <wangdi@clusterfs.com>
36  */
37
38 #define DEBUG_SUBSYSTEM S_MDS
39
40 #include <linux/module.h>
41 #include <linux/kthread.h>
42 #include <obd_class.h>
43 #include <uapi/linux/lustre/lustre_ioctl.h>
44 #include <lustre_mds.h>
45 #include <obd_support.h>
46 #include <lu_object.h>
47 #include <uapi/linux/lustre/lustre_param.h>
48 #include <lustre_fid.h>
49 #include <lustre_nodemap.h>
50 #include <lustre_barrier.h>
51
52 #include "mdd_internal.h"
53
54 static const struct md_device_operations mdd_ops;
55 static struct lu_device_type mdd_device_type;
56
57 static const char mdd_root_dir_name[] = "ROOT";
58 static const char mdd_obf_dir_name[] = "fid";
59 static const char mdd_lpf_dir_name[] = "lost+found";
60
61 /* Slab for MDD object allocation */
62 struct kmem_cache *mdd_object_kmem;
63
64 static struct lu_kmem_descr mdd_caches[] = {
65         {
66                 .ckd_cache = &mdd_object_kmem,
67                 .ckd_name  = "mdd_obj",
68                 .ckd_size  = sizeof(struct mdd_object)
69         },
70         {
71                 .ckd_cache = NULL
72         }
73 };
74
75 /**
76  * Mod params for the fs-wide (stored in ROOT) default dir layout,
77  * to be set and stored in EA, if EA is absent yet:
78  *
79  * stripe_offset, max_inherit, max_inherit_rr, see lfs setdirstripe for more
80  * details.
81  */
82 static unsigned int root_stripe_offset = LMV_OFFSET_DEFAULT;
83 module_param(root_stripe_offset, uint, 0444);
84 MODULE_PARM_DESC(root_stripe_offset, "fs-wide default LMV stripe offset");
85
86 static unsigned int root_max_inherit = LMV_INHERIT_UNLIMITED;
87 module_param(root_max_inherit, uint, 0444);
88 MODULE_PARM_DESC(root_max_inherit, "fs-wide default LMV max_inherit");
89
90 static unsigned int root_max_inherit_rr = LMV_INHERIT_RR_ROOT;
91 module_param(root_max_inherit_rr, uint, 0444);
92 MODULE_PARM_DESC(root_max_inherit_rr, "fs-wide default LMV max_inherit_rr");
93
94 static int mdd_connect_to_next(const struct lu_env *env, struct mdd_device *m,
95                                const char *nextdev)
96 {
97         struct obd_connect_data *data = NULL;
98         struct lu_device        *lud = mdd2lu_dev(m);
99         struct obd_device       *obd;
100         int                      rc;
101         ENTRY;
102
103         LASSERT(m->mdd_child_exp == NULL);
104
105         OBD_ALLOC(data, sizeof(*data));
106         if (data == NULL)
107                 GOTO(out, rc = -ENOMEM);
108
109         obd = class_name2obd(nextdev);
110         if (obd == NULL) {
111                 CERROR("can't locate next device: %s\n", nextdev);
112                 GOTO(out, rc = -ENOTCONN);
113         }
114
115         data->ocd_connect_flags = OBD_CONNECT_VERSION;
116         data->ocd_version = LUSTRE_VERSION_CODE;
117
118         rc = obd_connect(NULL, &m->mdd_child_exp, obd, &obd->obd_uuid, data, NULL);
119         if (rc) {
120                 CERROR("cannot connect to next dev %s (%d)\n", nextdev, rc);
121                 GOTO(out, rc);
122         }
123
124         lud->ld_site = m->mdd_child_exp->exp_obd->obd_lu_dev->ld_site;
125         LASSERT(lud->ld_site);
126         m->mdd_child = lu2dt_dev(m->mdd_child_exp->exp_obd->obd_lu_dev);
127         m->mdd_bottom = lu2dt_dev(lud->ld_site->ls_bottom_dev);
128         lu_dev_add_linkage(lud->ld_site, lud);
129
130 out:
131         if (data)
132                 OBD_FREE(data, sizeof(*data));
133         RETURN(rc);
134 }
135
136 static int mdd_init0(const struct lu_env *env, struct mdd_device *mdd,
137                 struct lu_device_type *t, struct lustre_cfg *lcfg)
138 {
139         int rc = -EINVAL;
140         const char *dev;
141
142         ENTRY;
143
144         /* LU-8040 Set defaults here, before values configs */
145         mdd->mdd_cl.mc_flags = 0; /* off by default */
146         /* per-server mask is set via parameters if needed */
147         mdd->mdd_cl.mc_proc_mask = CHANGELOG_MINMASK;
148         /* current mask is calculated from mask above and users masks */
149         mdd->mdd_cl.mc_current_mask = CHANGELOG_MINMASK;
150         mdd->mdd_cl.mc_deniednext = 60; /* 60 secs by default */
151
152         dev = lustre_cfg_string(lcfg, 0);
153         if (dev == NULL)
154                 RETURN(rc);
155
156         mdd->mdd_md_dev.md_lu_dev.ld_obd = class_name2obd(dev);
157         if (mdd->mdd_md_dev.md_lu_dev.ld_obd == NULL)
158                 RETURN(rc);
159         mdd->mdd_md_dev.md_lu_dev.ld_ops = &mdd_lu_ops;
160         mdd->mdd_md_dev.md_ops = &mdd_ops;
161
162         rc = mdd_connect_to_next(env, mdd, lustre_cfg_string(lcfg, 3));
163         if (rc != 0)
164                 RETURN(rc);
165
166         mdd->mdd_atime_diff = MAX_ATIME_DIFF;
167         /* sync permission changes */
168         mdd->mdd_sync_permission = 1;
169         /* enable changelog garbage collection */
170         mdd->mdd_changelog_gc = 1;
171         /* enable changelog cleanup due to lack of space */
172         mdd->mdd_changelog_free_space_gc = true;
173         /* set when emergency GC is started */
174         mdd->mdd_changelog_emrg_gc = false;
175         /* with a significant amount of idle time */
176         mdd->mdd_changelog_max_idle_time = CHLOG_MAX_IDLE_TIME;
177         /* or a significant amount of late indexes */
178         mdd->mdd_changelog_max_idle_indexes = CHLOG_MAX_IDLE_INDEXES;
179         /* with a reasonable interval between each check */
180         mdd->mdd_changelog_min_gc_interval = CHLOG_MIN_GC_INTERVAL;
181         /* with a very few number of free catalog entries */
182         mdd->mdd_changelog_min_free_cat_entries = CHLOG_MIN_FREE_CAT_ENTRIES;
183         /* special default striping for files created with O_APPEND */
184         mdd->mdd_append_stripe_count = 1;
185         mdd->mdd_append_pool[0] = '\0';
186
187         dt_conf_get(env, mdd->mdd_child, &mdd->mdd_dt_conf);
188
189         /* we are using service name but not mdd obd name
190          * for compatibility reasons.
191          * It is passed from MDT in lustre_cfg[2] buffer */
192         rc = mdd_procfs_init(mdd, lustre_cfg_string(lcfg, 2));
193         if (rc < 0)
194                 obd_disconnect(mdd->mdd_child_exp);
195
196         RETURN(rc);
197 }
198
199 static struct lu_device *mdd_device_fini(const struct lu_env *env,
200                                          struct lu_device *d)
201 {
202         struct mdd_device *mdd = lu2mdd_dev(d);
203
204         if (d->ld_site)
205                 lu_dev_del_linkage(d->ld_site, d);
206
207         mdd_procfs_fini(mdd);
208         return NULL;
209 }
210
211 static int changelog_init_cb(const struct lu_env *env, struct llog_handle *llh,
212                              struct llog_rec_hdr *hdr, void *data)
213 {
214         struct mdd_device *mdd = (struct mdd_device *)data;
215         struct llog_changelog_rec *rec = (struct llog_changelog_rec *)hdr;
216
217         LASSERT(llh->lgh_hdr->llh_flags & LLOG_F_IS_PLAIN);
218         LASSERT(rec->cr_hdr.lrh_type == CHANGELOG_REC);
219
220         CDEBUG(D_INFO,
221                "seeing record at index %d/%d/%llu t=%x %.*s in log"
222                DFID"\n", hdr->lrh_index, rec->cr_hdr.lrh_index,
223                rec->cr.cr_index, rec->cr.cr_type, rec->cr.cr_namelen,
224                changelog_rec_name(&rec->cr), PLOGID(&llh->lgh_id));
225         spin_lock(&mdd->mdd_cl.mc_lock);
226         mdd->mdd_cl.mc_index = rec->cr.cr_index;
227         spin_unlock(&mdd->mdd_cl.mc_lock);
228         return LLOG_PROC_BREAK;
229 }
230
231 char *mdd_chlg_username(struct llog_changelog_user_rec2 *rec, char *buf,
232                         size_t len)
233 {
234         if (rec->cur_hdr.lrh_type == CHANGELOG_USER_REC2 &&
235             rec->cur_name[0])
236                 snprintf(buf, len, "%s%u-%s",  CHANGELOG_USER_PREFIX,
237                          rec->cur_id, rec->cur_name);
238         else
239                 snprintf(buf, len, "%s%u", CHANGELOG_USER_PREFIX, rec->cur_id);
240         return buf;
241 }
242
243 __u32 mdd_chlg_usermask(struct llog_changelog_user_rec2 *rec)
244 {
245         return rec->cur_hdr.lrh_type == CHANGELOG_USER_REC2 ?
246                rec->cur_mask : 0;
247 }
248
249 static int changelog_user_init_cb(const struct lu_env *env,
250                                   struct llog_handle *llh,
251                                   struct llog_rec_hdr *hdr, void *data)
252 {
253         struct mdd_device *mdd = data;
254         struct llog_changelog_user_rec2 *rec;
255         char user_name[CHANGELOG_USER_NAMELEN_FULL];
256
257         LASSERT(llh->lgh_hdr->llh_flags & LLOG_F_IS_PLAIN);
258
259         rec = container_of(hdr, typeof(*rec), cur_hdr);
260         if (rec->cur_hdr.lrh_type != CHANGELOG_USER_REC &&
261             rec->cur_hdr.lrh_type != CHANGELOG_USER_REC2) {
262                 CWARN("%s: unknown user type %x at index %u in log "DFID"\n",
263                       mdd2obd_dev(mdd)->obd_name, hdr->lrh_index,
264                       rec->cur_hdr.lrh_type, PLOGID(&llh->lgh_id));
265
266                 return 0;
267         }
268
269         CDEBUG(D_INFO, "%s: user %s at index %u/%u endrec=%llu in log "DFID"\n",
270                mdd2obd_dev(mdd)->obd_name, mdd_chlg_username(rec, user_name,
271                                                              sizeof(user_name)),
272                hdr->lrh_index, rec->cur_hdr.lrh_index, rec->cur_endrec,
273                PLOGID(&llh->lgh_id));
274
275         spin_lock(&mdd->mdd_cl.mc_user_lock);
276         mdd->mdd_cl.mc_lastuser = rec->cur_id;
277         mdd->mdd_cl.mc_users++;
278         if (rec->cur_hdr.lrh_type == CHANGELOG_USER_REC2 && rec->cur_mask)
279                 mdd->mdd_cl.mc_current_mask |= rec->cur_mask;
280         else if (mdd->mdd_cl.mc_proc_mask == CHANGELOG_MINMASK)
281                 mdd->mdd_cl.mc_current_mask |= CHANGELOG_DEFMASK;
282         mdd->mdd_cl.mc_mintime = min(mdd->mdd_cl.mc_mintime, rec->cur_time);
283         mdd->mdd_cl.mc_minrec = min(mdd->mdd_cl.mc_minrec, rec->cur_endrec);
284         spin_unlock(&mdd->mdd_cl.mc_user_lock);
285         spin_lock(&mdd->mdd_cl.mc_lock);
286         if (rec->cur_endrec > mdd->mdd_cl.mc_index)
287                 mdd->mdd_cl.mc_index = rec->cur_endrec;
288         spin_unlock(&mdd->mdd_cl.mc_lock);
289
290         return LLOG_PROC_BREAK;
291 }
292
293 struct changelog_orphan_data {
294         __u64                   clod_index;
295         struct mdd_device       *clod_mdd;
296 };
297
298 /* find oldest changelog record index */
299 static int changelog_detect_orphan_cb(const struct lu_env *env,
300                                       struct llog_handle *llh,
301                                       struct llog_rec_hdr *hdr, void *data)
302 {
303         struct changelog_orphan_data *clod = data;
304         struct mdd_device *mdd = clod->clod_mdd;
305         struct llog_changelog_rec *rec;
306
307         LASSERT(llh->lgh_hdr->llh_flags & LLOG_F_IS_PLAIN);
308
309         rec = container_of(hdr, typeof(*rec), cr_hdr);
310         if (rec->cr_hdr.lrh_type != CHANGELOG_REC) {
311                 CWARN("%s: invalid record at index %d in log "DFID"\n",
312                       mdd2obd_dev(mdd)->obd_name, hdr->lrh_index,
313                       PLOGID(&llh->lgh_id));
314                 /* try to find some next valid record and thus allow to recover
315                  * from a corrupted LLOG, instead to assert and force a crash
316                  */
317                 return 0;
318         }
319
320         CDEBUG(D_INFO,
321                "%s: record at index %d/%d/%llu t=%x %.*s in log "DFID"\n",
322                mdd2obd_dev(mdd)->obd_name, hdr->lrh_index,
323                rec->cr_hdr.lrh_index, rec->cr.cr_index, rec->cr.cr_type,
324                rec->cr.cr_namelen, changelog_rec_name(&rec->cr),
325                PLOGID(&llh->lgh_id));
326
327         clod->clod_index = rec->cr.cr_index;
328
329         return LLOG_PROC_BREAK;
330 }
331
332 /* find oldest changelog user index */
333 static int changelog_user_detect_orphan_cb(const struct lu_env *env,
334                                            struct llog_handle *llh,
335                                            struct llog_rec_hdr *hdr, void *data)
336 {
337         struct changelog_orphan_data *clod = data;
338         struct mdd_device *mdd = clod->clod_mdd;
339         struct llog_changelog_user_rec2 *rec;
340         char user_name[CHANGELOG_USER_NAMELEN_FULL];
341
342         LASSERT(llh->lgh_hdr->llh_flags & LLOG_F_IS_PLAIN);
343
344         rec = container_of(hdr, typeof(*rec), cur_hdr);
345         if (rec->cur_hdr.lrh_type != CHANGELOG_USER_REC &&
346             rec->cur_hdr.lrh_type != CHANGELOG_USER_REC2) {
347                 CWARN("%s: unknown user type %u at index %u in log "DFID"\n",
348                       mdd2obd_dev(mdd)->obd_name, hdr->lrh_index,
349                       rec->cur_hdr.lrh_type, PLOGID(&llh->lgh_id));
350                 /* try to find some next valid record and thus allow to recover
351                  * from a corrupted LLOG, instead to assert and force a crash
352                  */
353                 return 0;
354         }
355
356         CDEBUG(D_INFO, "%s: user %s at index %u/%u endrec=%llu in log "DFID"\n",
357                mdd2obd_dev(mdd)->obd_name, mdd_chlg_username(rec, user_name,
358                                                              sizeof(user_name)),
359                hdr->lrh_index, rec->cur_hdr.lrh_index,
360                rec->cur_endrec, PLOGID(&llh->lgh_id));
361
362         clod->clod_index = min_t(__u64, clod->clod_index, rec->cur_endrec);
363
364         return 0;
365 }
366
367 struct changelog_cancel_cookie {
368         long long endrec;
369         struct mdd_device *mdd;
370 };
371
372 static int llog_changelog_cancel_cb(const struct lu_env *env,
373                                     struct llog_handle *llh,
374                                     struct llog_rec_hdr *hdr, void *data)
375 {
376         struct llog_changelog_rec *rec = (struct llog_changelog_rec *)hdr;
377         struct changelog_cancel_cookie *cl_cookie =
378                 (struct changelog_cancel_cookie *)data;
379
380         ENTRY;
381
382         /* This is always a (sub)log, not the catalog */
383         LASSERT(llh->lgh_hdr->llh_flags & LLOG_F_IS_PLAIN);
384
385         /* if current context is GC-thread allow it to stop upon umount
386          * remaining records cleanup will occur upon next mount
387          *
388          * also during testing, wait for GC-thread to be released
389          *
390          * XXX this requires the GC-thread to not fork a sub-thread via
391          * llog[_cat]_process_or_fork() and we may think to also implement
392          * this shutdown mechanism for manually started user unregister which
393          * can also take a long time if huge backlog of records
394          */
395         if (unlikely(cl_cookie->mdd->mdd_cl.mc_gc_task == current)) {
396                 /* wait to be released */
397                 while (CFS_FAIL_CHECK_QUIET(OBD_FAIL_FORCE_GC_THREAD))
398                         schedule();
399
400                 if (kthread_should_stop())
401                         RETURN(LLOG_PROC_BREAK);
402         }
403
404         if (rec->cr.cr_index > cl_cookie->endrec)
405                 /* records are in order, so we're done */
406                 RETURN(LLOG_PROC_BREAK);
407
408         if (unlikely(OBD_FAIL_PRECHECK(OBD_FAIL_MDS_CHANGELOG_RACE))) {
409                 if (cfs_fail_val == 0)
410                         cfs_fail_val = hdr->lrh_index;
411                 if (cfs_fail_val == hdr->lrh_index)
412                         OBD_RACE(OBD_FAIL_MDS_CHANGELOG_RACE);
413         }
414
415         /* Records folow one by one, cr_index++. We could calculate the
416          * last cr_index at this plain llog. And if it less then cookie endrec
417          * cancel the whole file.
418          */
419         if (llog_is_plain_skipable(llh->lgh_hdr, hdr, rec->cr.cr_index,
420                                    cl_cookie->endrec)) {
421                 int rc;
422
423                 if (unlikely(OBD_FAIL_PRECHECK(OBD_FAIL_MDS_CHANGELOG_DEL))) {
424                         if (cfs_fail_val == 0) {
425                                 cfs_fail_val = (unsigned long)llh & 0xFFFFFFFF;
426                                 OBD_RACE(OBD_FAIL_MDS_CHANGELOG_DEL);
427                         }
428                 }
429                 rc = llog_destroy(env, llh);
430                 if (!rc) {
431                         CDEBUG(D_HA, "Changelog destroyed plain "DFID"\n",
432                                PLOGID(&llh->lgh_id));
433                         RETURN(LLOG_DEL_PLAIN);
434                 }
435         }
436
437         /* cancel them one at a time.  I suppose we could store up the cookies
438          * and cancel them all at once; probably more efficient, but this is
439          * done as a user call, so who cares... */
440
441         RETURN(LLOG_DEL_RECORD);
442 }
443
444 static int llog_changelog_cancel(const struct lu_env *env,
445                                  struct llog_ctxt *ctxt,
446                                  struct changelog_cancel_cookie *cookie)
447 {
448         struct llog_handle      *cathandle = ctxt->loc_handle;
449         int                      rc;
450
451         ENTRY;
452
453         /* This should only be called with the catalog handle */
454         LASSERT(cathandle->lgh_hdr->llh_flags & LLOG_F_IS_CAT);
455
456         rc = llog_cat_process(env, cathandle, llog_changelog_cancel_cb,
457                               cookie, 0, 0);
458         if (rc >= 0)
459                 /* 0 or 1 means we're done */
460                 rc = 0;
461         else
462                 CERROR("%s: cancel idx %u of catalog "DFID": rc = %d\n",
463                        ctxt->loc_obd->obd_name, cathandle->lgh_last_idx,
464                        PLOGID(&cathandle->lgh_id), rc);
465
466         RETURN(rc);
467 }
468
469 static struct llog_operations changelog_orig_logops;
470
471 static int
472 mdd_changelog_write_header(const struct lu_env *env, struct mdd_device *mdd,
473                            int markerflags);
474
475 static int
476 mdd_changelog_on(const struct lu_env *env, struct mdd_device *mdd)
477 {
478         int rc = 0;
479
480         if ((mdd->mdd_cl.mc_flags & CLM_ON) != 0)
481                 return rc;
482
483         LCONSOLE_INFO("%s: changelog on\n", mdd2obd_dev(mdd)->obd_name);
484         if (mdd->mdd_cl.mc_flags & CLM_ERR) {
485                 CERROR("Changelogs cannot be enabled due to error "
486                        "condition (see %s log).\n",
487                        mdd2obd_dev(mdd)->obd_name);
488                 rc = -ESRCH;
489         } else {
490                 spin_lock(&mdd->mdd_cl.mc_lock);
491                 mdd->mdd_cl.mc_flags |= CLM_ON;
492                 spin_unlock(&mdd->mdd_cl.mc_lock);
493                 rc = mdd_changelog_write_header(env, mdd, CLM_START);
494         }
495         return rc;
496 }
497
498 static int
499 mdd_changelog_off(const struct lu_env *env, struct mdd_device *mdd)
500 {
501         int rc = 0;
502
503         if ((mdd->mdd_cl.mc_flags & CLM_ON) != CLM_ON)
504                 return rc;
505
506         LCONSOLE_INFO("%s: changelog off\n", mdd2obd_dev(mdd)->obd_name);
507         rc = mdd_changelog_write_header(env, mdd, CLM_FINI);
508         spin_lock(&mdd->mdd_cl.mc_lock);
509         mdd->mdd_cl.mc_flags &= ~CLM_ON;
510         spin_unlock(&mdd->mdd_cl.mc_lock);
511
512         return rc;
513 }
514
515 static int mdd_changelog_llog_init(const struct lu_env *env,
516                                    struct mdd_device *mdd)
517 {
518         struct obd_device *obd = mdd2obd_dev(mdd);
519         struct llog_ctxt *ctxt = NULL, *uctxt = NULL;
520         struct changelog_orphan_data clod = {
521                 .clod_mdd = mdd,
522                 .clod_index = -1,
523         }, user_orphan = {
524                 .clod_mdd = mdd,
525                 .clod_index = -1,
526         };
527         int rc;
528
529         ENTRY;
530
531         /* LU-2844 mdd setup failure should not cause umount oops */
532         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_CHANGELOG_INIT))
533                 RETURN(-EIO);
534
535         OBD_SET_CTXT_MAGIC(&obd->obd_lvfs_ctxt);
536         obd->obd_lvfs_ctxt.dt = mdd->mdd_bottom;
537         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_CHANGELOG_ORIG_CTXT,
538                         obd, &changelog_orig_logops);
539         if (rc) {
540                 CERROR("%s: changelog llog setup failed: rc = %d\n",
541                        obd->obd_name, rc);
542                 RETURN(rc);
543         }
544
545         ctxt = llog_get_context(obd, LLOG_CHANGELOG_ORIG_CTXT);
546         LASSERT(ctxt);
547
548         rc = llog_open_create(env, ctxt, &ctxt->loc_handle, NULL,
549                               CHANGELOG_CATALOG);
550         if (rc)
551                 GOTO(out_cleanup, rc);
552
553         rc = llog_init_handle(env, ctxt->loc_handle, LLOG_F_IS_CAT, NULL);
554         if (rc)
555                 GOTO(out_close, rc);
556
557         rc = llog_cat_reverse_process(env, ctxt->loc_handle,
558                                       changelog_init_cb, mdd);
559
560         if (rc < 0) {
561                 CERROR("%s: changelog init failed: rc = %d\n", obd->obd_name,
562                        rc);
563                 GOTO(out_close, rc);
564         }
565
566         CDEBUG(D_IOCTL, "changelog starting index=%llu\n",
567                mdd->mdd_cl.mc_index);
568
569         /* setup user changelog */
570         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_CHANGELOG_USER_ORIG_CTXT,
571                         obd, &changelog_orig_logops);
572         if (rc) {
573                 CERROR("%s: changelog users llog setup failed: rc = %d\n",
574                        obd->obd_name, rc);
575                 GOTO(out_close, rc);
576         }
577
578         uctxt = llog_get_context(obd, LLOG_CHANGELOG_USER_ORIG_CTXT);
579         LASSERT(ctxt);
580
581         rc = llog_open_create(env, uctxt, &uctxt->loc_handle, NULL,
582                               CHANGELOG_USERS);
583         if (rc)
584                 GOTO(out_ucleanup, rc);
585
586         rc = llog_init_handle(env, uctxt->loc_handle, LLOG_F_IS_CAT, NULL);
587         if (rc)
588                 GOTO(out_uclose, rc);
589
590         rc = llog_cat_reverse_process(env, uctxt->loc_handle,
591                                       changelog_user_init_cb, mdd);
592         if (rc < 0) {
593                 CERROR("%s: changelog user init failed: rc = %d\n",
594                        obd->obd_name, rc);
595                 GOTO(out_uclose, rc);
596         }
597
598         /* Finally apply per-server mask */
599         mdd->mdd_cl.mc_current_mask |= mdd->mdd_cl.mc_proc_mask;
600
601         /* If we have registered users, assume we want changelogs on */
602         if (mdd->mdd_cl.mc_lastuser > 0) {
603                 rc = mdd_changelog_on(env, mdd);
604                 if (rc < 0)
605                         GOTO(out_uclose, rc);
606         }
607
608         /* find and clear any orphan changelog records (1st record index <
609          * smallest of all users current index), likely to come from an
610          * interrupted manual or GC-thread purge, as its user record had
611          * been deleted first
612          * XXX we may wait for a still registered user clear operation to
613          * do the job, but it may then take a long time to reach the user's
614          * real targetted records if a huge purge backlog is still to be
615          * processed as a long time idle user record could have been deleted
616          * XXX we may need to run end of purge as a separate thread
617          */
618         rc = llog_cat_process(env, ctxt->loc_handle, changelog_detect_orphan_cb,
619                               &clod, 0, 0);
620         if (rc < 0) {
621                 CERROR("%s: changelog detect orphan failed: rc = %d\n",
622                        obd->obd_name, rc);
623                 GOTO(out_uclose, rc);
624         }
625         rc = llog_cat_process(env, uctxt->loc_handle,
626                               changelog_user_detect_orphan_cb,
627                               &user_orphan, 0, 0);
628         if (rc < 0) {
629                 CERROR("%s: changelog user detect orphan failed: rc = %d\n",
630                        obd->obd_name, rc);
631                 GOTO(out_uclose, rc);
632         }
633         if (unlikely(clod.clod_index < user_orphan.clod_index)) {
634                 struct changelog_cancel_cookie cl_cookie = {
635                         .endrec = user_orphan.clod_index,
636                         .mdd = mdd,
637                 };
638
639                 CWARN("%s : orphan changelog records found, starting from "
640                       "index %llu to index %llu, being cleared now\n",
641                       obd->obd_name, clod.clod_index, user_orphan.clod_index);
642
643                 /* XXX we may need to run end of purge as a separate thread */
644                 rc = llog_changelog_cancel(env, ctxt, &cl_cookie);
645                 if (rc < 0) {
646                         CERROR("%s: purge of changelog orphan records failed: "
647                                "rc = %d\n", obd->obd_name, rc);
648                         GOTO(out_uclose, rc);
649                 }
650         }
651
652         llog_ctxt_put(ctxt);
653         llog_ctxt_put(uctxt);
654         RETURN(0);
655 out_uclose:
656         llog_cat_close(env, uctxt->loc_handle);
657 out_ucleanup:
658         llog_cleanup(env, uctxt);
659 out_close:
660         llog_cat_close(env, ctxt->loc_handle);
661 out_cleanup:
662         llog_cleanup(env, ctxt);
663         return rc;
664 }
665
666 static int mdd_changelog_init(const struct lu_env *env, struct mdd_device *mdd)
667 {
668         struct obd_device       *obd = mdd2obd_dev(mdd);
669         int                      rc;
670
671         mdd->mdd_cl.mc_index = 0;
672         spin_lock_init(&mdd->mdd_cl.mc_lock);
673         mdd->mdd_cl.mc_starttime = ktime_get();
674         spin_lock_init(&mdd->mdd_cl.mc_user_lock);
675         mdd->mdd_cl.mc_lastuser = 0;
676
677         /* ensure a GC check will, and a thread run may, occur upon start */
678         mdd->mdd_cl.mc_gc_time = 0;
679         mdd->mdd_cl.mc_gc_task = MDD_CHLG_GC_NONE;
680         mdd->mdd_cl.mc_mintime = (__u32)ktime_get_real_seconds();
681         mdd->mdd_cl.mc_minrec = ULLONG_MAX;
682
683         rc = mdd_changelog_llog_init(env, mdd);
684         if (rc) {
685                 CERROR("%s: changelog setup during init failed: rc = %d\n",
686                        obd->obd_name, rc);
687                 mdd->mdd_cl.mc_flags |= CLM_ERR;
688         }
689
690         return rc;
691 }
692
693 static void mdd_changelog_fini(const struct lu_env *env,
694                                struct mdd_device *mdd)
695 {
696         struct obd_device       *obd = mdd2obd_dev(mdd);
697         struct llog_ctxt        *ctxt;
698
699         if (mdd->mdd_cl.mc_flags & CLM_CLEANUP_DONE)
700                 return;
701         mdd->mdd_cl.mc_flags = CLM_CLEANUP_DONE;
702
703 again:
704         /* stop GC-thread if running */
705         spin_lock(&mdd->mdd_cl.mc_lock);
706         if (likely(mdd->mdd_cl.mc_gc_task == MDD_CHLG_GC_NONE)) {
707                 /* avoid any attempt to run a GC-thread */
708                 mdd->mdd_cl.mc_gc_task = current;
709                 spin_unlock(&mdd->mdd_cl.mc_lock);
710         } else {
711                 struct task_struct *gc_task;
712
713                 if (unlikely(mdd->mdd_cl.mc_gc_task == MDD_CHLG_GC_NEED ||
714                              mdd->mdd_cl.mc_gc_task == MDD_CHLG_GC_START)) {
715                         /* need to wait for birthing GC-thread to be started
716                          * and to have set mc_gc_task to itself
717                          */
718                         spin_unlock(&mdd->mdd_cl.mc_lock);
719                         /* Add a tiny sleep */
720                         schedule_timeout_uninterruptible(1);
721                         /* go back to fully check if GC-thread has started or
722                          * even already exited or if a new one is starting...
723                          */
724                         goto again;
725                 }
726                 /* take a reference on task_struct to avoid it to be freed
727                  * upon exit
728                  */
729                 gc_task = mdd->mdd_cl.mc_gc_task;
730                 get_task_struct(gc_task);
731                 spin_unlock(&mdd->mdd_cl.mc_lock);
732                 kthread_stop(gc_task);
733                 put_task_struct(gc_task);
734         }
735
736         ctxt = llog_get_context(obd, LLOG_CHANGELOG_ORIG_CTXT);
737         if (ctxt) {
738                 llog_cat_close(env, ctxt->loc_handle);
739                 llog_cleanup(env, ctxt);
740         }
741         ctxt = llog_get_context(obd, LLOG_CHANGELOG_USER_ORIG_CTXT);
742         if (ctxt) {
743                 llog_cat_close(env, ctxt->loc_handle);
744                 llog_cleanup(env, ctxt);
745         }
746 }
747
748 /**
749  * Remove entries with indicies up to and including \a endrec from the
750  *  changelog
751  * \param mdd
752  * \param endrec
753  * \retval 0 ok
754  */
755 static int
756 mdd_changelog_llog_cancel(const struct lu_env *env, struct mdd_device *mdd,
757                           unsigned long long endrec)
758 {
759         struct obd_device *obd = mdd2obd_dev(mdd);
760         struct llog_ctxt *ctxt;
761         unsigned long long cur;
762         struct changelog_cancel_cookie cookie;
763         int rc;
764
765         ctxt = llog_get_context(obd, LLOG_CHANGELOG_ORIG_CTXT);
766         if (!ctxt)
767                 return -ENXIO;
768
769         spin_lock(&mdd->mdd_cl.mc_lock);
770         cur = (long long)mdd->mdd_cl.mc_index;
771         spin_unlock(&mdd->mdd_cl.mc_lock);
772
773         /*
774          * If purging all records, write a header entry so we don't have an
775          * empty catalog and we're sure to have a valid starting index next
776          * time. In a case of crash, we just restart with old log so we're
777          * allright.
778          */
779         if (endrec >= cur) {
780                 rc = mdd_changelog_write_header(env, mdd, CLM_PURGE);
781                 if (rc)
782                         goto out;
783                 endrec = cur;
784         }
785
786         /*
787          * Some records were purged, so reset repeat-access time (so we
788          * record new mtime update records, so users can see a file has been
789          * changed since the last purge)
790          */
791         mdd->mdd_cl.mc_starttime = ktime_get();
792
793         cookie.endrec = endrec;
794         cookie.mdd = mdd;
795         rc = llog_changelog_cancel(env, ctxt, &cookie);
796 out:
797         llog_ctxt_put(ctxt);
798         return rc;
799 }
800
801 /** Add a CL_MARK record to the changelog
802  * \param mdd
803  * \param markerflags - CLM_*
804  * \retval 0 ok
805  */
806 int mdd_changelog_write_header(const struct lu_env *env,
807                                struct mdd_device *mdd, int markerflags)
808 {
809         struct obd_device               *obd = mdd2obd_dev(mdd);
810         struct llog_changelog_rec       *rec;
811         struct lu_buf                   *buf;
812         struct llog_ctxt                *ctxt;
813         int                              reclen;
814         int                              len = strlen(obd->obd_name);
815         int                              rc;
816
817         ENTRY;
818
819         if (mdd->mdd_cl.mc_current_mask & BIT(CL_MARK)) {
820                 mdd->mdd_cl.mc_starttime = ktime_get();
821                 RETURN(0);
822         }
823
824         reclen = llog_data_len(sizeof(*rec) + len);
825         buf = lu_buf_check_and_alloc(&mdd_env_info(env)->mdi_chlg_buf, reclen);
826         if (buf->lb_buf == NULL)
827                 RETURN(-ENOMEM);
828         rec = buf->lb_buf;
829
830         rec->cr.cr_flags = CLF_VERSION;
831         rec->cr.cr_type = CL_MARK;
832         rec->cr.cr_namelen = len;
833         memcpy(changelog_rec_name(&rec->cr), obd->obd_name, rec->cr.cr_namelen);
834         /* Status and action flags */
835         rec->cr.cr_markerflags = mdd->mdd_cl.mc_flags | markerflags;
836         rec->cr_hdr.lrh_len = llog_data_len(changelog_rec_size(&rec->cr) +
837                                             rec->cr.cr_namelen);
838         rec->cr_hdr.lrh_type = CHANGELOG_REC;
839         rec->cr.cr_time = cl_time();
840
841         ctxt = llog_get_context(obd, LLOG_CHANGELOG_ORIG_CTXT);
842         LASSERT(ctxt);
843
844         rc = llog_cat_add(env, ctxt->loc_handle, &rec->cr_hdr, NULL);
845         if (rc > 0)
846                 rc = 0;
847         llog_ctxt_put(ctxt);
848
849         /* assume on or off event; reset repeat-access time */
850         mdd->mdd_cl.mc_starttime = ktime_get();
851         RETURN(rc);
852 }
853
854 /**
855  * Lookup method for "fid" object. Only filenames with correct SEQ:OID format
856  * are valid. We also check if object with passed fid exists or not.
857  */
858 static int obf_lookup(const struct lu_env *env, struct md_object *p,
859                       const struct lu_name *lname, struct lu_fid *f,
860                       struct md_op_spec *spec)
861 {
862         char *name = (char *)lname->ln_name;
863         struct mdd_device *mdd = mdo2mdd(p);
864         struct mdd_object *child;
865         int rc = 0;
866
867         while (*name == '[')
868                 name++;
869
870         sscanf(name, SFID, RFID(f));
871         if (!fid_is_sane(f))
872                 GOTO(out, rc = -ENOENT);
873
874         if (!fid_is_norm(f) && !fid_is_igif(f) && !fid_is_root(f) &&
875             !fid_seq_is_dot(f->f_seq))
876                 GOTO(out, rc = -ENOENT);
877
878         /* Check if object with this fid exists */
879         child = mdd_object_find(env, mdd, f);
880         if (IS_ERR(child))
881                 GOTO(out, rc = PTR_ERR(child));
882
883         if (mdd_object_exists(child) == 0)
884                 rc = -ENOENT;
885
886         mdd_object_put(env, child);
887
888 out:
889         return rc;
890 }
891
892 static int mdd_dummy_create(const struct lu_env *env,
893                             struct md_object *pobj,
894                             const struct lu_name *lname,
895                             struct md_object *child,
896                             struct md_op_spec *spec,
897                             struct md_attr* ma)
898 {
899         return -EPERM;
900 }
901
902 static int mdd_dummy_rename(const struct lu_env *env,
903                             struct md_object *src_pobj,
904                             struct md_object *tgt_pobj,
905                             const struct lu_fid *lf,
906                             const struct lu_name *lsname,
907                             struct md_object *tobj,
908                             const struct lu_name *ltname,
909                             struct md_attr *ma)
910 {
911         return -EPERM;
912 }
913
914 static int mdd_dummy_link(const struct lu_env *env,
915                           struct md_object *tgt_obj,
916                           struct md_object *src_obj,
917                           const struct lu_name *lname,
918                           struct md_attr *ma)
919 {
920         return -EPERM;
921 }
922
923 static int mdd_dummy_unlink(const struct lu_env *env,
924                             struct md_object *pobj,
925                             struct md_object *cobj,
926                             const struct lu_name *lname,
927                             struct md_attr *ma,
928                             int no_name)
929 {
930         return -EPERM;
931 }
932
933 int mdd_create(const struct lu_env *env, struct md_object *pobj,
934                       const struct lu_name *lname, struct md_object *child,
935                       struct md_op_spec *spec, struct md_attr *ma);
936 static int mdd_obf_create(const struct lu_env *env, struct md_object *pobj,
937                       const struct lu_name *lname, struct md_object *child,
938                       struct md_op_spec *spec, struct md_attr *ma)
939 {
940         if (spec->sp_cr_flags & MDS_OPEN_VOLATILE)
941                 return mdd_create(env, pobj, lname, child, spec, ma);
942         RETURN(-EPERM);
943 }
944
945 static const struct md_dir_operations mdd_obf_dir_ops = {
946         .mdo_lookup = obf_lookup,
947         .mdo_create = mdd_obf_create,
948         .mdo_rename = mdd_dummy_rename,
949         .mdo_link   = mdd_dummy_link,
950         .mdo_unlink = mdd_dummy_unlink
951 };
952
953 static const struct md_dir_operations mdd_lpf_dir_ops = {
954         .mdo_lookup = mdd_lookup,
955         .mdo_create = mdd_dummy_create,
956         .mdo_rename = mdd_dummy_rename,
957         .mdo_link   = mdd_dummy_link,
958         .mdo_unlink = mdd_dummy_unlink
959 };
960
961 static struct md_object *mdo_locate(const struct lu_env *env,
962                                     struct md_device *md,
963                                     const struct lu_fid *fid)
964 {
965         struct lu_object *obj;
966         struct md_object *mdo;
967
968         obj = lu_object_find(env, &md->md_lu_dev, fid, NULL);
969         if (!IS_ERR(obj)) {
970                 obj = lu_object_locate(obj->lo_header, md->md_lu_dev.ld_type);
971                 LASSERT(obj != NULL);
972                 mdo = lu2md(obj);
973         } else {
974                 mdo = ERR_CAST(obj);
975         }
976         return mdo;
977 }
978
979 static int mdd_lpf_setup(const struct lu_env *env, struct mdd_device *m)
980 {
981         struct md_object        *mdo;
982         struct mdd_object       *mdd_lpf;
983         struct lu_fid            fid    = LU_LPF_FID;
984         int                      rc;
985         ENTRY;
986
987         rc = mdd_local_file_create(env, m, mdd_object_fid(m->mdd_dot_lustre),
988                                    mdd_lpf_dir_name, S_IFDIR | S_IRUSR | S_IXUSR,
989                                    &fid);
990         if (rc != 0)
991                 RETURN(rc);
992
993         mdo = mdo_locate(env, &m->mdd_md_dev, &fid);
994         if (IS_ERR(mdo))
995                 RETURN(PTR_ERR(mdo));
996
997         LASSERT(lu_object_exists(&mdo->mo_lu));
998
999         mdd_lpf = md2mdd_obj(mdo);
1000         mdd_lpf->mod_obj.mo_dir_ops = &mdd_lpf_dir_ops;
1001         m->mdd_dot_lustre_objs.mdd_lpf = mdd_lpf;
1002
1003         RETURN(0);
1004 }
1005
1006 /**
1007  * Create special in-memory "fid" object for open-by-fid.
1008  */
1009 static int mdd_obf_setup(const struct lu_env *env, struct mdd_device *m)
1010 {
1011         struct md_object        *mdo;
1012         struct mdd_object       *mdd_obf;
1013         struct lu_fid            fid = LU_OBF_FID;
1014         int                      rc;
1015
1016         rc = mdd_local_file_create(env, m, mdd_object_fid(m->mdd_dot_lustre),
1017                                    mdd_obf_dir_name, S_IFDIR | S_IXUSR, &fid);
1018         if (rc < 0)
1019                 RETURN(rc);
1020
1021         mdo = mdo_locate(env, &m->mdd_md_dev, &fid);
1022         if (IS_ERR(mdo))
1023                 RETURN(PTR_ERR(mdo));
1024
1025         LASSERT(lu_object_exists(&mdo->mo_lu));
1026
1027         mdd_obf = md2mdd_obj(mdo);
1028         mdd_obf->mod_obj.mo_dir_ops = &mdd_obf_dir_ops;
1029         m->mdd_dot_lustre_objs.mdd_obf = mdd_obf;
1030
1031         return 0;
1032 }
1033
1034 static void mdd_dot_lustre_cleanup(const struct lu_env *env,
1035                                    struct mdd_device *m)
1036 {
1037         if (m->mdd_dot_lustre_objs.mdd_lpf != NULL) {
1038                 mdd_object_put(env, m->mdd_dot_lustre_objs.mdd_lpf);
1039                 m->mdd_dot_lustre_objs.mdd_lpf = NULL;
1040         }
1041         if (m->mdd_dot_lustre_objs.mdd_obf != NULL) {
1042                 mdd_object_put(env, m->mdd_dot_lustre_objs.mdd_obf);
1043                 m->mdd_dot_lustre_objs.mdd_obf = NULL;
1044         }
1045         if (m->mdd_dot_lustre != NULL) {
1046                 mdd_object_put(env, m->mdd_dot_lustre);
1047                 m->mdd_dot_lustre = NULL;
1048         }
1049 }
1050
1051 /** Setup ".lustre" directory object */
1052 static int mdd_dot_lustre_setup(const struct lu_env *env, struct mdd_device *m)
1053 {
1054         struct md_object        *mdo;
1055         struct lu_fid            fid;
1056         int                      rc;
1057
1058         ENTRY;
1059         /* Create ".lustre" directory in ROOT. */
1060         fid = LU_DOT_LUSTRE_FID;
1061         rc = mdd_local_file_create(env, m, &m->mdd_root_fid,
1062                                    dot_lustre_name,
1063                                    S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO,
1064                                    &fid);
1065         if (rc < 0)
1066                 RETURN(rc);
1067         mdo = mdo_locate(env, &m->mdd_md_dev, &fid);
1068         if (IS_ERR(mdo))
1069                 RETURN(PTR_ERR(mdo));
1070         LASSERT(lu_object_exists(&mdo->mo_lu));
1071
1072         m->mdd_dot_lustre = md2mdd_obj(mdo);
1073
1074         rc = mdd_obf_setup(env, m);
1075         if (rc) {
1076                 CERROR("%s: error initializing \"fid\" object: rc = %d.\n",
1077                        mdd2obd_dev(m)->obd_name, rc);
1078                 GOTO(out, rc);
1079         }
1080
1081         rc = mdd_lpf_setup(env, m);
1082         if (rc != 0) {
1083                 CERROR("%s: error initializing \"lost+found\": rc = %d.\n",
1084                        mdd2obd_dev(m)->obd_name, rc);
1085                 GOTO(out, rc);
1086         }
1087
1088         RETURN(0);
1089
1090 out:
1091         mdd_dot_lustre_cleanup(env, m);
1092
1093         return rc;
1094 }
1095
1096 /**
1097  * set llog methods and create LLOG_AGENT_ORIG_CTXT llog
1098  * object in obd_device
1099  */
1100 static int mdd_hsm_actions_llog_init(const struct lu_env *env,
1101                                      struct mdd_device *m)
1102 {
1103         struct obd_device       *obd = mdd2obd_dev(m);
1104         struct llog_ctxt        *ctxt = NULL;
1105         int                      rc;
1106         ENTRY;
1107
1108         OBD_SET_CTXT_MAGIC(&obd->obd_lvfs_ctxt);
1109         obd->obd_lvfs_ctxt.dt = m->mdd_bottom;
1110
1111         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_AGENT_ORIG_CTXT,
1112                         obd, &llog_common_cat_ops);
1113         if (rc) {
1114                 CERROR("%s: hsm actions llog setup failed: rc = %d\n",
1115                         obd->obd_name, rc);
1116                 RETURN(rc);
1117         }
1118
1119         ctxt = llog_get_context(obd, LLOG_AGENT_ORIG_CTXT);
1120         LASSERT(ctxt);
1121
1122         rc = llog_open_create(env, ctxt, &ctxt->loc_handle, NULL,
1123                               HSM_ACTIONS);
1124         if (rc) {
1125                 CERROR("%s: hsm actions llog open_create failed: rc = %d\n",
1126                         obd->obd_name, rc);
1127                 GOTO(out_cleanup, rc);
1128         }
1129
1130         rc = llog_init_handle(env, ctxt->loc_handle, LLOG_F_IS_CAT, NULL);
1131         if (rc)
1132                 GOTO(out_close, rc);
1133
1134         llog_ctxt_put(ctxt);
1135         RETURN(0);
1136
1137 out_close:
1138         llog_cat_close(env, ctxt->loc_handle);
1139         ctxt->loc_handle = NULL;
1140 out_cleanup:
1141         llog_cleanup(env, ctxt);
1142
1143         return rc;
1144 }
1145
1146 /**
1147  * cleanup the context created by llog_setup_named()
1148  */
1149 static int mdd_hsm_actions_llog_fini(const struct lu_env *env,
1150                                      struct mdd_device *m)
1151 {
1152         struct obd_device       *obd = mdd2obd_dev(m);
1153         struct llog_ctxt        *lctxt;
1154         ENTRY;
1155
1156         lctxt = llog_get_context(obd, LLOG_AGENT_ORIG_CTXT);
1157         if (lctxt) {
1158                 llog_cat_close(env, lctxt->loc_handle);
1159                 lctxt->loc_handle = NULL;
1160                 llog_cleanup(env, lctxt);
1161         }
1162
1163         RETURN(0);
1164 }
1165
1166 static void mdd_device_shutdown(const struct lu_env *env, struct mdd_device *m,
1167                                 struct lustre_cfg *cfg)
1168 {
1169         barrier_deregister(m->mdd_bottom);
1170         lfsck_degister(env, m->mdd_bottom);
1171         mdd_hsm_actions_llog_fini(env, m);
1172         mdd_changelog_fini(env, m);
1173         mdd_orphan_index_fini(env, m);
1174         mdd_dot_lustre_cleanup(env, m);
1175         if (obd2obt(mdd2obd_dev(m))->obt_nodemap_config_file) {
1176                 struct obd_device_target *obt = obd2obt(mdd2obd_dev(m));
1177
1178                 nm_config_file_deregister_tgt(env,
1179                                               obt->obt_nodemap_config_file);
1180                 obt->obt_nodemap_config_file = NULL;
1181         }
1182         if (m->mdd_los != NULL) {
1183                 local_oid_storage_fini(env, m->mdd_los);
1184                 m->mdd_los = NULL;
1185         }
1186         lu_site_purge(env, mdd2lu_dev(m)->ld_site, ~0);
1187
1188         if (m->mdd_child_exp)
1189                 obd_disconnect(m->mdd_child_exp);
1190 }
1191
1192 static int mdd_process_config(const struct lu_env *env,
1193                               struct lu_device *d, struct lustre_cfg *cfg)
1194 {
1195         struct mdd_device *m    = lu2mdd_dev(d);
1196         struct dt_device  *dt   = m->mdd_child;
1197         struct lu_device  *next = &dt->dd_lu_dev;
1198         int rc;
1199         ENTRY;
1200
1201         switch (cfg->lcfg_command) {
1202         case LCFG_PARAM: {
1203                 ssize_t count;
1204
1205                 count = class_modify_config(cfg, PARAM_MDD, &m->mdd_kobj);
1206                 rc = count > 0 ? 0 : count;
1207                 if (rc)
1208                         /* we don't understand; pass it on */
1209                         rc = next->ld_ops->ldo_process_config(env, next, cfg);
1210                 break;
1211         }
1212         case LCFG_SETUP:
1213                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
1214                 if (rc)
1215                         GOTO(out, rc);
1216                 dt_conf_get(env, dt, &m->mdd_dt_conf);
1217                 break;
1218         case LCFG_PRE_CLEANUP:
1219                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
1220                 mdd_generic_thread_stop(&m->mdd_orphan_cleanup_thread);
1221                 break;
1222         case LCFG_CLEANUP:
1223                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
1224                 lu_dev_del_linkage(d->ld_site, d);
1225                 mdd_device_shutdown(env, m, cfg);
1226                 break;
1227         default:
1228                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
1229                 break;
1230         }
1231 out:
1232         RETURN(rc);
1233 }
1234
1235 static int mdd_recovery_complete(const struct lu_env *env,
1236                                  struct lu_device *d)
1237 {
1238         struct mdd_device *mdd = lu2mdd_dev(d);
1239         struct lu_device *next;
1240         int rc;
1241         ENTRY;
1242
1243         LASSERT(mdd != NULL);
1244         next = &mdd->mdd_child->dd_lu_dev;
1245
1246         if (!mdd->mdd_bottom->dd_rdonly)
1247                 mdd_orphan_cleanup(env, mdd);
1248         rc = next->ld_ops->ldo_recovery_complete(env, next);
1249
1250         RETURN(rc);
1251 }
1252
1253 int mdd_local_file_create(const struct lu_env *env, struct mdd_device *mdd,
1254                           const struct lu_fid *pfid, const char *name,
1255                           __u32 mode, struct lu_fid *fid)
1256 {
1257         struct dt_object *parent, *dto;
1258         int rc = 0;
1259
1260         ENTRY;
1261
1262         LASSERT(!fid_is_zero(pfid));
1263         parent = dt_locate(env, mdd->mdd_bottom, pfid);
1264         if (unlikely(IS_ERR(parent)))
1265                 RETURN(PTR_ERR(parent));
1266
1267         /* create local file/dir, if @fid is passed then try to use it */
1268         if (fid_is_zero(fid))
1269                 dto = local_file_find_or_create(env, mdd->mdd_los, parent,
1270                                                 name, mode);
1271         else
1272                 dto = local_file_find_or_create_with_fid(env, mdd->mdd_bottom,
1273                                                          fid, parent, name,
1274                                                          mode);
1275         if (IS_ERR(dto))
1276                 GOTO(out_put, rc = PTR_ERR(dto));
1277         *fid = *lu_object_fid(&dto->do_lu);
1278         /* since stack is not fully set up the local_storage uses own stack
1279          * and we should drop its object from cache */
1280         dt_object_put_nocache(env, dto);
1281         EXIT;
1282 out_put:
1283         dt_object_put(env, parent);
1284         return rc;
1285 }
1286
1287 static int mdd_lfsck_out_notify(const struct lu_env *env, void *data,
1288                                 enum lfsck_events event)
1289 {
1290         return 0;
1291 }
1292
1293 static int mdd_prepare(const struct lu_env *env,
1294                        struct lu_device *pdev,
1295                        struct lu_device *cdev)
1296 {
1297         struct mdd_device *mdd = lu2mdd_dev(cdev);
1298         struct lu_device *next = &mdd->mdd_child->dd_lu_dev;
1299         struct nm_config_file *nodemap_config;
1300         struct obd_device_target *obt = obd2obt(mdd2obd_dev(mdd));
1301         struct dt_object *root = NULL;
1302         struct thandle *th = NULL;
1303         struct lu_fid fid;
1304         int rc;
1305
1306         ENTRY;
1307
1308         rc = next->ld_ops->ldo_prepare(env, cdev, next);
1309         if (rc)
1310                 RETURN(rc);
1311
1312         /* Setup local dirs */
1313         fid.f_seq = FID_SEQ_LOCAL_NAME;
1314         fid.f_oid = 1;
1315         fid.f_ver = 0;
1316         rc = local_oid_storage_init(env, mdd->mdd_bottom, &fid,
1317                                     &mdd->mdd_los);
1318         if (rc)
1319                 RETURN(rc);
1320
1321         rc = dt_root_get(env, mdd->mdd_child, &mdd->mdd_local_root_fid);
1322         if (rc < 0)
1323                 GOTO(out_los, rc);
1324
1325         lu_root_fid(&fid);
1326         if (mdd_seq_site(mdd)->ss_node_id == 0) {
1327                 rc = mdd_local_file_create(env, mdd, &mdd->mdd_local_root_fid,
1328                                            mdd_root_dir_name, S_IFDIR |
1329                                            S_IRUGO | S_IWUSR | S_IXUGO, &fid);
1330                 if (rc != 0) {
1331                         CERROR("%s: create root fid failed: rc = %d\n",
1332                                mdd2obd_dev(mdd)->obd_name, rc);
1333                         GOTO(out_los, rc);
1334                 }
1335
1336                 /* store a default directory layout on the root directory if
1337                  * it doesn't already exist to improve MDT space balance.
1338                  */
1339                 root = dt_locate(env, mdd->mdd_bottom, &fid);
1340                 if (unlikely(IS_ERR(root)))
1341                         GOTO(out_los, rc = PTR_ERR(root));
1342
1343                 rc = dt_xattr_get(env, root, &LU_BUF_NULL,
1344                                   XATTR_NAME_DEFAULT_LMV);
1345                 if (rc == -ENODATA) {
1346                         struct lu_buf buf;
1347                         struct lmv_user_md lmv_default = {
1348                                 .lum_magic              = LMV_USER_MAGIC,
1349                                 .lum_stripe_count       = 1,
1350                                 .lum_stripe_offset      = root_stripe_offset,
1351                                 .lum_max_inherit        = root_max_inherit,
1352                                 .lum_max_inherit_rr     = root_max_inherit_rr,
1353                         };
1354
1355                         th = dt_trans_create(env, mdd->mdd_bottom);
1356                         if (IS_ERR(th))
1357                                 GOTO(out_root_put, rc = PTR_ERR(th));
1358
1359                         buf.lb_buf = &lmv_default;
1360                         buf.lb_len = sizeof(lmv_default);
1361                         rc = dt_declare_xattr_set(env, root, &buf,
1362                                                   XATTR_NAME_DEFAULT_LMV, 0,
1363                                                   th);
1364                         if (rc)
1365                                 GOTO(out_trans_stop, rc);
1366
1367                         rc = dt_trans_start_local(env, mdd->mdd_bottom, th);
1368                         if (rc)
1369                                 GOTO(out_trans_stop, rc);
1370
1371                         rc = dt_xattr_set(env, root, &buf,
1372                                           XATTR_NAME_DEFAULT_LMV, 0, th);
1373                         if (rc)
1374                                 GOTO(out_trans_stop, rc);
1375
1376                         dt_trans_stop(env, mdd->mdd_bottom, th);
1377                         th = NULL;
1378                 } else if (rc < 0 && rc != -ERANGE) {
1379                         CERROR("%s: get default LMV of root failed: rc = %d\n",
1380                                mdd2obd_dev(mdd)->obd_name, rc);
1381
1382                         GOTO(out_root_put, rc);
1383                 }
1384
1385                 dt_object_put(env, root);
1386                 root = NULL;
1387
1388                 mdd->mdd_root_fid = fid;
1389                 rc = mdd_dot_lustre_setup(env, mdd);
1390                 if (rc != 0) {
1391                         CERROR("%s: initializing .lustre failed: rc = %d\n",
1392                                mdd2obd_dev(mdd)->obd_name, rc);
1393                         GOTO(out_los, rc);
1394                 }
1395         } else {
1396                 /* Normal client usually send root access to MDT0 directly,
1397                  * the root FID on non-MDT0 will only be used by echo client. */
1398                 mdd->mdd_root_fid = fid;
1399         }
1400
1401         rc = mdd_orphan_index_init(env, mdd);
1402         if (rc < 0)
1403                 GOTO(out_dot, rc);
1404
1405         rc = mdd_changelog_init(env, mdd);
1406         if (rc != 0) {
1407                 CERROR("%s: failed to initialize changelog: rc = %d\n",
1408                        mdd2obd_dev(mdd)->obd_name, rc);
1409                 GOTO(out_orph, rc);
1410         }
1411
1412         rc = mdd_hsm_actions_llog_init(env, mdd);
1413         if (rc != 0)
1414                 GOTO(out_changelog, rc);
1415
1416         nodemap_config = nm_config_file_register_tgt(env, mdd->mdd_bottom,
1417                                                      mdd->mdd_los);
1418         if (IS_ERR(nodemap_config)) {
1419                 rc = PTR_ERR(nodemap_config);
1420                 if (rc != -EROFS)
1421                         GOTO(out_hsm, rc);
1422         } else {
1423                 obt->obt_nodemap_config_file = nodemap_config;
1424         }
1425
1426         rc = lfsck_register(env, mdd->mdd_bottom, mdd->mdd_child,
1427                             mdd2obd_dev(mdd), mdd_lfsck_out_notify,
1428                             mdd, true);
1429         if (rc != 0) {
1430                 CERROR("%s: failed to initialize lfsck: rc = %d\n",
1431                        mdd2obd_dev(mdd)->obd_name, rc);
1432                 GOTO(out_nodemap, rc);
1433         }
1434
1435         rc = barrier_register(mdd->mdd_bottom, mdd->mdd_child);
1436         if (rc) {
1437                 CERROR("%s: failed to register to barrier: rc = %d\n",
1438                        mdd2obd_dev(mdd)->obd_name, rc);
1439                 GOTO(out_lfsck, rc);
1440         }
1441
1442         RETURN(0);
1443
1444 out_lfsck:
1445         lfsck_degister(env, mdd->mdd_bottom);
1446 out_nodemap:
1447         nm_config_file_deregister_tgt(env, obt->obt_nodemap_config_file);
1448         obt->obt_nodemap_config_file = NULL;
1449 out_hsm:
1450         mdd_hsm_actions_llog_fini(env, mdd);
1451 out_changelog:
1452         mdd_changelog_fini(env, mdd);
1453 out_orph:
1454         mdd_orphan_index_fini(env, mdd);
1455 out_dot:
1456         if (mdd_seq_site(mdd)->ss_node_id == 0)
1457                 mdd_dot_lustre_cleanup(env, mdd);
1458 out_trans_stop:
1459         if (th != NULL)
1460                 dt_trans_stop(env, mdd->mdd_bottom, th);
1461 out_root_put:
1462         if (root != NULL)
1463                 dt_object_put(env, root);
1464 out_los:
1465         local_oid_storage_fini(env, mdd->mdd_los);
1466         mdd->mdd_los = NULL;
1467
1468         return rc;
1469 }
1470
1471 /**
1472  * Implementation of lu_device_operations::ldo_fid_alloc() for MDD.
1473  *
1474  * Find corresponding device by passed parent and name, and allocate FID from
1475  * there.
1476  *
1477  * see include/lu_object.h for the details.
1478  */
1479 static int mdd_fid_alloc(const struct lu_env *env, struct lu_device *d,
1480                          struct lu_fid *fid, struct lu_object *parent,
1481                          const struct lu_name *name)
1482 {
1483         struct mdd_device *mdd = lu2mdd_dev(d);
1484         struct lu_object *o = lu_object_next(parent);
1485
1486         return dt_fid_alloc(env, mdd->mdd_child, fid, o, name);
1487 }
1488
1489 const struct lu_device_operations mdd_lu_ops = {
1490         .ldo_object_alloc      = mdd_object_alloc,
1491         .ldo_process_config    = mdd_process_config,
1492         .ldo_recovery_complete = mdd_recovery_complete,
1493         .ldo_prepare           = mdd_prepare,
1494         .ldo_fid_alloc         = mdd_fid_alloc,
1495 };
1496
1497 static int mdd_root_get(const struct lu_env *env,
1498                         struct md_device *m, struct lu_fid *f)
1499 {
1500         struct mdd_device *mdd = lu2mdd_dev(&m->md_lu_dev);
1501
1502         ENTRY;
1503         *f = mdd->mdd_root_fid;
1504         RETURN(0);
1505 }
1506
1507 /*
1508  * No permission check is needed.
1509  */
1510 static int mdd_statfs(const struct lu_env *env, struct md_device *m,
1511                       struct obd_statfs *sfs)
1512 {
1513         struct mdd_device *mdd = lu2mdd_dev(&m->md_lu_dev);
1514         int rc;
1515
1516         ENTRY;
1517
1518         rc = mdd_child_ops(mdd)->dt_statfs(env, mdd->mdd_child, sfs, NULL);
1519
1520         sfs->os_namelen = min_t(__u32, sfs->os_namelen, NAME_MAX);
1521
1522         RETURN(rc);
1523 }
1524
1525 static const struct dt_device_param *mdd_dtconf_get(const struct lu_env *env,
1526                                                     struct md_device *m)
1527 {
1528         struct mdd_device *mdd = lu2mdd_dev(&m->md_lu_dev);
1529
1530         return &mdd->mdd_dt_conf;
1531 }
1532
1533 static int mdd_llog_ctxt_get(const struct lu_env *env, struct md_device *m,
1534                              int idx, void **h)
1535 {
1536         struct mdd_device *mdd = lu2mdd_dev(&m->md_lu_dev);
1537
1538         *h = llog_group_get_ctxt(&mdd2obd_dev(mdd)->obd_olg, idx);
1539         return (*h == NULL ? -ENOENT : 0);
1540 }
1541
1542 static struct lu_device *mdd_device_free(const struct lu_env *env,
1543                                          struct lu_device *lu)
1544 {
1545         struct mdd_device *m = lu2mdd_dev(lu);
1546         ENTRY;
1547
1548         LASSERT(atomic_read(&lu->ld_ref) == 0);
1549         md_device_fini(&m->mdd_md_dev);
1550         OBD_FREE_PTR(m);
1551         RETURN(NULL);
1552 }
1553
1554 static struct lu_device *mdd_device_alloc(const struct lu_env *env,
1555                                           struct lu_device_type *t,
1556                                           struct lustre_cfg *lcfg)
1557 {
1558         struct lu_device  *l;
1559         struct mdd_device *m;
1560
1561         OBD_ALLOC_PTR(m);
1562         if (m == NULL) {
1563                 l = ERR_PTR(-ENOMEM);
1564         } else {
1565                 int rc;
1566
1567                 l = mdd2lu_dev(m);
1568                 md_device_init(&m->mdd_md_dev, t);
1569                 rc = mdd_init0(env, m, t, lcfg);
1570                 if (rc != 0) {
1571                         mdd_device_free(env, l);
1572                         l = ERR_PTR(rc);
1573                 }
1574         }
1575
1576         return l;
1577 }
1578
1579 /*
1580  * we use exports to track all mdd users
1581  */
1582 static int mdd_obd_connect(const struct lu_env *env, struct obd_export **exp,
1583                            struct obd_device *obd, struct obd_uuid *cluuid,
1584                            struct obd_connect_data *data, void *localdata)
1585 {
1586         struct mdd_device    *mdd = lu2mdd_dev(obd->obd_lu_dev);
1587         struct lustre_handle  conn;
1588         int                   rc;
1589         ENTRY;
1590
1591         CDEBUG(D_CONFIG, "connect #%d\n", mdd->mdd_connects);
1592
1593         rc = class_connect(&conn, obd, cluuid);
1594         if (rc)
1595                 RETURN(rc);
1596
1597         *exp = class_conn2export(&conn);
1598
1599         /* Why should there ever be more than 1 connect? */
1600         LASSERT(mdd->mdd_connects == 0);
1601         mdd->mdd_connects++;
1602
1603         RETURN(0);
1604 }
1605
1606 /*
1607  * once last export (we don't count self-export) disappeared
1608  * mdd can be released
1609  */
1610 static int mdd_obd_disconnect(struct obd_export *exp)
1611 {
1612         struct obd_device *obd = exp->exp_obd;
1613         struct mdd_device *mdd = lu2mdd_dev(obd->obd_lu_dev);
1614         int                rc, release = 0;
1615         ENTRY;
1616
1617         mdd->mdd_connects--;
1618         if (mdd->mdd_connects == 0)
1619                 release = 1;
1620
1621         rc = class_disconnect(exp);
1622
1623         if (rc == 0 && release)
1624                 class_manual_cleanup(obd);
1625         RETURN(rc);
1626 }
1627
1628 static int mdd_obd_get_info(const struct lu_env *env, struct obd_export *exp,
1629                             __u32 keylen, void *key, __u32 *vallen, void *val)
1630 {
1631         int rc = -EINVAL;
1632
1633         if (KEY_IS(KEY_OSP_CONNECTED)) {
1634                 struct obd_device       *obd = exp->exp_obd;
1635                 struct mdd_device       *mdd;
1636
1637                 if (!obd->obd_set_up || obd->obd_stopping)
1638                         RETURN(-EAGAIN);
1639
1640                 mdd = lu2mdd_dev(obd->obd_lu_dev);
1641                 LASSERT(mdd);
1642                 rc = obd_get_info(env, mdd->mdd_child_exp, keylen, key, vallen,
1643                                   val);
1644                 RETURN(rc);
1645         }
1646
1647         RETURN(rc);
1648 }
1649
1650 static int mdd_obd_set_info_async(const struct lu_env *env,
1651                                   struct obd_export *exp,
1652                                   __u32 keylen, void *key,
1653                                   __u32 vallen, void *val,
1654                                   struct ptlrpc_request_set *set)
1655 {
1656         struct obd_device       *obd = exp->exp_obd;
1657         struct mdd_device       *mdd;
1658         int                      rc;
1659
1660         if (!obd->obd_set_up || obd->obd_stopping)
1661                 RETURN(-EAGAIN);
1662
1663         mdd = lu2mdd_dev(obd->obd_lu_dev);
1664         LASSERT(mdd);
1665         rc = obd_set_info_async(env, mdd->mdd_child_exp, keylen, key,
1666                                 vallen, val, set);
1667         RETURN(rc);
1668 }
1669
1670 static const struct obd_ops mdd_obd_device_ops = {
1671         .o_owner        = THIS_MODULE,
1672         .o_connect      = mdd_obd_connect,
1673         .o_disconnect   = mdd_obd_disconnect,
1674         .o_get_info     = mdd_obd_get_info,
1675         .o_set_info_async = mdd_obd_set_info_async,
1676 };
1677
1678 struct mdd_changelog_name_check_data {
1679         const char *mcnc_name;
1680         __u32       mcnc_id;
1681 };
1682
1683 /**
1684  * changelog_recalc_mask callback
1685  *
1686  * Is is called per each registered user and calculates combined mask of
1687  * all registered users.
1688  */
1689 static int mdd_changelog_name_check_cb(const struct lu_env *env,
1690                                        struct llog_handle *llh,
1691                                        struct llog_rec_hdr *hdr, void *data)
1692 {
1693         struct llog_changelog_user_rec2 *rec;
1694         struct mdd_changelog_name_check_data *mcnc = data;
1695
1696         rec = container_of(hdr, typeof(*rec), cur_hdr);
1697         if (rec->cur_hdr.lrh_type == CHANGELOG_USER_REC2 &&
1698             !strncmp(rec->cur_name, mcnc->mcnc_name, sizeof(rec->cur_name))) {
1699                 mcnc->mcnc_id = rec->cur_id;
1700                 return -EEXIST;
1701         }
1702         return 0;
1703 }
1704
1705 static int mdd_changelog_name_check(const struct lu_env *env,
1706                                     struct llog_ctxt *ctxt,
1707                                     struct mdd_device *mdd, const char *name)
1708 {
1709         struct mdd_changelog_name_check_data mcnc = { .mcnc_name = name, };
1710         int chr = 0;
1711         int rc;
1712
1713         ENTRY;
1714
1715         /* first symbol is a letter */
1716         if (!isalpha(name[0])) {
1717                 rc = -EINVAL;
1718                 CERROR("%s: first char '%c' in '%s' is not letter: rc = %d\n",
1719                        mdd2obd_dev(mdd)->obd_name, name[0], name, rc);
1720                 RETURN(rc);
1721         }
1722
1723         /* name is valid: contains letters, numbers and '-', '_' only */
1724         while (name[++chr]) {
1725                 if (!(isalnum(name[chr]) || name[chr] == '_' ||
1726                       name[chr] == '-')) {
1727                         rc = -EINVAL;
1728                         CERROR("%s: wrong char '%c' in name '%s': rc = %d\n",
1729                                mdd2obd_dev(mdd)->obd_name, name[chr], name, rc);
1730                         RETURN(rc);
1731                 }
1732         }
1733
1734         if (chr > CHANGELOG_USER_NAMELEN) {
1735                 rc = -ENAMETOOLONG;
1736                 CERROR("%s: name '%s' is over %d symbols limit: rc = %d\n",
1737                        mdd2obd_dev(mdd)->obd_name, name,
1738                        CHANGELOG_USER_NAMELEN, rc);
1739                 RETURN(rc);
1740         }
1741
1742         rc = llog_cat_process(env, ctxt->loc_handle,
1743                               mdd_changelog_name_check_cb, &mcnc, 0, 0);
1744         if (rc == -EEXIST)
1745                 CWARN("%s: changelog name %s exists already: rc = %d\n",
1746                       mdd2obd_dev(mdd)->obd_name, name, rc);
1747         else if (rc < 0)
1748                 CWARN("%s: failed user changelog processing: rc = %d\n",
1749                       mdd2obd_dev(mdd)->obd_name, rc);
1750         RETURN(rc);
1751 }
1752
1753 static int mdd_changelog_user_register(const struct lu_env *env,
1754                                        struct mdd_device *mdd, int *id,
1755                                        const char *name, const char *mask)
1756 {
1757         struct llog_ctxt *ctxt;
1758         struct llog_changelog_user_rec2 *rec;
1759         char user_name[CHANGELOG_USER_NAMELEN_FULL];
1760         int rc;
1761
1762         ENTRY;
1763
1764         ctxt = llog_get_context(mdd2obd_dev(mdd),
1765                                 LLOG_CHANGELOG_USER_ORIG_CTXT);
1766         if (ctxt == NULL)
1767                 RETURN(-ENXIO);
1768
1769         OBD_ALLOC_PTR(rec);
1770         if (rec == NULL) {
1771                 llog_ctxt_put(ctxt);
1772                 RETURN(-ENOMEM);
1773         }
1774
1775         CFS_RACE(CFS_FAIL_CHLOG_USER_REG_UNREG_RACE);
1776
1777         rec->cur_hdr.lrh_len = sizeof(*rec);
1778         /* keep old record type for users without mask/name for
1779          * compatibility needs
1780          */
1781         if (mask || (name && name[0]))
1782                 rec->cur_hdr.lrh_type = CHANGELOG_USER_REC2;
1783         else
1784                 rec->cur_hdr.lrh_type = CHANGELOG_USER_REC;
1785         spin_lock(&mdd->mdd_cl.mc_user_lock);
1786         if (mdd->mdd_cl.mc_lastuser == (unsigned int)(-1)) {
1787                 spin_unlock(&mdd->mdd_cl.mc_user_lock);
1788                 rc = -EOVERFLOW;
1789                 CERROR("%s: registering %s user: max ID is exceeded: rc = %d\n",
1790                        mdd2obd_dev(mdd)->obd_name,
1791                        (name && name[0]) ? name : "new", rc);
1792                 GOTO(out, rc);
1793         }
1794         *id = rec->cur_id = ++mdd->mdd_cl.mc_lastuser;
1795         mdd->mdd_cl.mc_users++;
1796         spin_unlock(&mdd->mdd_cl.mc_user_lock);
1797
1798         rec->cur_time = (__u32)ktime_get_real_seconds();
1799         if (OBD_FAIL_PRECHECK(OBD_FAIL_TIME_IN_CHLOG_USER)) {
1800                 rec->cur_time -= min(cfs_fail_val, rec->cur_time);
1801                 spin_lock(&mdd->mdd_cl.mc_user_lock);
1802                 mdd->mdd_cl.mc_mintime = rec->cur_time;
1803                 spin_unlock(&mdd->mdd_cl.mc_user_lock);
1804         }
1805
1806         spin_lock(&mdd->mdd_cl.mc_lock);
1807         rec->cur_endrec = mdd->mdd_cl.mc_index;
1808         spin_unlock(&mdd->mdd_cl.mc_lock);
1809
1810         if (mask) {
1811                 /* if user will use relative mask apply it on default one */
1812                 rec->cur_mask = CHANGELOG_DEFMASK;
1813                 rc = cfs_str2mask(mask, changelog_type2str, &rec->cur_mask,
1814                                   CHANGELOG_MINMASK, CHANGELOG_ALLMASK,
1815                                   CHANGELOG_DEFMASK);
1816                 if (rc)
1817                         GOTO(out_users, rc);
1818         } else if (mdd->mdd_cl.mc_proc_mask == CHANGELOG_MINMASK) {
1819                 /* a maskless users means default mask but only if server has
1820                  * no specific mask set
1821                  */
1822                 rec->cur_mask = CHANGELOG_DEFMASK;
1823         }
1824
1825         if (name && name[0]) {
1826                 rc = mdd_changelog_name_check(env, ctxt, mdd, name);
1827                 if (rc)
1828                         GOTO(out_users, rc);
1829                 strlcpy(rec->cur_name, name, sizeof(rec->cur_name));
1830         }
1831         mdd_chlg_username(rec, user_name, sizeof(user_name));
1832
1833         rc = llog_cat_add(env, ctxt->loc_handle, &rec->cur_hdr, NULL);
1834         if (rc) {
1835                 CWARN("%s: failed to register changelog user %s: rc = %d\n",
1836                       mdd2obd_dev(mdd)->obd_name, user_name, rc);
1837                 GOTO(out_users, rc);
1838         }
1839
1840         /* apply user mask finally */
1841         spin_lock(&mdd->mdd_cl.mc_user_lock);
1842         mdd->mdd_cl.mc_current_mask |= rec->cur_mask;
1843         spin_unlock(&mdd->mdd_cl.mc_user_lock);
1844
1845         CDEBUG(D_IOCTL, "%s: registered changelog user '%s', mask %#x\n",
1846                mdd2obd_dev(mdd)->obd_name, user_name, rec->cur_mask);
1847
1848         /* Assume we want it on since somebody registered */
1849         rc = mdd_changelog_on(env, mdd);
1850         if (rc)
1851                 /* record is added, so don't decrement users on error */
1852                 GOTO(out, rc);
1853 out_users:
1854         if (rc) {
1855                 spin_lock(&mdd->mdd_cl.mc_user_lock);
1856                 mdd->mdd_cl.mc_users--;
1857                 spin_unlock(&mdd->mdd_cl.mc_user_lock);
1858         }
1859 out:
1860         OBD_FREE_PTR(rec);
1861         llog_ctxt_put(ctxt);
1862         RETURN(rc);
1863 }
1864
1865 struct mdd_changelog_recalc_mask_data {
1866         struct mdd_device *mcrm_mdd;
1867         __u32              mcrm_mask;
1868 };
1869
1870 /**
1871  * changelog_recalc_mask callback
1872  *
1873  * Is is called per each registered user and calculates combined mask of
1874  * all registered users.
1875  */
1876 static int mdd_changelog_recalc_mask_cb(const struct lu_env *env,
1877                                        struct llog_handle *llh,
1878                                        struct llog_rec_hdr *hdr, void *data)
1879 {
1880         struct llog_changelog_user_rec2 *rec;
1881         struct mdd_changelog_recalc_mask_data *mcrm = data;
1882
1883         rec = container_of(hdr, typeof(*rec), cur_hdr);
1884         if (rec->cur_hdr.lrh_type == CHANGELOG_USER_REC2 && rec->cur_mask)
1885                 mcrm->mcrm_mask |= rec->cur_mask;
1886         else if (mcrm->mcrm_mdd->mdd_cl.mc_proc_mask == CHANGELOG_MINMASK)
1887                 mcrm->mcrm_mask |= CHANGELOG_DEFMASK;
1888
1889         return 0;
1890 }
1891
1892 int mdd_changelog_recalc_mask(const struct lu_env *env, struct mdd_device *mdd)
1893 {
1894         struct llog_ctxt *ctxt;
1895         struct mdd_changelog_recalc_mask_data mcrm = {
1896                 .mcrm_mdd = mdd,
1897                 .mcrm_mask = mdd->mdd_cl.mc_proc_mask,
1898         };
1899         int rc;
1900
1901         ENTRY;
1902
1903         ctxt = llog_get_context(mdd2obd_dev(mdd),
1904                                 LLOG_CHANGELOG_USER_ORIG_CTXT);
1905         if (!ctxt)
1906                 RETURN(-ENXIO);
1907
1908         if (!(ctxt->loc_handle->lgh_hdr->llh_flags & LLOG_F_IS_CAT))
1909                 GOTO(out, rc = -ENXIO);
1910
1911         rc = llog_cat_process(env, ctxt->loc_handle,
1912                               mdd_changelog_recalc_mask_cb, &mcrm, 0, 0);
1913         if (rc < 0)
1914                 CWARN("%s: failed user changelog processing: rc = %d\n",
1915                       mdd2obd_dev(mdd)->obd_name, rc);
1916
1917         spin_lock(&mdd->mdd_cl.mc_user_lock);
1918         CDEBUG(D_INFO, "%s: recalc changelog mask: %#x -> %#x\n",
1919                mdd2obd_dev(mdd)->obd_name, mdd->mdd_cl.mc_current_mask,
1920                mcrm.mcrm_mask);
1921         mdd->mdd_cl.mc_current_mask = mcrm.mcrm_mask;
1922         spin_unlock(&mdd->mdd_cl.mc_user_lock);
1923
1924         EXIT;
1925 out:
1926         llog_ctxt_put(ctxt);
1927
1928         return rc;
1929 }
1930
1931 struct mdd_changelog_user_purge {
1932         struct mdd_device *mcup_mdd;
1933         __u32 mcup_id;
1934         __u32 mcup_usercount;
1935         __u64 mcup_minrec;
1936         bool mcup_found;
1937         char mcup_name[CHANGELOG_USER_NAMELEN_FULL];
1938 };
1939
1940 /**
1941  * changelog_user_purge callback
1942  *
1943  * Is called once per user.
1944  *
1945  * Check to see the user requested is available from rec.
1946  * Truncate the changelog.
1947  * Keep track of the total number of users (calls).
1948  */
1949 static int mdd_changelog_user_purge_cb(const struct lu_env *env,
1950                                        struct llog_handle *llh,
1951                                        struct llog_rec_hdr *hdr, void *data)
1952 {
1953         struct llog_changelog_user_rec2 *rec;
1954         struct mdd_changelog_user_purge *mcup = data;
1955         struct llog_cookie cookie;
1956         int rc;
1957
1958         ENTRY;
1959
1960         if ((llh->lgh_hdr->llh_flags & LLOG_F_IS_PLAIN) == 0)
1961                 RETURN(-ENXIO);
1962
1963         rec = container_of(hdr, typeof(*rec), cur_hdr);
1964
1965         mcup->mcup_usercount++;
1966
1967         if (rec->cur_id != mcup->mcup_id) {
1968                 /* truncate to the lowest endrec that is not this user */
1969                 mcup->mcup_minrec = min(mcup->mcup_minrec, rec->cur_endrec);
1970                 RETURN(0);
1971         }
1972
1973         mdd_chlg_username(rec, mcup->mcup_name, sizeof(mcup->mcup_name));
1974
1975         /* Unregister this user */
1976         cookie.lgc_lgl = llh->lgh_id;
1977         cookie.lgc_index = hdr->lrh_index;
1978         rc = llog_cat_cancel_records(env, llh->u.phd.phd_cat_handle,
1979                                      1, &cookie);
1980         if (rc == 0) {
1981                 mcup->mcup_found = true;
1982                 mcup->mcup_usercount--;
1983                 spin_lock(&mcup->mcup_mdd->mdd_cl.mc_user_lock);
1984                 mcup->mcup_mdd->mdd_cl.mc_users--;
1985                 spin_unlock(&mcup->mcup_mdd->mdd_cl.mc_user_lock);
1986         }
1987
1988         RETURN(rc);
1989 }
1990
1991 int mdd_changelog_user_purge(const struct lu_env *env,
1992                              struct mdd_device *mdd, __u32 id)
1993 {
1994         struct mdd_changelog_user_purge mcup = {
1995                 .mcup_mdd = mdd,
1996                 .mcup_id = id,
1997                 .mcup_found = false,
1998                 .mcup_usercount = 0,
1999                 .mcup_minrec = ULLONG_MAX,
2000                 .mcup_name = { 0 },
2001         };
2002         struct llog_ctxt *ctxt;
2003         int rc;
2004
2005         ENTRY;
2006
2007         CDEBUG(D_IOCTL, "%s: Purge request: id=%u\n",
2008                mdd2obd_dev(mdd)->obd_name, id);
2009
2010         ctxt = llog_get_context(mdd2obd_dev(mdd),
2011                                 LLOG_CHANGELOG_USER_ORIG_CTXT);
2012         if (!ctxt)
2013                 RETURN(-ENXIO);
2014         if (!(ctxt->loc_handle->lgh_hdr->llh_flags & LLOG_F_IS_CAT))
2015                 GOTO(out, rc = -ENXIO);
2016
2017         rc = llog_cat_process(env, ctxt->loc_handle,
2018                               mdd_changelog_user_purge_cb, &mcup, 0, 0);
2019         if (rc) {
2020                 CWARN("%s: failed to purge changelog for user %s: rc = %d\n",
2021                       mdd2obd_dev(mdd)->obd_name, mcup.mcup_name, rc);
2022                 GOTO(out, rc);
2023         }
2024
2025         OBD_FAIL_TIMEOUT(OBD_FAIL_LLOG_PURGE_DELAY, cfs_fail_val);
2026         if (mcup.mcup_usercount == 0) {
2027                 spin_lock(&mdd->mdd_cl.mc_user_lock);
2028                 if (mdd->mdd_cl.mc_users == 0) {
2029                         /* No more users; turn changelogs off */
2030                         CDEBUG(D_IOCTL, "turning off changelogs\n");
2031                         rc = mdd_changelog_off(env, mdd);
2032                 }
2033                 spin_unlock(&mdd->mdd_cl.mc_user_lock);
2034         }
2035
2036         if (mcup.mcup_found) {
2037                 CDEBUG(D_IOCTL,
2038                        "%s: Purge changelog entries for user %s record=%llu\n",
2039                        mdd2obd_dev(mdd)->obd_name,
2040                        mcup.mcup_name, mcup.mcup_minrec);
2041                 rc = mdd_changelog_llog_cancel(env, mdd, mcup.mcup_minrec);
2042         } else {
2043                 CWARN("%s: No changelog for user id %u: rc = %d\n",
2044                       mdd2obd_dev(mdd)->obd_name, id, rc);
2045                 GOTO(out, rc = -ENOENT);
2046         }
2047
2048         CFS_RACE(CFS_FAIL_CHLOG_USER_REG_UNREG_RACE);
2049
2050         EXIT;
2051 out:
2052         llog_ctxt_put(ctxt);
2053
2054         return rc;
2055 }
2056
2057 struct mdd_changelog_user_clear {
2058         __u64 mcuc_endrec;
2059         __u64 mcuc_minrec;
2060         __u32 mcuc_mintime;
2061         __u32 mcuc_id;
2062         bool mcuc_flush;
2063         struct mdd_device *mcuc_mdd;
2064         char mcuc_name[CHANGELOG_USER_NAMELEN_FULL];
2065 };
2066
2067 /**
2068  * changelog_clear callback
2069  *
2070  * Is called once per user.
2071  *
2072  * Check to see the user requested is available from rec.
2073  * Check the oldest (smallest) record for boundary conditions.
2074  * Truncate the changelog.
2075  */
2076 static int mdd_changelog_clear_cb(const struct lu_env *env,
2077                                   struct llog_handle *llh,
2078                                   struct llog_rec_hdr *hdr,
2079                                   void *data)
2080 {
2081         struct llog_changelog_user_rec2 *rec;
2082         struct mdd_changelog_user_clear *mcuc = data;
2083         struct mdd_device *mdd = mcuc->mcuc_mdd;
2084         int rc;
2085
2086         ENTRY;
2087
2088         if ((llh->lgh_hdr->llh_flags & LLOG_F_IS_PLAIN) == 0)
2089                 RETURN(-ENXIO);
2090
2091         rec = container_of(hdr, typeof(*rec), cur_hdr);
2092         /* Does the changelog id match the requested id? */
2093         if (rec->cur_id != mcuc->mcuc_id) {
2094                 mcuc->mcuc_minrec = min(mcuc->mcuc_minrec, rec->cur_endrec);
2095                 mcuc->mcuc_mintime = min(mcuc->mcuc_mintime, rec->cur_time);
2096                 RETURN(0);
2097         }
2098
2099         mdd_chlg_username(rec, mcuc->mcuc_name, sizeof(mcuc->mcuc_name));
2100         /* cur_endrec is the oldest purgeable record, make sure we're newer */
2101         if (rec->cur_endrec > mcuc->mcuc_endrec) {
2102                 rc = -EINVAL;
2103                 CDEBUG(D_IOCTL,
2104                        "%s: request %llu < endrec %llu for user %s: rc = %d\n",
2105                        mdd2obd_dev(mdd)->obd_name, mcuc->mcuc_endrec,
2106                        rec->cur_endrec, mcuc->mcuc_name, rc);
2107                 RETURN(rc);
2108         }
2109
2110         /*
2111          * Flag that we've met all the range and user checks.
2112          * We now know the record to flush.
2113          */
2114         mcuc->mcuc_flush = true;
2115
2116         rec->cur_endrec = mcuc->mcuc_endrec;
2117         rec->cur_time = (__u32)ktime_get_real_seconds();
2118
2119         CDEBUG(D_IOCTL, "%s: update changelog user %s endrec = %llu\n",
2120                mdd2obd_dev(mdd)->obd_name, mcuc->mcuc_name, rec->cur_endrec);
2121
2122         /* Update the endrec */
2123         rc = llog_write(env, llh, hdr, hdr->lrh_index);
2124
2125         RETURN(rc);
2126 }
2127
2128 /**
2129  * Clear a changelog up to entry specified by endrec for user id.
2130  */
2131 static int mdd_changelog_clear(const struct lu_env *env,
2132                                struct mdd_device *mdd, __u32 id,
2133                                __u64 endrec)
2134 {
2135         struct mdd_changelog_user_clear mcuc = {
2136                 .mcuc_id = id,
2137                 .mcuc_minrec = endrec,
2138                 .mcuc_flush = false,
2139                 .mcuc_mdd = mdd,
2140                 .mcuc_mintime = ktime_get_real_seconds(),
2141                 .mcuc_name = { 0 },
2142         };
2143         struct llog_ctxt *ctxt;
2144         __u64 start_rec;
2145         int rc;
2146
2147         ENTRY;
2148
2149         CDEBUG(D_IOCTL, "%s: Purge request: id=%u, endrec=%llu\n",
2150                mdd2obd_dev(mdd)->obd_name, id, endrec);
2151         /* start_rec is the newest (largest value) entry in the changelogs*/
2152         spin_lock(&mdd->mdd_cl.mc_lock);
2153         start_rec = mdd->mdd_cl.mc_index;
2154         spin_unlock(&mdd->mdd_cl.mc_lock);
2155
2156         if (start_rec < endrec) {
2157                 CDEBUG(D_IOCTL, "%s: Could not clear changelog, requested "\
2158                        "address out of range\n", mdd2obd_dev(mdd)->obd_name);
2159                 RETURN(-EINVAL);
2160         }
2161
2162         if (endrec == 0) {
2163                 mcuc.mcuc_endrec = start_rec;
2164                 mcuc.mcuc_minrec = ULLONG_MAX;
2165         } else {
2166                 mcuc.mcuc_endrec = endrec;
2167         }
2168
2169         ctxt = llog_get_context(mdd2obd_dev(mdd),
2170                                 LLOG_CHANGELOG_USER_ORIG_CTXT);
2171         if (!ctxt)
2172                 RETURN(-ENXIO);
2173
2174         if (!(ctxt->loc_handle->lgh_hdr->llh_flags & LLOG_F_IS_CAT))
2175                 GOTO(out, rc = -ENXIO);
2176
2177         rc = llog_cat_process(env, ctxt->loc_handle, mdd_changelog_clear_cb,
2178                               &mcuc, 0, 0);
2179         if (rc == -EINVAL) {
2180                 CDEBUG(D_IOCTL, "%s: no changelog recnum <= %llu to clear\n",
2181                        mdd2obd_dev(mdd)->obd_name, (unsigned long long)endrec);
2182                 GOTO(out, rc);
2183         }
2184
2185         if (rc < 0) {
2186                 CWARN("%s: can't clear the changelog for user %s: rc = %d\n",
2187                       mdd2obd_dev(mdd)->obd_name, mcuc.mcuc_name, rc);
2188                 GOTO(out, rc);
2189         }
2190
2191         if (!mcuc.mcuc_flush) {
2192                 CDEBUG(D_IOCTL, "%s: no entry for user %d\n",
2193                        mdd2obd_dev(mdd)->obd_name, id);
2194                 GOTO(out, rc = -ENOENT);
2195         }
2196
2197         CDEBUG(D_IOCTL, "%s: purge changelog user %s entries up to %llu\n",
2198                mdd2obd_dev(mdd)->obd_name, mcuc.mcuc_name, mcuc.mcuc_minrec);
2199
2200         rc = mdd_changelog_llog_cancel(env, mdd, mcuc.mcuc_minrec);
2201         if (rc)
2202                 GOTO(out, rc);
2203
2204         spin_lock(&mdd->mdd_cl.mc_user_lock);
2205         mdd->mdd_cl.mc_minrec = mcuc.mcuc_minrec;
2206         mdd->mdd_cl.mc_mintime = mcuc.mcuc_mintime;
2207         spin_unlock(&mdd->mdd_cl.mc_user_lock);
2208
2209         EXIT;
2210 out:
2211         llog_ctxt_put(ctxt);
2212
2213         return rc;
2214 }
2215
2216 static int mdd_changelog_user_deregister(const struct lu_env *env,
2217                                          struct mdd_device *mdd, int *id,
2218                                          const char *name)
2219 {
2220         struct llog_ctxt *ctxt;
2221         struct mdd_changelog_name_check_data mcnc = {
2222                 .mcnc_name = name,
2223                 .mcnc_id = 0,
2224         };
2225         int rc;
2226
2227         ENTRY;
2228
2229         if (name) {
2230                 ctxt = llog_get_context(mdd2obd_dev(mdd),
2231                                         LLOG_CHANGELOG_USER_ORIG_CTXT);
2232                 if (!ctxt)
2233                         RETURN(-ENXIO);
2234
2235                 rc = llog_cat_process(env, ctxt->loc_handle,
2236                               mdd_changelog_name_check_cb, &mcnc, 0, 0);
2237                 llog_ctxt_put(ctxt);
2238
2239                 if (rc != -EEXIST) {
2240                         CDEBUG(D_IOCTL, "%s: no entry for username %s\n",
2241                                mdd2obd_dev(mdd)->obd_name, name);
2242                         RETURN(-ENOENT);
2243                 }
2244                 *id = mcnc.mcnc_id;
2245         }
2246
2247         /* explicitly clear changelog first, to protect from crash in
2248          * the middle of purge that would lead to unregistered consumer
2249          * but pending changelog entries
2250          */
2251         rc = mdd_changelog_clear(env, mdd, *id, 0);
2252         if (!rc)
2253                 rc = mdd_changelog_user_purge(env, mdd, *id);
2254
2255         /* recalc changelog current mask */
2256         mdd_changelog_recalc_mask(env, mdd);
2257
2258         RETURN(rc);
2259 }
2260
2261 /** mdd_iocontrol
2262  * May be called remotely from mdt_iocontrol_handle or locally from
2263  * mdt_iocontrol. Data may be freeform - remote handling doesn't enforce
2264  * an obd_ioctl_data format (but local ioctl handler does).
2265  * \param cmd - ioc
2266  * \param len - data len
2267  * \param karg - ioctl data, in kernel space
2268  */
2269 static int mdd_iocontrol(const struct lu_env *env, struct md_device *m,
2270                          unsigned int cmd, int len, void *karg)
2271 {
2272         struct mdd_device *mdd = lu2mdd_dev(&m->md_lu_dev);
2273         struct obd_device *obd = mdd2obd_dev(mdd);
2274         struct obd_ioctl_data *data;
2275         int rc = -EINVAL;
2276
2277         ENTRY;
2278         CDEBUG(D_IOCTL, "%s: cmd=%x len=%u karg=%pK\n",
2279                obd->obd_name, cmd, len, karg);
2280         if (unlikely(karg == NULL))
2281                 RETURN(OBD_IOC_ERROR(obd->obd_name, cmd, "karg=NULL", rc));
2282         data = karg;
2283
2284         /* Doesn't use obd_ioctl_data */
2285         switch (cmd) {
2286         case OBD_IOC_CHANGELOG_CLEAR: {
2287                 struct changelog_setinfo *cs = karg;
2288
2289                 if (unlikely(!barrier_entry(mdd->mdd_bottom)))
2290                         RETURN(-EINPROGRESS);
2291
2292                 rc = mdd_changelog_clear(env, mdd, cs->cs_id, cs->cs_recno);
2293                 barrier_exit(mdd->mdd_bottom);
2294                 RETURN(rc);
2295         }
2296         case OBD_IOC_START_LFSCK: {
2297                 rc = lfsck_start(env, mdd->mdd_bottom, karg);
2298                 RETURN(rc);
2299         }
2300         case OBD_IOC_STOP_LFSCK: {
2301                 rc = lfsck_stop(env, mdd->mdd_bottom, karg);
2302                 RETURN(rc);
2303         }
2304         case OBD_IOC_QUERY_LFSCK: {
2305                 rc = lfsck_query(env, mdd->mdd_bottom, NULL, NULL, karg);
2306                 RETURN(rc);
2307         }
2308         case OBD_IOC_LLOG_PRINT:
2309         case OBD_IOC_LLOG_CANCEL:
2310                 rc = obd_iocontrol(cmd, mdd->mdd_child_exp, len, karg, NULL);
2311                 RETURN(rc);
2312         }
2313
2314         /* Below ioctls use obd_ioctl_data */
2315         if (data->ioc_version != OBD_IOCTL_VERSION) {
2316                 CERROR("%s: iocontrol from '%s' bad magic %x != %x: rc = %d\n",
2317                        obd->obd_name, current->comm,
2318                        data->ioc_version, OBD_IOCTL_VERSION, rc);
2319                 RETURN(rc);
2320         }
2321
2322         switch (cmd) {
2323         case OBD_IOC_CHANGELOG_REG:
2324                 if (unlikely(!barrier_entry(mdd->mdd_bottom)))
2325                         RETURN(-EINPROGRESS);
2326
2327                 rc = mdd_changelog_user_register(env, mdd, &data->ioc_u32_1,
2328                                                  data->ioc_inlbuf1,
2329                                                  data->ioc_inlbuf2);
2330                 barrier_exit(mdd->mdd_bottom);
2331                 break;
2332         case OBD_IOC_CHANGELOG_DEREG:
2333                 if (unlikely(!barrier_entry(mdd->mdd_bottom)))
2334                         RETURN(-EINPROGRESS);
2335
2336                 rc = mdd_changelog_user_deregister(env, mdd, &data->ioc_u32_1,
2337                                                    data->ioc_inlbuf1);
2338
2339                 barrier_exit(mdd->mdd_bottom);
2340                 break;
2341         default:
2342                 rc = OBD_IOC_ERROR(obd->obd_name, cmd, "unrecognized", -ENOTTY);
2343                 break;
2344         }
2345
2346         RETURN(rc);
2347 }
2348
2349 /* type constructor/destructor: mdd_type_init, mdd_type_fini */
2350 LU_TYPE_INIT_FINI(mdd, &mdd_thread_key);
2351
2352 static const struct md_device_operations mdd_ops = {
2353         .mdo_statfs         = mdd_statfs,
2354         .mdo_root_get       = mdd_root_get,
2355         .mdo_llog_ctxt_get  = mdd_llog_ctxt_get,
2356         .mdo_iocontrol      = mdd_iocontrol,
2357         .mdo_dtconf_get     = mdd_dtconf_get,
2358 };
2359
2360 static const struct lu_device_type_operations mdd_device_type_ops = {
2361         .ldto_init              = mdd_type_init,
2362         .ldto_fini              = mdd_type_fini,
2363
2364         .ldto_start             = mdd_type_start,
2365         .ldto_stop              = mdd_type_stop,
2366
2367         .ldto_device_alloc      = mdd_device_alloc,
2368         .ldto_device_free       = mdd_device_free,
2369
2370         .ldto_device_fini       = mdd_device_fini
2371 };
2372
2373 static struct lu_device_type mdd_device_type = {
2374         .ldt_tags     = LU_DEVICE_MD,
2375         .ldt_name     = LUSTRE_MDD_NAME,
2376         .ldt_ops      = &mdd_device_type_ops,
2377         .ldt_ctx_tags = LCT_MD_THREAD
2378 };
2379
2380 /* context key constructor: mdd_key_init */
2381 LU_KEY_INIT(mdd, struct mdd_thread_info);
2382
2383 static void mdd_key_fini(const struct lu_context *ctx,
2384                          struct lu_context_key *key, void *data)
2385 {
2386         struct mdd_thread_info *info = data;
2387
2388         lu_buf_free(&info->mdi_big_buf);
2389         lu_buf_free(&info->mdi_link_buf);
2390         lu_buf_free(&info->mdi_xattr_buf);
2391         lu_buf_free(&info->mdi_chlg_buf);
2392
2393         OBD_FREE_PTR(info);
2394 }
2395
2396 /* context key: mdd_thread_key */
2397 LU_CONTEXT_KEY_DEFINE(mdd, LCT_MD_THREAD);
2398
2399 int mdd_generic_thread_start(struct mdd_generic_thread *thread,
2400                              int (*func)(void *), void *data, char *name)
2401 {
2402         struct task_struct      *task;
2403
2404         LASSERT(thread->mgt_init == false);
2405         init_completion(&thread->mgt_started);
2406         init_completion(&thread->mgt_finished);
2407         thread->mgt_data = data;
2408         thread->mgt_abort = false;
2409         thread->mgt_init = true;
2410
2411         task = kthread_run(func, thread, name);
2412         if (IS_ERR(task)) {
2413                 complete(&thread->mgt_finished);
2414                 return PTR_ERR(task);
2415         }
2416         wait_for_completion(&thread->mgt_started);
2417         return 0;
2418 }
2419
2420 void mdd_generic_thread_stop(struct mdd_generic_thread *thread)
2421 {
2422         if (thread->mgt_init == true) {
2423                 thread->mgt_abort = true;
2424                 wait_for_completion(&thread->mgt_finished);
2425         }
2426 }
2427
2428 static int __init mdd_init(void)
2429 {
2430         int rc;
2431
2432         rc = lu_kmem_init(mdd_caches);
2433         if (rc)
2434                 return rc;
2435
2436         changelog_orig_logops = llog_common_cat_ops;
2437         changelog_orig_logops.lop_write_rec = mdd_changelog_write_rec;
2438
2439         rc = class_register_type(&mdd_obd_device_ops, NULL, false,
2440                                  LUSTRE_MDD_NAME, &mdd_device_type);
2441         if (rc)
2442                 lu_kmem_fini(mdd_caches);
2443         return rc;
2444 }
2445
2446 static void __exit mdd_exit(void)
2447 {
2448         class_unregister_type(LUSTRE_MDD_NAME);
2449         lu_kmem_fini(mdd_caches);
2450 }
2451
2452 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
2453 MODULE_DESCRIPTION("Lustre Meta-data Device Driver ("LUSTRE_MDD_NAME")");
2454 MODULE_VERSION(LUSTRE_VERSION_STRING);
2455 MODULE_LICENSE("GPL");
2456
2457 module_init(mdd_init);
2458 module_exit(mdd_exit);