Whamcloud - gitweb
LU-16747 llapi: fix race in get_root_path_slow()
[fs/lustre-release.git] / lustre / lod / lod_dev.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,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright  2009 Sun Microsystems, Inc. All rights reserved
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/lod/lod_dev.c
32  *
33  * Lustre Logical Object Device
34  *
35  * Author: Alex Zhuravlev <alexey.zhuravlev@intel.com>
36  * Author: Mikhail Pershin <mike.pershin@intel.com>
37  */
38 /**
39  * The Logical Object Device (LOD) layer manages access to striped
40  * objects (both regular files and directories). It implements the DT
41  * device and object APIs and is responsible for creating, storing,
42  * and loading striping information as an extended attribute of the
43  * underlying OSD object. LOD is the server side analog of the LOV and
44  * LMV layers on the client side.
45  *
46  * Metadata LU object stack (layers of the same compound LU object,
47  * all have the same FID):
48  *
49  *        MDT
50  *         |      MD API
51  *        MDD
52  *         |      DT API
53  *        LOD
54  *       /   \    DT API
55  *     OSD   OSP
56  *
57  * During LOD object initialization the localness or remoteness of the
58  * object FID dictates the choice between OSD and OSP.
59  *
60  * An LOD object (file or directory) with N stripes (each has a
61  * different FID):
62  *
63  *          LOD
64  *           |
65  *   +---+---+---+...+
66  *   |   |   |   |   |
67  *   S0  S1  S2  S3  S(N-1)  OS[DP] objects, seen as DT objects by LOD
68  *
69  * When upper layers must access an object's stripes (which are
70  * themselves OST or MDT LU objects) LOD finds these objects by their
71  * FIDs and stores them as an array of DT object pointers on the
72  * object. Declarations and operations on LOD objects are received by
73  * LOD (as DT object operations) and performed on the underlying
74  * OS[DP] object and (as needed) on the stripes. From the perspective
75  * of LOD, a stripe-less file (created by mknod() or open with
76  * O_LOV_DELAY_CREATE) is an object which does not yet have stripes,
77  * while a non-striped directory (created by mkdir()) is an object
78  * which will never have stripes.
79  *
80  * The LOD layer also implements a small subset of the OBD device API
81  * to support MDT stack initialization and finalization (an MDD device
82  * connects and disconnects itself to and from the underlying LOD
83  * device), and pool management. In turn LOD uses the OBD device API
84  * to connect it self to the underlying OSD, and to connect itself to
85  * OSP devices representing the MDTs and OSTs that bear the stripes of
86  * its objects.
87  */
88
89 #define DEBUG_SUBSYSTEM S_MDS
90
91 #include <linux/kthread.h>
92 #include <obd_class.h>
93 #include <md_object.h>
94 #include <lustre_fid.h>
95 #include <uapi/linux/lustre/lustre_param.h>
96 #include <uapi/linux/lustre/lustre_ioctl.h>
97 #include <lustre_update.h>
98 #include <lustre_log.h>
99 #include <lustre_lmv.h>
100 #include <llog_swab.h>
101
102 #include "lod_internal.h"
103
104 static const char lod_update_log_name[] = "update_log";
105 static const char lod_update_log_dir_name[] = "update_log_dir";
106
107 /*
108  * Lookup target by FID.
109  *
110  * Lookup MDT/OST target index by FID. Type of the target can be
111  * specific or any.
112  *
113  * \param[in] env               LU environment provided by the caller
114  * \param[in] lod               lod device
115  * \param[in] fid               FID
116  * \param[out] tgt              result target index
117  * \param[in] type              expected type of the target:
118  *                              LU_SEQ_RANGE_{MDT,OST,ANY}
119  *
120  * \retval 0                    on success
121  * \retval negative             negated errno on error
122  **/
123 int lod_fld_lookup(const struct lu_env *env, struct lod_device *lod,
124                    const struct lu_fid *fid, u32 *tgt, int *type)
125 {
126         struct lu_seq_range range = { 0 };
127         struct lu_server_fld *server_fld;
128         int rc;
129
130         ENTRY;
131
132         if (!fid_is_sane(fid)) {
133                 CERROR("%s: invalid FID "DFID"\n", lod2obd(lod)->obd_name,
134                        PFID(fid));
135                 RETURN(-EIO);
136         }
137
138         if (fid_is_idif(fid)) {
139                 *tgt = fid_idif_ost_idx(fid);
140                 *type = LU_SEQ_RANGE_OST;
141                 RETURN(0);
142         }
143
144         if (fid_is_update_log(fid) || fid_is_update_log_dir(fid)) {
145                 *tgt = fid_oid(fid);
146                 *type = LU_SEQ_RANGE_MDT;
147                 RETURN(0);
148         }
149
150         if (!lod->lod_initialized || (!fid_seq_in_fldb(fid_seq(fid)))) {
151                 LASSERT(lu_site2seq(lod2lu_dev(lod)->ld_site) != NULL);
152
153                 *tgt = lu_site2seq(lod2lu_dev(lod)->ld_site)->ss_node_id;
154                 *type = LU_SEQ_RANGE_MDT;
155                 RETURN(0);
156         }
157
158         server_fld = lu_site2seq(lod2lu_dev(lod)->ld_site)->ss_server_fld;
159         if (!server_fld)
160                 RETURN(-EIO);
161
162         fld_range_set_type(&range, *type);
163         rc = fld_server_lookup(env, server_fld, fid_seq(fid), &range);
164         if (rc != 0)
165                 RETURN(rc);
166
167         *tgt = range.lsr_index;
168         *type = range.lsr_flags;
169
170         CDEBUG(D_INFO, "%s: got tgt %x for sequence: %#llx\n",
171                lod2obd(lod)->obd_name, *tgt, fid_seq(fid));
172
173         RETURN(0);
174 }
175
176 /* Slab for OSD object allocation */
177 struct kmem_cache *lod_object_kmem;
178
179 /* Slab for dt_txn_callback */
180 struct kmem_cache *lod_txn_callback_kmem;
181 static struct lu_kmem_descr lod_caches[] = {
182         {
183                 .ckd_cache = &lod_object_kmem,
184                 .ckd_name  = "lod_obj",
185                 .ckd_size  = sizeof(struct lod_object)
186         },
187         {
188                 .ckd_cache = &lod_txn_callback_kmem,
189                 .ckd_name  = "lod_txn_callback",
190                 .ckd_size  = sizeof(struct dt_txn_callback)
191         },
192         {
193                 .ckd_cache = NULL
194         }
195 };
196
197 static struct lu_device *lod_device_fini(const struct lu_env *env,
198                                          struct lu_device *d);
199
200 /**
201  * Implementation of lu_device_operations::ldo_object_alloc() for LOD
202  *
203  * Allocates and initializes LOD's slice in the given object.
204  *
205  * see include/lu_object.h for the details.
206  */
207 static struct lu_object *lod_object_alloc(const struct lu_env *env,
208                                           const struct lu_object_header *hdr,
209                                           struct lu_device *dev)
210 {
211         struct lod_object *lod_obj;
212         struct lu_object *lu_obj;
213
214         ENTRY;
215
216         OBD_SLAB_ALLOC_PTR_GFP(lod_obj, lod_object_kmem, GFP_NOFS);
217         if (!lod_obj)
218                 RETURN(ERR_PTR(-ENOMEM));
219
220         mutex_init(&lod_obj->ldo_layout_mutex);
221         lu_obj = lod2lu_obj(lod_obj);
222         dt_object_init(&lod_obj->ldo_obj, NULL, dev);
223         lod_obj->ldo_obj.do_ops = &lod_obj_ops;
224         lu_obj->lo_ops = &lod_lu_obj_ops;
225
226         RETURN(lu_obj);
227 }
228
229 /**
230  * Process the config log for all sub device.
231  *
232  * The function goes through all the targets in the given table
233  * and apply given configuration command on to the targets.
234  * Used to cleanup the targets at unmount.
235  *
236  * \param[in] env               LU environment provided by the caller
237  * \param[in] lod               lod device
238  * \param[in] ltd               target's table to go through
239  * \param[in] lcfg              configuration command to apply
240  *
241  * \retval 0                    on success
242  * \retval negative             negated errno on error
243  **/
244 static int lod_sub_process_config(const struct lu_env *env,
245                                  struct lod_device *lod,
246                                  struct lod_tgt_descs *ltd,
247                                  struct lustre_cfg *lcfg)
248 {
249         struct lu_device *next;
250         struct lu_tgt_desc *tgt;
251         int rc = 0;
252
253         lod_getref(ltd);
254         ltd_foreach_tgt(ltd, tgt) {
255                 int rc1;
256
257                 LASSERT(tgt && tgt->ltd_tgt);
258                 next = &tgt->ltd_tgt->dd_lu_dev;
259                 rc1 = next->ld_ops->ldo_process_config(env, next, lcfg);
260                 if (rc1) {
261                         CERROR("%s: error cleaning up LOD index %u: cmd %#x : rc = %d\n",
262                                lod2obd(lod)->obd_name, tgt->ltd_index,
263                                lcfg->lcfg_command, rc1);
264                         rc = rc1;
265                 }
266         }
267         lod_putref(lod, ltd);
268         return rc;
269 }
270
271 struct lod_recovery_data {
272         struct lod_device       *lrd_lod;
273         struct lod_tgt_desc     *lrd_ltd;
274         struct task_struct      **lrd_task;
275         u32                     lrd_idx;
276         struct lu_env           lrd_env;
277         struct completion       *lrd_started;
278 };
279
280 /**
281  * process update recovery record
282  *
283  * Add the update recovery recode to the update recovery list in
284  * lod_recovery_data. Then the recovery thread (target_recovery_thread)
285  * will redo these updates.
286  *
287  * \param[in]env        execution environment
288  * \param[in]llh        log handle of update record
289  * \param[in]rec        update record to be replayed
290  * \param[in]data       update recovery data which holds the necessary
291  *                      arguments for recovery (see struct lod_recovery_data)
292  *
293  * \retval              0 if the record is processed successfully.
294  * \retval              negative errno if the record processing fails.
295  */
296 static int lod_process_recovery_updates(const struct lu_env *env,
297                                         struct llog_handle *llh,
298                                         struct llog_rec_hdr *rec,
299                                         void *data)
300 {
301         struct lod_recovery_data *lrd = data;
302         struct llog_cookie *cookie = &lod_env_info(env)->lti_cookie;
303         struct lu_target *lut;
304         u32 index = 0;
305
306         ENTRY;
307
308         if (!lrd->lrd_ltd) {
309                 int rc;
310
311                 rc = lodname2mdt_index(lod2obd(lrd->lrd_lod)->obd_name, &index);
312                 if (rc != 0)
313                         return rc;
314         } else {
315                 index = lrd->lrd_ltd->ltd_index;
316         }
317
318         if (rec->lrh_len !=
319                 llog_update_record_size((struct llog_update_record *)rec)) {
320                 CERROR("%s: broken update record! index %u "DFID".%u: rc = %d\n",
321                        lod2obd(lrd->lrd_lod)->obd_name, index,
322                        PLOGID(&llh->lgh_id), rec->lrh_index, -EIO);
323                 return -EINVAL;
324         }
325
326         cookie->lgc_lgl = llh->lgh_id;
327         cookie->lgc_index = rec->lrh_index;
328         cookie->lgc_subsys = LLOG_UPDATELOG_ORIG_CTXT;
329
330         CDEBUG(D_HA, "%s: process recovery updates "DFID".%u\n",
331                lod2obd(lrd->lrd_lod)->obd_name,
332                PLOGID(&llh->lgh_id), rec->lrh_index);
333         lut = lod2lu_dev(lrd->lrd_lod)->ld_site->ls_tgt;
334
335         if (obd_mdt_recovery_abort(lut->lut_obd))
336                 return -ESHUTDOWN;
337
338         return insert_update_records_to_replay_list(lut->lut_tdtd,
339                                         (struct llog_update_record *)rec,
340                                         cookie, index);
341 }
342
343 /* retain old catalog, create new catalog and update catlist */
344 static int lod_sub_recreate_llog(const struct lu_env *env,
345                                  struct lod_device *lod, struct dt_device *dt,
346                                  int index)
347 {
348         struct lod_thread_info *lti = lod_env_info(env);
349         struct llog_ctxt *ctxt;
350         struct llog_handle *lgh;
351         struct llog_catid *cid = &lti->lti_cid;
352         struct lu_fid *fid = &lti->lti_fid;
353         struct obd_device *obd;
354         int rc;
355
356         ENTRY;
357         lu_update_log_fid(fid, index);
358         rc = lodname2mdt_index(lod2obd(lod)->obd_name, (__u32 *)&index);
359         if (rc < 0)
360                 RETURN(rc);
361
362         rc = llog_osd_get_cat_list(env, dt, index, 1, NULL, fid);
363         if (rc < 0) {
364                 CERROR("%s: can't access update_log: rc = %d\n",
365                        lod2obd(lod)->obd_name, rc);
366                 RETURN(rc);
367         }
368
369         obd = dt->dd_lu_dev.ld_obd;
370         ctxt = llog_get_context(obd, LLOG_UPDATELOG_ORIG_CTXT);
371         LASSERT(ctxt != NULL);
372         if (ctxt->loc_handle) {
373                 /* retain old catalog */
374                 llog_retain(env, ctxt->loc_handle);
375                 llog_cat_close(env, ctxt->loc_handle);
376                 LASSERT(!ctxt->loc_handle);
377         }
378
379         ctxt->loc_flags |= LLOG_CTXT_FLAG_NORMAL_FID;
380         ctxt->loc_chunk_size = LLOG_MIN_CHUNK_SIZE * 4;
381         rc = llog_open_create(env, ctxt, &lgh, NULL, NULL);
382         if (rc < 0)
383                 GOTO(out_put, rc);
384
385         LASSERT(lgh != NULL);
386         rc = llog_init_handle(env, lgh, LLOG_F_IS_CAT, NULL);
387         if (rc != 0)
388                 GOTO(out_close, rc);
389
390         cid->lci_logid = lgh->lgh_id;
391         rc = llog_osd_put_cat_list(env, dt, index, 1, cid, fid);
392         if (rc != 0)
393                 GOTO(out_close, rc);
394
395         ctxt->loc_handle = lgh;
396
397         CDEBUG(D_INFO, "%s: recreate catalog "DFID"\n",
398                obd->obd_name, PLOGID(&cid->lci_logid));
399 out_close:
400         if (rc)
401                 llog_cat_close(env, lgh);
402 out_put:
403         llog_ctxt_put(ctxt);
404         RETURN(rc);
405 }
406
407 /* retain update catalog and llogs, and create a new catalog */
408 static int lod_sub_cancel_llog(const struct lu_env *env,
409                                struct lod_device *lod, struct dt_device *dt,
410                                int index)
411 {
412         struct llog_ctxt *ctxt;
413         int rc = 0;
414
415         ctxt = llog_get_context(dt->dd_lu_dev.ld_obd,
416                                 LLOG_UPDATELOG_ORIG_CTXT);
417         if (!ctxt)
418                 return 0;
419
420         if (ctxt->loc_handle) {
421                 LCONSOLE(D_INFO, "%s: cancel update llog "DFID"\n",
422                          dt->dd_lu_dev.ld_obd->obd_name,
423                          PLOGID(&ctxt->loc_handle->lgh_id));
424                 /* set retention on logs to simplify reclamation */
425                 llog_process_or_fork(env, ctxt->loc_handle, llog_cat_retain_cb,
426                                      NULL, NULL, false);
427                 /* retain old catalog and create a new one */
428                 lod_sub_recreate_llog(env, lod, dt, index);
429         }
430         llog_ctxt_put(ctxt);
431         return rc;
432 }
433
434 /**
435  * recovery thread for update log
436  *
437  * Start recovery thread and prepare the sub llog, then it will retrieve
438  * the update records from the correpondent MDT and do recovery.
439  *
440  * \param[in] arg       pointer to the recovery data
441  *
442  * \retval              0 if recovery succeeds
443  * \retval              negative errno if recovery failed.
444  */
445 static int lod_sub_recovery_thread(void *arg)
446 {
447         struct lod_recovery_data *lrd = arg;
448         struct lod_device *lod = lrd->lrd_lod;
449         struct dt_device *dt;
450         struct llog_ctxt *ctxt = NULL;
451         struct lu_env *env = &lrd->lrd_env;
452         struct lu_target *lut;
453         struct lu_tgt_desc *mdt = NULL;
454         struct lu_device *top_device;
455         time64_t start;
456         int retries = 0;
457         int rc;
458
459         ENTRY;
460
461         lut = lod2lu_dev(lod)->ld_site->ls_tgt;
462         atomic_inc(&lut->lut_tdtd->tdtd_recovery_threads_count);
463         if (!lrd->lrd_ltd)
464                 dt = lod->lod_child;
465         else
466                 dt = lrd->lrd_ltd->ltd_tgt;
467
468         start = ktime_get_real_seconds();
469         complete(lrd->lrd_started);
470
471 again:
472
473         if (unlikely(CFS_FAIL_PRECHECK(OBD_FAIL_TGT_RECOVERY_CONNECT)) &&
474             lrd->lrd_ltd) {
475                 CFS_FAIL_TIMEOUT(OBD_FAIL_TGT_RECOVERY_CONNECT, cfs_fail_val);
476                 rc = -EIO;
477         } else {
478                 rc = lod_sub_prep_llog(env, lod, dt, lrd->lrd_idx);
479         }
480
481         if (!rc && !lod->lod_child->dd_rdonly) {
482                 /* Process the recovery record */
483                 ctxt = llog_get_context(dt->dd_lu_dev.ld_obd,
484                                         LLOG_UPDATELOG_ORIG_CTXT);
485                 LASSERT(ctxt != NULL);
486                 LASSERT(ctxt->loc_handle != NULL);
487
488                 rc = llog_cat_process(env, ctxt->loc_handle,
489                                       lod_process_recovery_updates, lrd, 0, 0);
490         }
491
492         top_device = lod->lod_dt_dev.dd_lu_dev.ld_site->ls_top_dev;
493         if (rc < 0 && dt != lod->lod_child &&
494             !obd_mdt_recovery_abort(top_device->ld_obd)) {
495                 if (rc == -EBADR) {
496                         /* remote update llog is shorter than expected from
497                          * local header. Cached copy could be de-synced during
498                          * recovery, trust remote llog data
499                          */
500                         CDEBUG(D_HA, "%s update log data de-sync\n",
501                                dt->dd_lu_dev.ld_obd->obd_name);
502                         rc = 0;
503                 } else if (rc == -ETIMEDOUT || rc == -EAGAIN || rc == -EIO) {
504                         /*
505                          * the remote target might failover at the same time,
506                          * let's retry here
507                          */
508                         if (ctxt) {
509                                 if (ctxt->loc_handle)
510                                         llog_cat_close(env, ctxt->loc_handle);
511                                 llog_ctxt_put(ctxt);
512                                 ctxt = NULL;
513                         }
514                         retries++;
515                         CDEBUG(D_HA, "%s get update log failed %d, retry\n",
516                                dt->dd_lu_dev.ld_obd->obd_name, rc);
517                         goto again;
518                 }
519         }
520
521         llog_ctxt_put(ctxt);
522         if (rc < 0) {
523                 CERROR("%s: get update log duration %lld, retries %d, failed: rc = %d\n",
524                        dt->dd_lu_dev.ld_obd->obd_name,
525                        ktime_get_real_seconds() - start, retries, rc);
526                 /* abort MDT recovery of this target, but not all targets,
527                  * because recovery still has chance to succeed.
528                  */
529                 if (!obd_mdt_recovery_abort(top_device->ld_obd))
530                         lod_sub_cancel_llog(env, lod, dt, lrd->lrd_idx);
531         } else {
532                 CDEBUG(D_HA,
533                        "%s retrieved update log, duration %lld, retries %d\n",
534                        dt->dd_lu_dev.ld_obd->obd_name,
535                        ktime_get_real_seconds() - start, retries);
536         }
537
538         spin_lock(&lod->lod_lock);
539         if (!lrd->lrd_ltd)
540                 lod->lod_child_got_update_log = 1;
541         else
542                 lrd->lrd_ltd->ltd_got_update_log = 1;
543
544         if (!lod->lod_child_got_update_log) {
545                 spin_unlock(&lod->lod_lock);
546                 GOTO(out, rc);
547         }
548
549         lod_foreach_mdt(lod, mdt) {
550                 if (!mdt->ltd_got_update_log) {
551                         spin_unlock(&lod->lod_lock);
552                         GOTO(out, rc);
553                 }
554         }
555         lut->lut_tdtd->tdtd_replay_ready = 1;
556         spin_unlock(&lod->lod_lock);
557
558         CDEBUG(D_HA, "%s got update logs from all MDTs.\n",
559                lut->lut_obd->obd_name);
560         wake_up(&lut->lut_obd->obd_next_transno_waitq);
561         EXIT;
562
563 out:
564         atomic_dec(&lut->lut_tdtd->tdtd_recovery_threads_count);
565         wake_up(&lut->lut_tdtd->tdtd_recovery_threads_waitq);
566         if (xchg(lrd->lrd_task, NULL) == NULL)
567                 /* Someone is waiting for us to finish, need
568                  * to synchronize cleanly.
569                  */
570                 wait_var_event(lrd, kthread_should_stop());
571         lu_env_fini(env);
572         OBD_FREE_PTR(lrd);
573         return rc;
574 }
575
576 /**
577  * finish sub llog context
578  *
579  * Stop update recovery thread for the sub device, then cleanup the
580  * correspondent llog ctxt.
581  *
582  * \param[in] env      execution environment
583  * \param[in] lod      lod device to do update recovery
584  * \param[in] thread   recovery thread on this sub device
585  */
586 void lod_sub_fini_llog(const struct lu_env *env,
587                        struct dt_device *dt, struct task_struct **thread)
588 {
589         struct obd_device *obd;
590         struct llog_ctxt *ctxt;
591         struct task_struct *task = NULL;
592
593         ENTRY;
594
595         obd = dt->dd_lu_dev.ld_obd;
596         CDEBUG(D_INFO, "%s: finish sub llog\n", obd->obd_name);
597         /* Wait for recovery thread to complete */
598         if (thread)
599                 task = xchg(thread, NULL);
600         if (task)
601                 kthread_stop(task);
602
603         ctxt = llog_get_context(obd, LLOG_UPDATELOG_ORIG_CTXT);
604         if (!ctxt)
605                 RETURN_EXIT;
606
607         if (ctxt->loc_handle)
608                 llog_cat_close(env, ctxt->loc_handle);
609
610         llog_cleanup(env, ctxt);
611
612         RETURN_EXIT;
613 }
614
615 /**
616  * Extract MDT target index from a device name.
617  *
618  * a helper function to extract index from the given device name
619  * like "fsname-MDTxxxx-mdtlov"
620  *
621  * \param[in] lodname           device name
622  * \param[out] mdt_index        extracted index
623  *
624  * \retval 0            on success
625  * \retval -EINVAL      if the name is invalid
626  */
627 int lodname2mdt_index(char *lodname, u32 *mdt_index)
628 {
629         u32 index;
630         const char *ptr, *tmp;
631         int rc;
632
633         /* 1.8 configs don't have "-MDT0000" at the end */
634         ptr = strstr(lodname, "-MDT");
635         if (!ptr) {
636                 *mdt_index = 0;
637                 return 0;
638         }
639
640         ptr = strrchr(lodname, '-');
641         if (!ptr) {
642                 rc = -EINVAL;
643                 CERROR("invalid MDT index in '%s': rc = %d\n", lodname, rc);
644                 return rc;
645         }
646
647         if (strncmp(ptr, "-mdtlov", 7) != 0) {
648                 rc = -EINVAL;
649                 CERROR("invalid MDT index in '%s': rc = %d\n", lodname, rc);
650                 return rc;
651         }
652
653         if ((unsigned long)ptr - (unsigned long)lodname <= 8) {
654                 rc = -EINVAL;
655                 CERROR("invalid MDT index in '%s': rc = %d\n", lodname, rc);
656                 return rc;
657         }
658
659         if (strncmp(ptr - 8, "-MDT", 4) != 0) {
660                 rc = -EINVAL;
661                 CERROR("invalid MDT index in '%s': rc = %d\n", lodname, rc);
662                 return rc;
663         }
664
665         rc = target_name2index(ptr - 7, &index, &tmp);
666         if (rc < 0 || rc & LDD_F_SV_ALL || *tmp != '-') {
667                 rc = -EINVAL;
668                 CERROR("invalid MDT index in '%s': rc = %d\n", lodname, rc);
669                 return rc;
670         }
671         *mdt_index = index;
672         return 0;
673 }
674
675 /**
676  * Init sub llog context
677  *
678  * Setup update llog ctxt for update recovery threads, then start the
679  * recovery thread (lod_sub_recovery_thread) to read update llog from
680  * the correspondent MDT to do update recovery.
681  *
682  * \param[in] env       execution environment
683  * \param[in] lod       lod device to do update recovery
684  * \param[in] dt        sub dt device for which the recovery thread is
685  *
686  * \retval              0 if initialization succeeds.
687  * \retval              negative errno if initialization fails.
688  */
689 int lod_sub_init_llog(const struct lu_env *env, struct lod_device *lod,
690                       struct dt_device *dt)
691 {
692         struct obd_device *obd;
693         struct lod_recovery_data *lrd = NULL;
694         DECLARE_COMPLETION_ONSTACK(started);
695         struct task_struct **taskp;
696         struct task_struct *task;
697         struct lod_tgt_desc *subtgt = NULL;
698         u32 index;
699         u32 master_index;
700         int rc;
701
702         ENTRY;
703
704         rc = lodname2mdt_index(lod2obd(lod)->obd_name, &master_index);
705         if (rc != 0)
706                 RETURN(rc);
707
708         OBD_ALLOC_PTR(lrd);
709         if (!lrd)
710                 RETURN(-ENOMEM);
711
712         if (lod->lod_child == dt) {
713                 taskp = &lod->lod_child_recovery_task;
714                 index = master_index;
715         } else {
716                 struct lu_tgt_desc *mdt;
717
718                 lod_foreach_mdt(lod, mdt) {
719                         if (mdt->ltd_tgt == dt) {
720                                 index = mdt->ltd_index;
721                                 subtgt = mdt;
722                                 break;
723                         }
724                 }
725                 LASSERT(subtgt != NULL);
726                 taskp = &subtgt->ltd_recovery_task;
727         }
728
729         CDEBUG(D_INFO, "%s init sub log %s\n", lod2obd(lod)->obd_name,
730                dt->dd_lu_dev.ld_obd->obd_name);
731         lrd->lrd_lod = lod;
732         lrd->lrd_ltd = subtgt;
733         lrd->lrd_task = taskp;
734         lrd->lrd_idx = index;
735         lrd->lrd_started = &started;
736
737         obd = dt->dd_lu_dev.ld_obd;
738         obd->obd_lvfs_ctxt.dt = dt;
739         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_UPDATELOG_ORIG_CTXT,
740                         NULL, &llog_common_cat_ops);
741         if (rc < 0) {
742                 CERROR("%s: cannot setup updatelog llog: rc = %d\n",
743                        obd->obd_name, rc);
744                 GOTO(free_lrd, rc);
745         }
746
747         rc = lu_env_init(&lrd->lrd_env, LCT_LOCAL | LCT_MD_THREAD);
748         if (rc != 0) {
749                 CERROR("%s: can't initialize env: rc = %d\n",
750                        lod2obd(lod)->obd_name, rc);
751                 GOTO(free_lrd, rc);
752         }
753
754         /* Start the recovery thread */
755         task = kthread_create(lod_sub_recovery_thread, lrd, "lod%04x_rec%04x",
756                               master_index, index);
757         if (IS_ERR(task)) {
758                 rc = PTR_ERR(task);
759                 CERROR("%s: cannot start recovery thread: rc = %d\n",
760                        obd->obd_name, rc);
761                 lu_env_fini(&lrd->lrd_env);
762                 GOTO(out_llog, rc);
763         }
764         *taskp = task;
765         wake_up_process(task);
766         wait_for_completion(&started);
767
768         RETURN(0);
769 out_llog:
770         lod_sub_fini_llog(env, dt, taskp);
771 free_lrd:
772         OBD_FREE_PTR(lrd);
773         RETURN(rc);
774 }
775
776 /**
777  * Stop sub recovery thread
778  *
779  * Stop sub recovery thread on all subs.
780  *
781  * \param[in] env       execution environment
782  * \param[in] lod       lod device to do update recovery
783  */
784 static void lod_sub_stop_recovery_threads(const struct lu_env *env,
785                                           struct lod_device *lod)
786 {
787         struct task_struct *task;
788         struct lu_tgt_desc *mdt;
789
790         /*
791          * Stop the update log commit cancel threads and finish master
792          * llog ctxt
793          */
794         task = xchg(&lod->lod_child_recovery_task, NULL);
795         if (task)
796                 kthread_stop(task);
797
798         lod_getref(&lod->lod_mdt_descs);
799         lod_foreach_mdt(lod, mdt) {
800                 task = xchg(&mdt->ltd_recovery_task, NULL);
801                 if (task)
802                         kthread_stop(task);
803         }
804         lod_putref(lod, &lod->lod_mdt_descs);
805 }
806
807 /**
808  * finish all sub llog
809  *
810  * cleanup all of sub llog ctxt on the LOD.
811  *
812  * \param[in] env       execution environment
813  * \param[in] lod       lod device to do update recovery
814  */
815 static void lod_sub_fini_all_llogs(const struct lu_env *env,
816                                    struct lod_device *lod)
817 {
818         struct lu_tgt_desc *mdt;
819
820         /*
821          * Stop the update log commit cancel threads and finish master
822          * llog ctxt
823          */
824         lod_sub_fini_llog(env, lod->lod_child,
825                           &lod->lod_child_recovery_task);
826         lod_getref(&lod->lod_mdt_descs);
827         lod_foreach_mdt(lod, mdt)
828                 lod_sub_fini_llog(env, mdt->ltd_tgt,
829                                   &mdt->ltd_recovery_task);
830         lod_putref(lod, &lod->lod_mdt_descs);
831 }
832
833 static char *lod_show_update_logs_retrievers(void *data, int *size, int *count)
834 {
835         struct lod_device *lod = (struct lod_device *)data;
836         struct lu_target *lut = lod2lu_dev(lod)->ld_site->ls_tgt;
837         struct lu_tgt_desc *mdt = NULL;
838         char *buf;
839         int len = 0;
840         int rc;
841         int i;
842
843         *count = atomic_read(&lut->lut_tdtd->tdtd_recovery_threads_count);
844         if (*count == 0) {
845                 *size = 0;
846                 return NULL;
847         }
848
849         *size = 5 * *count + 1;
850         OBD_ALLOC(buf, *size);
851         if (!buf)
852                 return NULL;
853
854         *count = 0;
855         memset(buf, 0, *size);
856
857         if (!lod->lod_child_got_update_log) {
858                 rc = lodname2mdt_index(lod2obd(lod)->obd_name, &i);
859                 LASSERTF(rc == 0, "Fail to parse target index: rc = %d\n", rc);
860
861                 rc = scnprintf(buf + len, *size - len, " %04x", i);
862                 LASSERT(rc > 0);
863
864                 len += rc;
865                 (*count)++;
866         }
867
868         lod_foreach_mdt(lod, mdt) {
869                 if (!mdt->ltd_got_update_log) {
870                         rc = scnprintf(buf + len, *size - len, " %04x",
871                                        mdt->ltd_index);
872                         if (unlikely(rc <= 0))
873                                 break;
874
875                         len += rc;
876                         (*count)++;
877                 }
878         }
879
880         return buf;
881 }
882
883 /**
884  * Prepare distribute txn
885  *
886  * Prepare distribute txn structure for LOD
887  *
888  * \param[in] env       execution environment
889  * \param[in] lod_device  LOD device
890  *
891  * \retval              0 if preparation succeeds.
892  * \retval              negative errno if preparation fails.
893  */
894 static int lod_prepare_distribute_txn(const struct lu_env *env,
895                                       struct lod_device *lod)
896 {
897         struct target_distribute_txn_data *tdtd;
898         struct lu_target *lut;
899         int rc;
900
901         ENTRY;
902
903         /* Init update recovery data */
904         OBD_ALLOC_PTR(tdtd);
905         if (!tdtd)
906                 RETURN(-ENOMEM);
907
908         lut = lod2lu_dev(lod)->ld_site->ls_tgt;
909         tdtd->tdtd_dt = &lod->lod_dt_dev;
910         rc = distribute_txn_init(env, lut, tdtd,
911                 lu_site2seq(lod2lu_dev(lod)->ld_site)->ss_node_id);
912
913         if (rc < 0) {
914                 CERROR("%s: cannot init distribute txn: rc = %d\n",
915                        lod2obd(lod)->obd_name, rc);
916                 OBD_FREE_PTR(tdtd);
917                 RETURN(rc);
918         }
919
920         tdtd->tdtd_show_update_logs_retrievers =
921                 lod_show_update_logs_retrievers;
922         tdtd->tdtd_show_retrievers_cbdata = lod;
923
924         lut->lut_tdtd = tdtd;
925
926         RETURN(0);
927 }
928
929 /**
930  * Finish distribute txn
931  *
932  * Release the resource holding by distribute txn, i.e. stop distribute
933  * txn thread.
934  *
935  * \param[in] env       execution environment
936  * \param[in] lod       lod device
937  */
938 static void lod_fini_distribute_txn(const struct lu_env *env,
939                                     struct lod_device *lod)
940 {
941         struct lu_target *lut;
942
943         lut = lod2lu_dev(lod)->ld_site->ls_tgt;
944         target_recovery_fini(lut->lut_obd);
945         if (!lut->lut_tdtd)
946                 return;
947
948         distribute_txn_fini(env, lut->lut_tdtd);
949
950         OBD_FREE_PTR(lut->lut_tdtd);
951         lut->lut_tdtd = NULL;
952 }
953
954 /**
955  * Implementation of lu_device_operations::ldo_process_config() for LOD
956  *
957  * The method is called by the configuration subsystem during setup,
958  * cleanup and when the configuration changes. The method processes
959  * few specific commands like adding/removing the targets, changing
960  * the runtime parameters.
961
962  * \param[in] env               LU environment provided by the caller
963  * \param[in] dev               lod device
964  * \param[in] lcfg              configuration command to apply
965  *
966  * \retval 0                    on success
967  * \retval negative             negated errno on error
968  *
969  * The examples are below.
970  *
971  * Add osc config log:
972  * marker  20 (flags=0x01, v2.2.49.56) lustre-OST0001  'add osc'
973  * add_uuid  nid=192.168.122.162@tcp(0x20000c0a87aa2)  0:  1:nidxxx
974  * attach    0:lustre-OST0001-osc-MDT0001  1:osc  2:lustre-MDT0001-mdtlov_UUID
975  * setup     0:lustre-OST0001-osc-MDT0001  1:lustre-OST0001_UUID  2:nid
976  * lov_modify_tgts add 0:lustre-MDT0001-mdtlov  1:lustre-OST0001_UUID  2:1  3:1
977  * marker  20 (flags=0x02, v2.2.49.56) lustre-OST0001  'add osc'
978  *
979  * Add mdc config log:
980  * marker  10 (flags=0x01, v2.2.49.56) lustre-MDT0000  'add osp'
981  * add_uuid  nid=192.168.122.162@tcp(0x20000c0a87aa2)  0:  1:nid
982  * attach 0:lustre-MDT0000-osp-MDT0001  1:osp  2:lustre-MDT0001-mdtlov_UUID
983  * setup     0:lustre-MDT0000-osp-MDT0001  1:lustre-MDT0000_UUID  2:nid
984  * modify_mdc_tgts add 0:lustre-MDT0001  1:lustre-MDT0000_UUID  2:0  3:1
985  * marker  10 (flags=0x02, v2.2.49.56) lustre-MDT0000_UUID  'add osp'
986  */
987 static int lod_process_config(const struct lu_env *env,
988                               struct lu_device *dev,
989                               struct lustre_cfg *lcfg)
990 {
991         struct lod_device *lod = lu2lod_dev(dev);
992         struct lu_device *next = &lod->lod_child->dd_lu_dev;
993         char *arg1;
994         int rc = 0;
995
996         ENTRY;
997
998         switch (lcfg->lcfg_command) {
999         case LCFG_LOV_DEL_OBD:
1000         case LCFG_LOV_ADD_INA:
1001         case LCFG_LOV_ADD_OBD:
1002         case LCFG_ADD_MDC: {
1003                 u32 index;
1004                 u32 mdt_index;
1005                 int gen;
1006                 /*
1007                  * lov_modify_tgts add  0:lov_mdsA  1:osp  2:0  3:1
1008                  * modify_mdc_tgts add  0:lustre-MDT0001
1009                  *                    1:lustre-MDT0001-mdc0002
1010                  *                    2:2  3:1
1011                  */
1012                 arg1 = lustre_cfg_string(lcfg, 1);
1013
1014                 if (sscanf(lustre_cfg_buf(lcfg, 2), "%d", &index) != 1)
1015                         GOTO(out, rc = -EINVAL);
1016                 if (sscanf(lustre_cfg_buf(lcfg, 3), "%d", &gen) != 1)
1017                         GOTO(out, rc = -EINVAL);
1018
1019                 if (lcfg->lcfg_command == LCFG_LOV_ADD_OBD) {
1020                         u32 mdt_index;
1021
1022                         rc = lodname2mdt_index(lustre_cfg_string(lcfg, 0),
1023                                                &mdt_index);
1024                         if (rc != 0)
1025                                 GOTO(out, rc);
1026
1027                         rc = lod_add_device(env, lod, arg1, index, gen,
1028                                             mdt_index, LUSTRE_OSC_NAME, 1);
1029                 } else if (lcfg->lcfg_command == LCFG_ADD_MDC) {
1030                         mdt_index = index;
1031                         rc = lod_add_device(env, lod, arg1, index, gen,
1032                                             mdt_index, LUSTRE_MDC_NAME, 1);
1033                 } else if (lcfg->lcfg_command == LCFG_LOV_ADD_INA) {
1034                         /*FIXME: Add mdt_index for LCFG_LOV_ADD_INA*/
1035                         mdt_index = 0;
1036                         rc = lod_add_device(env, lod, arg1, index, gen,
1037                                             mdt_index, LUSTRE_OSC_NAME, 0);
1038                 } else {
1039                         rc = lod_del_device(env, lod, &lod->lod_ost_descs,
1040                                             arg1, index, gen);
1041                 }
1042
1043                 break;
1044         }
1045
1046         case LCFG_PARAM: {
1047                 struct obd_device *obd;
1048                 ssize_t count;
1049                 char *param;
1050
1051                 /*
1052                  * Check if it is activate/deactivate mdc
1053                  * lustre-MDTXXXX-osp-MDTXXXX.active=1
1054                  */
1055                 param = lustre_cfg_buf(lcfg, 1);
1056                 if (strstr(param, "osp") && strstr(param, ".active=")) {
1057                         struct lod_tgt_desc *sub_tgt = NULL;
1058                         struct lu_tgt_desc *mdt;
1059                         char *ptr;
1060                         char *tmp;
1061
1062                         ptr = strstr(param, ".");
1063                         *ptr = '\0';
1064                         obd = class_name2obd(param);
1065                         if (!obd) {
1066                                 CERROR("%s: can not find %s: rc = %d\n",
1067                                        lod2obd(lod)->obd_name, param, -EINVAL);
1068                                 *ptr = '.';
1069                                 GOTO(out, rc);
1070                         }
1071
1072                         lod_foreach_mdt(lod, mdt) {
1073                                 if (mdt->ltd_tgt->dd_lu_dev.ld_obd == obd) {
1074                                         sub_tgt = mdt;
1075                                         break;
1076                                 }
1077                         }
1078
1079                         if (!sub_tgt) {
1080                                 CERROR("%s: can not find %s: rc = %d\n",
1081                                        lod2obd(lod)->obd_name, param, -EINVAL);
1082                                 *ptr = '.';
1083                                 GOTO(out, rc);
1084                         }
1085
1086                         *ptr = '.';
1087                         tmp = strstr(param, "=");
1088                         tmp++;
1089                         if (*tmp == '1') {
1090                                 struct llog_ctxt *ctxt;
1091
1092                                 obd = sub_tgt->ltd_tgt->dd_lu_dev.ld_obd;
1093                                 ctxt = llog_get_context(obd,
1094                                                 LLOG_UPDATELOG_ORIG_CTXT);
1095                                 if (!ctxt) {
1096                                         rc = llog_setup(env, obd, &obd->obd_olg,
1097                                                        LLOG_UPDATELOG_ORIG_CTXT,
1098                                                     NULL, &llog_common_cat_ops);
1099                                         if (rc < 0)
1100                                                 GOTO(out, rc);
1101                                 } else {
1102                                         llog_ctxt_put(ctxt);
1103                                 }
1104                                 rc = lod_sub_prep_llog(env, lod,
1105                                                        sub_tgt->ltd_tgt,
1106                                                        sub_tgt->ltd_index);
1107                                 sub_tgt->ltd_active = !rc;
1108                         } else {
1109                                 lod_sub_fini_llog(env, sub_tgt->ltd_tgt,
1110                                                   NULL);
1111                                 sub_tgt->ltd_active = 0;
1112                         }
1113                         GOTO(out, rc);
1114                 }
1115
1116
1117                 if (strstr(param, PARAM_LOD) != NULL)
1118                         count = class_modify_config(lcfg, PARAM_LOD,
1119                                                     &lod->lod_dt_dev.dd_kobj);
1120                 else
1121                         count = class_modify_config(lcfg, PARAM_LOV,
1122                                                     &lod->lod_dt_dev.dd_kobj);
1123                 rc = count > 0 ? 0 : count;
1124                 GOTO(out, rc);
1125         }
1126         case LCFG_PRE_CLEANUP: {
1127                 lod_sub_process_config(env, lod, &lod->lod_mdt_descs, lcfg);
1128                 lod_sub_process_config(env, lod, &lod->lod_ost_descs, lcfg);
1129                 CFS_FAIL_TIMEOUT(OBD_FAIL_TGT_RECOVERY_CONNECT, cfs_fail_val * 2);
1130                 next = &lod->lod_child->dd_lu_dev;
1131                 rc = next->ld_ops->ldo_process_config(env, next, lcfg);
1132                 if (rc != 0)
1133                         CDEBUG(D_HA, "%s: can't process %u: %d\n",
1134                                lod2obd(lod)->obd_name, lcfg->lcfg_command, rc);
1135
1136                 lod_sub_stop_recovery_threads(env, lod);
1137                 lod_fini_distribute_txn(env, lod);
1138                 lod_sub_fini_all_llogs(env, lod);
1139                 break;
1140         }
1141         case LCFG_CLEANUP: {
1142                 if (lod->lod_md_root) {
1143                         dt_object_put(env, &lod->lod_md_root->ldo_obj);
1144                         lod->lod_md_root = NULL;
1145                 }
1146
1147                 /*
1148                  * do cleanup on underlying storage only when
1149                  * all OSPs are cleaned up, as they use that OSD as well
1150                  */
1151                 lu_dev_del_linkage(dev->ld_site, dev);
1152                 lod_sub_process_config(env, lod, &lod->lod_mdt_descs, lcfg);
1153                 lod_sub_process_config(env, lod, &lod->lod_ost_descs, lcfg);
1154                 next = &lod->lod_child->dd_lu_dev;
1155                 rc = next->ld_ops->ldo_process_config(env, next, lcfg);
1156                 if (rc)
1157                         CERROR("%s: can't process %u: rc = %d\n",
1158                                lod2obd(lod)->obd_name, lcfg->lcfg_command, rc);
1159
1160                 rc = obd_disconnect(lod->lod_child_exp);
1161                 if (rc)
1162                         CERROR("error in disconnect from storage: rc = %d\n",
1163                                rc);
1164                 break;
1165         }
1166         default:
1167                 CERROR("%s: unknown command %u\n", lod2obd(lod)->obd_name,
1168                        lcfg->lcfg_command);
1169                 rc = -EINVAL;
1170                 break;
1171         }
1172
1173 out:
1174         RETURN(rc);
1175 }
1176
1177 /**
1178  * Implementation of lu_device_operations::ldo_recovery_complete() for LOD
1179  *
1180  * The method is called once the recovery is complete. This implementation
1181  * distributes the notification to all the known targets.
1182  *
1183  * see include/lu_object.h for the details
1184  */
1185 static int lod_recovery_complete(const struct lu_env *env,
1186                                  struct lu_device *dev)
1187 {
1188         struct lod_device *lod = lu2lod_dev(dev);
1189         struct lu_device *next = &lod->lod_child->dd_lu_dev;
1190         struct lod_tgt_desc *tgt;
1191         int rc;
1192
1193         ENTRY;
1194
1195         LASSERT(lod->lod_recovery_completed == 0);
1196         lod->lod_recovery_completed = 1;
1197
1198         rc = next->ld_ops->ldo_recovery_complete(env, next);
1199
1200         lod_getref(&lod->lod_ost_descs);
1201         if (lod->lod_ost_descs.ltd_tgts_size > 0) {
1202                 lod_foreach_ost(lod, tgt) {
1203                         LASSERT(tgt && tgt->ltd_tgt);
1204                         next = &tgt->ltd_tgt->dd_lu_dev;
1205                         rc = next->ld_ops->ldo_recovery_complete(env, next);
1206                         if (rc)
1207                                 CERROR("%s: can't complete recovery on #%d: rc = %d\n",
1208                                        lod2obd(lod)->obd_name, tgt->ltd_index,
1209                                        rc);
1210                 }
1211         }
1212         lod_putref(lod, &lod->lod_ost_descs);
1213         RETURN(rc);
1214 }
1215
1216 /**
1217  * Init update logs on all sub device
1218  *
1219  * LOD initialize update logs on all of sub devices. Because the initialization
1220  * process might need FLD lookup, see llog_osd_open()->dt_locate()->...->
1221  * lod_object_init(), this API has to be called after LOD is initialized.
1222  * \param[in] env       execution environment
1223  * \param[in] lod       lod device
1224  *
1225  * \retval              0 if update log is initialized successfully.
1226  * \retval              negative errno if initialization fails.
1227  */
1228 static int lod_sub_init_llogs(const struct lu_env *env, struct lod_device *lod)
1229 {
1230         struct lu_tgt_desc *mdt;
1231         int rc;
1232
1233         ENTRY;
1234
1235         /*
1236          * llog must be setup after LOD is initialized, because llog
1237          * initialization include FLD lookup
1238          */
1239         LASSERT(lod->lod_initialized);
1240
1241         /* Init the llog in its own stack */
1242         rc = lod_sub_init_llog(env, lod, lod->lod_child);
1243         if (rc < 0)
1244                 RETURN(rc);
1245
1246         lod_foreach_mdt(lod, mdt) {
1247                 rc = lod_sub_init_llog(env, lod, mdt->ltd_tgt);
1248                 if (rc != 0)
1249                         break;
1250         }
1251
1252         RETURN(rc);
1253 }
1254
1255 #define UPDATE_LOG_MAX_AGE      (30 * 24 * 60 * 60)     /* 30 days, in sec */
1256
1257 static int lod_update_log_stale(const struct lu_env *env, struct dt_object *dto,
1258                                 struct lu_buf *buf)
1259 {
1260         struct lu_attr *attr = &lod_env_info(env)->lti_attr;
1261         struct llog_log_hdr *hdr;
1262         loff_t off = 0;
1263         int rc;
1264
1265         ENTRY;
1266         rc = dt_attr_get(env, dto, attr);
1267         if (rc)
1268                 RETURN(rc);
1269
1270         if (!(attr->la_valid & (LA_CTIME | LA_SIZE)))
1271                 RETURN(-EFAULT);
1272
1273         /* by default update log ctime is not set */
1274         if (attr->la_ctime == 0)
1275                 RETURN(0);
1276
1277         /* update log not expired yet */
1278         if (attr->la_ctime + UPDATE_LOG_MAX_AGE > ktime_get_real_seconds())
1279                 RETURN(0);
1280
1281         if (attr->la_size == 0)
1282                 RETURN(-EFAULT);
1283
1284         rc = dt_read(env, dto, buf, &off);
1285         if (rc < 0)
1286                 RETURN(rc);
1287
1288         hdr = (struct llog_log_hdr *)buf->lb_buf;
1289         if (LLOG_REC_HDR_NEEDS_SWABBING(&hdr->llh_hdr))
1290                 lustre_swab_llog_hdr(hdr);
1291         /* log header is sane and flag LLOG_F_MAX_AGE|LLOG_F_RM_ON_ERR is set */
1292         if (rc >= sizeof(*hdr) &&
1293             hdr->llh_hdr.lrh_type == LLOG_HDR_MAGIC &&
1294             (hdr->llh_flags & (LLOG_F_MAX_AGE | LLOG_F_RM_ON_ERR)) ==
1295             (LLOG_F_MAX_AGE | LLOG_F_RM_ON_ERR))
1296                 RETURN(1);
1297
1298         RETURN(0);
1299 }
1300
1301 /**
1302  * Reclaim stale update log.
1303  *
1304  * When update log is canceld (upon recovery abort), it's not destroy, but
1305  * canceled from catlist, and set ctime and LLOG_F_MAX_AGE|LLOG_F_RM_ON_ERR,
1306  * which is kept for debug. If it expired (more than UPDATE_LOG_MAX_AGE seconds
1307  * passed), destroy it to save space.
1308  */
1309 static int lod_update_log_gc(const struct lu_env *env, struct lod_device *lod,
1310                              struct dt_object *dir, struct dt_object *dto,
1311                              const char *name)
1312 {
1313         struct dt_device *dt = lod->lod_child;
1314         struct thandle *th;
1315         int rc;
1316
1317         ENTRY;
1318         th = dt_trans_create(env, dt);
1319         if (IS_ERR(th))
1320                 RETURN(PTR_ERR(th));
1321
1322         rc = dt_declare_delete(env, dir, (const struct dt_key *)name, th);
1323         if (rc)
1324                 GOTO(out_trans, rc);
1325
1326         rc = dt_declare_destroy(env, dto, th);
1327         if (rc)
1328                 GOTO(out_trans, rc);
1329
1330         rc = dt_trans_start_local(env, dt, th);
1331         if (rc)
1332                 GOTO(out_trans, rc);
1333
1334         rc = dt_delete(env, dir, (const struct dt_key *)name, th);
1335         if (rc)
1336                 GOTO(out_trans, rc);
1337
1338         rc = dt_destroy(env, dto, th);
1339         GOTO(out_trans, rc);
1340 out_trans:
1341         dt_trans_stop(env, dt, th);
1342
1343         return rc;
1344 }
1345
1346 /* reclaim stale update llogs under "update_log_dir" */
1347 static int lod_update_log_dir_gc(const struct lu_env *env,
1348                                  struct lod_device *lod,
1349                                  struct dt_object *dir)
1350 {
1351         struct lod_thread_info *info = lod_env_info(env);
1352         struct lu_buf *buf = &info->lti_linkea_buf;
1353         struct lu_dirent *ent = (struct lu_dirent *)info->lti_key;
1354         struct lu_fid *fid = &info->lti_fid;
1355         struct dt_it *it;
1356         const struct dt_it_ops *iops;
1357         struct dt_object *dto;
1358         int rc;
1359
1360         ENTRY;
1361
1362         if (unlikely(!dt_try_as_dir(env, dir, true)))
1363                 RETURN(-ENOTDIR);
1364
1365         lu_buf_alloc(buf, sizeof(struct llog_log_hdr));
1366         if (!buf->lb_buf)
1367                 RETURN(-ENOMEM);
1368
1369         iops = &dir->do_index_ops->dio_it;
1370         it = iops->init(env, dir, LUDA_64BITHASH);
1371         if (IS_ERR(it))
1372                 GOTO(out, rc = PTR_ERR(it));
1373
1374         rc = iops->load(env, it, 0);
1375         if (rc == 0)
1376                 rc = iops->next(env, it);
1377         else if (rc > 0)
1378                 rc = 0;
1379
1380         while (rc == 0) {
1381                 rc = iops->rec(env, it, (struct dt_rec *)ent, LUDA_64BITHASH);
1382                 if (rc != 0)
1383                         break;
1384
1385                 ent->lde_namelen = le16_to_cpu(ent->lde_namelen);
1386                 if (ent->lde_name[0] == '.') {
1387                         if (ent->lde_namelen == 1)
1388                                 goto next;
1389
1390                         if (ent->lde_namelen == 2 && ent->lde_name[1] == '.')
1391                                 goto next;
1392                 }
1393
1394                 fid_le_to_cpu(fid, &ent->lde_fid);
1395                 dto = dt_locate(env, lod->lod_child, fid);
1396                 if (IS_ERR(dto))
1397                         goto next;
1398
1399                 buf->lb_len = sizeof(struct llog_log_hdr);
1400                 if (lod_update_log_stale(env, dto, buf) == 1)
1401                         lod_update_log_gc(env, lod, dir, dto, ent->lde_name);
1402                 dt_object_put(env, dto);
1403 next:
1404                 rc = iops->next(env, it);
1405         }
1406
1407         iops->put(env, it);
1408         iops->fini(env, it);
1409 out:
1410         buf->lb_len = sizeof(struct llog_log_hdr);
1411         lu_buf_free(buf);
1412
1413         RETURN(rc > 0 ? 0 : rc);
1414 }
1415
1416 /**
1417  * Implementation of lu_device_operations::ldo_prepare() for LOD
1418  *
1419  * see include/lu_object.h for the details.
1420  */
1421 static int lod_prepare(const struct lu_env *env, struct lu_device *pdev,
1422                        struct lu_device *cdev)
1423 {
1424         struct lod_device *lod = lu2lod_dev(cdev);
1425         struct lu_device *next = &lod->lod_child->dd_lu_dev;
1426         struct lu_fid *fid = &lod_env_info(env)->lti_fid;
1427         int rc;
1428         struct dt_object *root;
1429         struct dt_object *dto;
1430         u32 index;
1431
1432         ENTRY;
1433
1434         rc = next->ld_ops->ldo_prepare(env, pdev, next);
1435         if (rc != 0) {
1436                 CERROR("%s: prepare bottom error: rc = %d\n",
1437                        lod2obd(lod)->obd_name, rc);
1438                 RETURN(rc);
1439         }
1440
1441         lod->lod_initialized = 1;
1442
1443         rc = dt_root_get(env, lod->lod_child, fid);
1444         if (rc < 0)
1445                 RETURN(rc);
1446
1447         root = dt_locate(env, lod->lod_child, fid);
1448         if (IS_ERR(root))
1449                 RETURN(PTR_ERR(root));
1450
1451         /* Create update log object */
1452         index = lu_site2seq(lod2lu_dev(lod)->ld_site)->ss_node_id;
1453         lu_update_log_fid(fid, index);
1454
1455         dto = local_file_find_or_create_with_fid(env, lod->lod_child,
1456                                                  fid, root,
1457                                                  lod_update_log_name,
1458                                                  S_IFREG | 0644);
1459         if (IS_ERR(dto))
1460                 GOTO(out_put, rc = PTR_ERR(dto));
1461
1462         dt_object_put(env, dto);
1463
1464         /* Create update log dir */
1465         lu_update_log_dir_fid(fid, index);
1466         dto = local_file_find_or_create_with_fid(env, lod->lod_child,
1467                                                  fid, root,
1468                                                  lod_update_log_dir_name,
1469                                                  S_IFDIR | 0644);
1470         if (IS_ERR(dto))
1471                 GOTO(out_put, rc = PTR_ERR(dto));
1472
1473         lod_update_log_dir_gc(env, lod, dto);
1474         dt_object_put(env, dto);
1475
1476         rc = lod_prepare_distribute_txn(env, lod);
1477         if (rc != 0)
1478                 GOTO(out_put, rc);
1479
1480         rc = lod_sub_init_llogs(env, lod);
1481         if (rc != 0)
1482                 GOTO(out_put, rc);
1483
1484 out_put:
1485         dt_object_put(env, root);
1486
1487         RETURN(rc);
1488 }
1489
1490 /**
1491  * Implementation of lu_device_operations::ldo_fid_alloc() for LOD
1492  *
1493  * Find corresponding device by passed parent and name, and allocate FID from
1494  * there.
1495  *
1496  * see include/lu_object.h for the details.
1497  */
1498 static int lod_fid_alloc(const struct lu_env *env, struct lu_device *d,
1499                          struct lu_fid *fid, struct lu_object *parent,
1500                          const struct lu_name *name)
1501 {
1502         struct lod_device *lod = lu2lod_dev(d);
1503         struct lod_object *lo = lu2lod_obj(parent);
1504         struct dt_device *next;
1505         int rc;
1506
1507         ENTRY;
1508
1509         /* if @parent is remote, we don't know whether its layout was changed,
1510          * always reload layout.
1511          */
1512         if (lu_object_remote(parent))
1513                 lod_striping_free(env, lo);
1514
1515         rc = lod_striping_load(env, lo);
1516         if (rc)
1517                 RETURN(rc);
1518
1519         if (lo->ldo_dir_stripe_count > 0 && name) {
1520                 struct dt_object *stripe;
1521                 int idx;
1522
1523                 idx = __lmv_name_to_stripe_index(lo->ldo_dir_hash_type,
1524                                                  lo->ldo_dir_stripe_count,
1525                                                  lo->ldo_dir_migrate_hash,
1526                                                  lo->ldo_dir_migrate_offset,
1527                                                  name->ln_name,
1528                                                  name->ln_namelen, true);
1529                 if (idx < 0)
1530                         RETURN(idx);
1531
1532                 stripe = lo->ldo_stripe[idx];
1533                 if (!stripe || !dt_object_exists(stripe))
1534                         RETURN(-ENODEV);
1535
1536                 next = lu2dt_dev(stripe->do_lu.lo_dev);
1537         } else {
1538                 next = lod->lod_child;
1539         }
1540
1541         rc = dt_fid_alloc(env, next, fid, parent, name);
1542
1543         RETURN(rc);
1544 }
1545
1546 const struct lu_device_operations lod_lu_ops = {
1547         .ldo_object_alloc       = lod_object_alloc,
1548         .ldo_process_config     = lod_process_config,
1549         .ldo_recovery_complete  = lod_recovery_complete,
1550         .ldo_prepare            = lod_prepare,
1551         .ldo_fid_alloc          = lod_fid_alloc,
1552 };
1553
1554 /**
1555  * Implementation of dt_device_operations::dt_root_get() for LOD
1556  *
1557  * see include/dt_object.h for the details.
1558  */
1559 static int lod_root_get(const struct lu_env *env,
1560                         struct dt_device *dev, struct lu_fid *f)
1561 {
1562         return dt_root_get(env, dt2lod_dev(dev)->lod_child, f);
1563 }
1564
1565 static void lod_statfs_sum(struct obd_statfs *sfs,
1566                              struct obd_statfs *ost_sfs, int *bs)
1567 {
1568         while (ost_sfs->os_bsize < *bs) {
1569                 *bs >>= 1;
1570                 sfs->os_bsize >>= 1;
1571                 sfs->os_bavail <<= 1;
1572                 sfs->os_blocks <<= 1;
1573                 sfs->os_bfree <<= 1;
1574                 sfs->os_granted <<= 1;
1575         }
1576         while (ost_sfs->os_bsize > *bs) {
1577                 ost_sfs->os_bsize >>= 1;
1578                 ost_sfs->os_bavail <<= 1;
1579                 ost_sfs->os_blocks <<= 1;
1580                 ost_sfs->os_bfree <<= 1;
1581                 ost_sfs->os_granted <<= 1;
1582         }
1583         sfs->os_bavail += ost_sfs->os_bavail;
1584         sfs->os_blocks += ost_sfs->os_blocks;
1585         sfs->os_bfree += ost_sfs->os_bfree;
1586         sfs->os_granted += ost_sfs->os_granted;
1587 }
1588
1589 /**
1590  * Implementation of dt_device_operations::dt_statfs() for LOD
1591  *
1592  * see include/dt_object.h for the details.
1593  */
1594 static int lod_statfs(const struct lu_env *env, struct dt_device *dev,
1595                       struct obd_statfs *sfs, struct obd_statfs_info *info)
1596 {
1597         struct lod_device *lod = dt2lod_dev(dev);
1598         struct lu_tgt_desc *tgt;
1599         struct obd_statfs ost_sfs;
1600         u64 ost_files = 0;
1601         u64 ost_ffree = 0;
1602         int rc, bs;
1603
1604         rc = dt_statfs(env, dt2lod_dev(dev)->lod_child, sfs);
1605         if (rc)
1606                 GOTO(out, rc);
1607
1608         bs = sfs->os_bsize;
1609
1610         sfs->os_bavail = 0;
1611         sfs->os_blocks = 0;
1612         sfs->os_bfree = 0;
1613         sfs->os_granted = 0;
1614
1615         lod_getref(&lod->lod_mdt_descs);
1616         lod_foreach_mdt(lod, tgt) {
1617                 rc = dt_statfs(env, tgt->ltd_tgt, &ost_sfs);
1618                 /* ignore errors */
1619                 if (rc)
1620                         continue;
1621                 sfs->os_files += ost_sfs.os_files;
1622                 sfs->os_ffree += ost_sfs.os_ffree;
1623                 lod_statfs_sum(sfs, &ost_sfs, &bs);
1624         }
1625         lod_putref(lod, &lod->lod_mdt_descs);
1626
1627         /*
1628          * at some point we can check whether DoM is enabled and
1629          * decide how to account MDT space. for simplicity let's
1630          * just fallback to pre-DoM policy if any OST is alive
1631          */
1632         lod_getref(&lod->lod_ost_descs);
1633         lod_foreach_ost(lod, tgt) {
1634                 rc = dt_statfs(env, tgt->ltd_tgt, &ost_sfs);
1635                 /* ignore errors */
1636                 if (rc || ost_sfs.os_bsize == 0)
1637                         continue;
1638                 if (!ost_files) {
1639                         /*
1640                          * if only MDTs with DoM then report only MDT blocks,
1641                          * otherwise show only OST blocks, and DoM is "free"
1642                          */
1643                         sfs->os_bavail = 0;
1644                         sfs->os_blocks = 0;
1645                         sfs->os_bfree = 0;
1646                         sfs->os_granted = 0;
1647                 }
1648                 ost_files += ost_sfs.os_files;
1649                 ost_ffree += ost_sfs.os_ffree;
1650                 ost_sfs.os_bavail += ost_sfs.os_granted;
1651                 lod_statfs_sum(sfs, &ost_sfs, &bs);
1652                 LASSERTF(bs == ost_sfs.os_bsize, "%d != %d\n",
1653                         (int)sfs->os_bsize, (int)ost_sfs.os_bsize);
1654         }
1655         lod_putref(lod, &lod->lod_ost_descs);
1656         sfs->os_state |= OS_STATFS_SUM;
1657
1658         /* If we have _some_ OSTs, but don't have as many free objects on the
1659          * OSTs as inodes on the MDTs, reduce the reported number of inodes
1660          * to compensate, so that the "inodes in use" number is correct.
1661          * This should be kept in sync with ll_statfs_internal().
1662          */
1663         if (ost_files && ost_ffree < sfs->os_ffree) {
1664                 sfs->os_files = (sfs->os_files - sfs->os_ffree) + ost_ffree;
1665                 sfs->os_ffree = ost_ffree;
1666         }
1667
1668         /* a single successful statfs should be enough */
1669         rc = 0;
1670
1671 out:
1672         RETURN(rc);
1673 }
1674
1675 /**
1676  * Implementation of dt_device_operations::dt_trans_create() for LOD
1677  *
1678  * Creates a transaction using local (to this node) OSD.
1679  *
1680  * see include/dt_object.h for the details.
1681  */
1682 static struct thandle *lod_trans_create(const struct lu_env *env,
1683                                         struct dt_device *dt)
1684 {
1685         struct thandle *th;
1686
1687         th = top_trans_create(env, dt2lod_dev(dt)->lod_child);
1688         if (IS_ERR(th))
1689                 return th;
1690
1691         th->th_dev = dt;
1692
1693         return th;
1694 }
1695
1696 /* distributed transaction failure may cause object missing or disconnected
1697  * directories, check space before transaction start.
1698  */
1699 static int lod_trans_space_check(const struct lu_env *env,
1700                                  struct lod_device *lod,
1701                                  struct thandle *th)
1702 {
1703         struct lod_thread_info *info = lod_env_info(env);
1704         struct obd_statfs *sfs = &info->lti_osfs;
1705         struct top_thandle *top_th = container_of(th, struct top_thandle,
1706                                                   tt_super);
1707         struct top_multiple_thandle *tmt = top_th->tt_multiple_thandle;
1708         struct sub_thandle *st;
1709         int rc;
1710
1711         if (likely(!tmt))
1712                 return 0;
1713
1714         list_for_each_entry(st, &tmt->tmt_sub_thandle_list, st_sub_list) {
1715                 struct dt_device *sub_dt;
1716
1717                 if (st->st_sub_th == NULL)
1718                         continue;
1719
1720                 if (st->st_sub_th == top_th->tt_master_sub_thandle)
1721                         continue;
1722
1723                 sub_dt = st->st_sub_th->th_dev;
1724                 rc = dt_statfs(env, sub_dt, sfs);
1725                 if (rc) {
1726                         CDEBUG(D_INFO, "%s: fail - statfs error: rc = %d\n",
1727                                sub_dt->dd_lu_dev.ld_obd->obd_name, rc);
1728                         /* statfs may fail during recovery, skip check */
1729                         if (!lod->lod_recovery_completed)
1730                                 rc = 0;
1731                         return rc;
1732                 }
1733
1734                 if (unlikely(sfs->os_state &
1735                              (OS_STATFS_ENOINO | OS_STATFS_ENOSPC))) {
1736                         CDEBUG(D_INFO, "%s: fail - target state %x: rc = %d\n",
1737                                sub_dt->dd_lu_dev.ld_obd->obd_name,
1738                                sfs->os_state, -ENOSPC);
1739                         return -ENOSPC;
1740                 }
1741         }
1742
1743         return 0;
1744 }
1745
1746 /**
1747  * Implementation of dt_device_operations::dt_trans_start() for LOD
1748  *
1749  * Starts the set of local transactions using the targets involved
1750  * in declare phase. Initial support for the distributed transactions.
1751  *
1752  * see include/dt_object.h for the details.
1753  */
1754 static int lod_trans_start(const struct lu_env *env, struct dt_device *dt,
1755                            struct thandle *th)
1756 {
1757         struct lod_device *lod = dt2lod_dev(dt);
1758
1759         if (lod->lod_dist_txn_check_space) {
1760                 int rc;
1761
1762                 rc = lod_trans_space_check(env, lod, th);
1763                 if (rc)
1764                         return rc;
1765         }
1766
1767         return top_trans_start(env, lod->lod_child, th);
1768 }
1769
1770 static int lod_trans_cb_add(struct thandle *th,
1771                             struct dt_txn_commit_cb *dcb)
1772 {
1773         struct top_thandle      *top_th = container_of(th, struct top_thandle,
1774                                                        tt_super);
1775         return dt_trans_cb_add(top_th->tt_master_sub_thandle, dcb);
1776 }
1777
1778 /**
1779  * add noop update to the update records
1780  *
1781  * Add noop updates to the update records, which is only used in
1782  * test right now.
1783  *
1784  * \param[in] env       execution environment
1785  * \param[in] dt        dt device of lod
1786  * \param[in] th        thandle
1787  * \param[in] count     the count of update records to be added.
1788  *
1789  * \retval              0 if adding succeeds.
1790  * \retval              negative errno if adding fails.
1791  */
1792 static int lod_add_noop_records(const struct lu_env *env,
1793                                 struct dt_device *dt, struct thandle *th,
1794                                 int count)
1795 {
1796         struct top_thandle *top_th;
1797         struct lu_fid *fid = &lod_env_info(env)->lti_fid;
1798         int i;
1799         int rc = 0;
1800
1801         top_th = container_of(th, struct top_thandle, tt_super);
1802         if (!top_th->tt_multiple_thandle)
1803                 return 0;
1804
1805         fid_zero(fid);
1806         for (i = 0; i < count; i++) {
1807                 rc = update_record_pack(noop, th, fid);
1808                 if (rc < 0)
1809                         return rc;
1810         }
1811         return rc;
1812 }
1813
1814 /**
1815  * Implementation of dt_device_operations::dt_trans_stop() for LOD
1816  *
1817  * Stops the set of local transactions using the targets involved
1818  * in declare phase. Initial support for the distributed transactions.
1819  *
1820  * see include/dt_object.h for the details.
1821  */
1822 static int lod_trans_stop(const struct lu_env *env, struct dt_device *dt,
1823                           struct thandle *th)
1824 {
1825         if (CFS_FAIL_CHECK(OBD_FAIL_SPLIT_UPDATE_REC)) {
1826                 int rc;
1827
1828                 rc = lod_add_noop_records(env, dt, th, 5000);
1829                 if (rc < 0)
1830                         RETURN(rc);
1831         }
1832         return top_trans_stop(env, dt2lod_dev(dt)->lod_child, th);
1833 }
1834
1835 /**
1836  * Implementation of dt_device_operations::dt_conf_get() for LOD
1837  *
1838  * Currently returns the configuration provided by the local OSD.
1839  *
1840  * see include/dt_object.h for the details.
1841  */
1842 static void lod_conf_get(const struct lu_env *env,
1843                          const struct dt_device *dev,
1844                          struct dt_device_param *param)
1845 {
1846         dt_conf_get(env, dt2lod_dev((struct dt_device *)dev)->lod_child, param);
1847 }
1848
1849 /**
1850  * Implementation of dt_device_operations::dt_sync() for LOD
1851  *
1852  * Syncs all known OST targets. Very very expensive and used
1853  * rarely by LFSCK now. Should not be used in general.
1854  *
1855  * see include/dt_object.h for the details.
1856  */
1857 static int lod_sync(const struct lu_env *env, struct dt_device *dev)
1858 {
1859         struct lod_device *lod = dt2lod_dev(dev);
1860         struct lu_tgt_desc *tgt;
1861         int rc = 0;
1862
1863         ENTRY;
1864
1865         lod_getref(&lod->lod_ost_descs);
1866         lod_foreach_ost(lod, tgt) {
1867                 if (tgt->ltd_discon)
1868                         continue;
1869                 rc = dt_sync(env, tgt->ltd_tgt);
1870                 if (rc) {
1871                         if (rc != -ENOTCONN) {
1872                                 CERROR("%s: can't sync ost %u: rc = %d\n",
1873                                        lod2obd(lod)->obd_name, tgt->ltd_index,
1874                                        rc);
1875                                 break;
1876                         }
1877                         rc = 0;
1878                 }
1879         }
1880         lod_putref(lod, &lod->lod_ost_descs);
1881
1882         if (rc)
1883                 RETURN(rc);
1884
1885         lod_getref(&lod->lod_mdt_descs);
1886         lod_foreach_mdt(lod, tgt) {
1887                 if (tgt->ltd_discon)
1888                         continue;
1889                 rc = dt_sync(env, tgt->ltd_tgt);
1890                 if (rc) {
1891                         if (rc != -ENOTCONN) {
1892                                 CERROR("%s: can't sync mdt %u: rc = %d\n",
1893                                        lod2obd(lod)->obd_name, tgt->ltd_index,
1894                                        rc);
1895                                 break;
1896                         }
1897                         rc = 0;
1898                 }
1899         }
1900         lod_putref(lod, &lod->lod_mdt_descs);
1901
1902         if (rc == 0)
1903                 rc = dt_sync(env, lod->lod_child);
1904
1905         RETURN(rc);
1906 }
1907
1908 /**
1909  * Implementation of dt_device_operations::dt_ro() for LOD
1910  *
1911  * Turns local OSD read-only, used for the testing only.
1912  *
1913  * see include/dt_object.h for the details.
1914  */
1915 static int lod_ro(const struct lu_env *env, struct dt_device *dev)
1916 {
1917         return dt_ro(env, dt2lod_dev(dev)->lod_child);
1918 }
1919
1920 /**
1921  * Implementation of dt_device_operations::dt_commit_async() for LOD
1922  *
1923  * Asks local OSD to commit sooner.
1924  *
1925  * see include/dt_object.h for the details.
1926  */
1927 static int lod_commit_async(const struct lu_env *env, struct dt_device *dev)
1928 {
1929         return dt_commit_async(env, dt2lod_dev(dev)->lod_child);
1930 }
1931
1932 static const struct dt_device_operations lod_dt_ops = {
1933         .dt_root_get         = lod_root_get,
1934         .dt_statfs           = lod_statfs,
1935         .dt_trans_create     = lod_trans_create,
1936         .dt_trans_start      = lod_trans_start,
1937         .dt_trans_stop       = lod_trans_stop,
1938         .dt_conf_get         = lod_conf_get,
1939         .dt_sync             = lod_sync,
1940         .dt_ro               = lod_ro,
1941         .dt_commit_async     = lod_commit_async,
1942         .dt_trans_cb_add     = lod_trans_cb_add,
1943 };
1944
1945 /**
1946  * Connect to a local OSD.
1947  *
1948  * Used to connect to the local OSD at mount. OSD name is taken from the
1949  * configuration command passed. This connection is used to identify LU
1950  * site and pin the OSD from early removal.
1951  *
1952  * \param[in] env               LU environment provided by the caller
1953  * \param[in] lod               lod device
1954  * \param[in] cfg               configuration command to apply
1955  *
1956  * \retval 0                    on success
1957  * \retval negative             negated errno on error
1958  **/
1959 static int lod_connect_to_osd(const struct lu_env *env, struct lod_device *lod,
1960                               struct lustre_cfg *cfg)
1961 {
1962         struct obd_connect_data *data = NULL;
1963         struct obd_device *obd;
1964         char *nextdev = NULL, *p, *s;
1965         int rc, len = 0;
1966
1967         ENTRY;
1968
1969         LASSERT(cfg);
1970         LASSERT(lod->lod_child_exp == NULL);
1971
1972         /*
1973          * compatibility hack: we still use old config logs
1974          * which specify LOV, but we need to learn underlying
1975          * OSD device, which is supposed to be:
1976          *  <fsname>-MDTxxxx-osd
1977          *
1978          * 2.x MGS generates lines like the following:
1979          *   #03 (176)lov_setup 0:lustre-MDT0000-mdtlov  1:(struct lov_desc)
1980          * 1.8 MGS generates lines like the following:
1981          *   #03 (168)lov_setup 0:lustre-mdtlov  1:(struct lov_desc)
1982          *
1983          * we use "-MDT" to differentiate 2.x from 1.8
1984          */
1985         p = lustre_cfg_string(cfg, 0);
1986         if (p && strstr(p, "-mdtlov")) {
1987                 len = strlen(p) + 6;
1988                 OBD_ALLOC(nextdev, len);
1989                 if (!nextdev)
1990                         GOTO(out, rc = -ENOMEM);
1991
1992                 strcpy(nextdev, p);
1993                 s = strstr(nextdev, "-mdtlov");
1994                 if (unlikely(!s)) {
1995                         CERROR("%s: unable to parse device name: rc = %d\n",
1996                                lustre_cfg_string(cfg, 0), -EINVAL);
1997                         GOTO(out, rc = -EINVAL);
1998                 }
1999
2000                 if (strstr(nextdev, "-MDT")) {
2001                         /* 2.x config */
2002                         strcpy(s, "-osd");
2003                 } else {
2004                         /* 1.8 config */
2005                         strcpy(s, "-MDT0000-osd");
2006                 }
2007         } else {
2008                 CERROR("%s: unable to parse device name: rc = %d\n",
2009                        lustre_cfg_string(cfg, 0), -EINVAL);
2010                 GOTO(out, rc = -EINVAL);
2011         }
2012
2013         OBD_ALLOC_PTR(data);
2014         if (!data)
2015                 GOTO(out, rc = -ENOMEM);
2016
2017         obd = class_name2obd(nextdev);
2018         if (!obd) {
2019                 CERROR("%s: can not locate next device: rc = %d\n",
2020                        nextdev, -ENOTCONN);
2021                 GOTO(out, rc = -ENOTCONN);
2022         }
2023
2024         data->ocd_connect_flags = OBD_CONNECT_VERSION;
2025         data->ocd_version = LUSTRE_VERSION_CODE;
2026
2027         rc = obd_connect(env, &lod->lod_child_exp, obd, &obd->obd_uuid,
2028                          data, NULL);
2029         if (rc) {
2030                 CERROR("%s: cannot connect to next dev: rc = %d\n",
2031                        nextdev, rc);
2032                 GOTO(out, rc);
2033         }
2034
2035         lod->lod_dt_dev.dd_lu_dev.ld_site =
2036                 lod->lod_child_exp->exp_obd->obd_lu_dev->ld_site;
2037         LASSERT(lod->lod_dt_dev.dd_lu_dev.ld_site);
2038         lod->lod_child = lu2dt_dev(lod->lod_child_exp->exp_obd->obd_lu_dev);
2039
2040 out:
2041         if (data)
2042                 OBD_FREE_PTR(data);
2043         if (nextdev)
2044                 OBD_FREE(nextdev, len);
2045         RETURN(rc);
2046 }
2047
2048 static int lod_lsfs_init(const struct lu_env *env, struct lod_device *d)
2049 {
2050         struct obd_statfs sfs;
2051         int rc;
2052
2053         rc = dt_statfs(env, d->lod_child, &sfs);
2054         if (rc) {
2055                 CDEBUG(D_LAYOUT, "%s: failed to get OSD statfs, rc = %d\n",
2056                        lod2obd(d)->obd_name, rc);
2057                 return rc;
2058         }
2059
2060         /* udpate local OSD cached statfs data */
2061         spin_lock_init(&d->lod_lsfs_lock);
2062         d->lod_lsfs_age = ktime_get_seconds();
2063         d->lod_lsfs_total_mb = (sfs.os_blocks * sfs.os_bsize) >> 20;
2064         d->lod_lsfs_free_mb = (sfs.os_bfree * sfs.os_bsize) >> 20;
2065         return 0;
2066 }
2067
2068 /**
2069  * Initialize LOD device at setup.
2070  *
2071  * Initializes the given LOD device using the original configuration command.
2072  * The function initiates a connection to the local OSD and initializes few
2073  * internal structures like pools, target tables, etc.
2074  *
2075  * \param[in] env               LU environment provided by the caller
2076  * \param[in] lod               lod device
2077  * \param[in] ldt               not used
2078  * \param[in] cfg               configuration command
2079  *
2080  * \retval 0                    on success
2081  * \retval negative             negated errno on error
2082  **/
2083 static int lod_init0(const struct lu_env *env, struct lod_device *lod,
2084                      struct lu_device_type *ldt, struct lustre_cfg *cfg)
2085 {
2086         struct dt_device_param ddp;
2087         struct obd_device *obd;
2088         int rc;
2089
2090         ENTRY;
2091
2092         obd = class_name2obd(lustre_cfg_string(cfg, 0));
2093         if (!obd) {
2094                 rc = -ENODEV;
2095                 CERROR("Cannot find obd with name '%s': rc = %d\n",
2096                        lustre_cfg_string(cfg, 0), rc);
2097                 RETURN(rc);
2098         }
2099
2100         obd->obd_lu_dev = &lod->lod_dt_dev.dd_lu_dev;
2101         lod->lod_dt_dev.dd_lu_dev.ld_obd = obd;
2102         lod->lod_dt_dev.dd_lu_dev.ld_ops = &lod_lu_ops;
2103         lod->lod_dt_dev.dd_ops = &lod_dt_ops;
2104
2105         rc = lod_connect_to_osd(env, lod, cfg);
2106         if (rc)
2107                 RETURN(rc);
2108
2109         dt_conf_get(env, &lod->lod_dt_dev, &ddp);
2110         lod->lod_osd_max_easize = ddp.ddp_max_ea_size;
2111         lod->lod_dom_stripesize_max_kb = (1ULL << 10); /* 1Mb is default */
2112         lod->lod_max_stripecount = 0;
2113
2114         /* initialize local statfs cached values */
2115         rc = lod_lsfs_init(env, lod);
2116         if (rc)
2117                 GOTO(out_disconnect, rc);
2118
2119         /* default threshold as half of total space, in MiB */
2120         lod->lod_dom_threshold_free_mb = lod->lod_lsfs_total_mb / 2;
2121         /* set default DoM stripe size based on free space amount */
2122         lod_dom_stripesize_recalc(lod);
2123
2124         /* setup obd to be used with old lov code */
2125         rc = lod_pools_init(lod, cfg);
2126         if (rc)
2127                 GOTO(out_disconnect, rc);
2128
2129         rc = lod_procfs_init(lod);
2130         if (rc)
2131                 GOTO(out_pools, rc);
2132
2133         spin_lock_init(&lod->lod_lock);
2134         spin_lock_init(&lod->lod_connects_lock);
2135         lu_tgt_descs_init(&lod->lod_mdt_descs, true);
2136         lu_tgt_descs_init(&lod->lod_ost_descs, false);
2137         lu_qos_rr_init(&lod->lod_mdt_descs.ltd_qos.lq_rr);
2138         lu_qos_rr_init(&lod->lod_ost_descs.ltd_qos.lq_rr);
2139         lod->lod_dist_txn_check_space = 1;
2140
2141         RETURN(0);
2142
2143 out_pools:
2144         lod_pools_fini(lod);
2145 out_disconnect:
2146         obd_disconnect(lod->lod_child_exp);
2147         RETURN(rc);
2148 }
2149
2150 /**
2151  * Implementation of lu_device_type_operations::ldto_device_free() for LOD
2152  *
2153  * Releases the memory allocated for LOD device.
2154  *
2155  * see include/lu_object.h for the details.
2156  */
2157 static struct lu_device *lod_device_free(const struct lu_env *env,
2158                                          struct lu_device *lu)
2159 {
2160         struct lod_device *lod = lu2lod_dev(lu);
2161         struct lu_device  *next = &lod->lod_child->dd_lu_dev;
2162
2163         ENTRY;
2164
2165         if (atomic_read(&lu->ld_site->ls_obj_hash.nelems)) {
2166                 lu_site_print(env, lu->ld_site, &lu->ld_ref, D_ERROR,
2167                               lu_cdebug_printer);
2168         }
2169         LASSERTF(atomic_read(&lu->ld_ref) == 0, "lu is %p\n", lu);
2170         dt_device_fini(&lod->lod_dt_dev);
2171         OBD_FREE_PTR(lod);
2172         RETURN(next);
2173 }
2174
2175 /**
2176  * Implementation of lu_device_type_operations::ldto_device_alloc() for LOD
2177  *
2178  * Allocates LOD device and calls the helpers to initialize it.
2179  *
2180  * see include/lu_object.h for the details.
2181  */
2182 static struct lu_device *lod_device_alloc(const struct lu_env *env,
2183                                           struct lu_device_type *type,
2184                                           struct lustre_cfg *lcfg)
2185 {
2186         struct lod_device *lod;
2187         struct lu_device *lu_dev;
2188
2189         OBD_ALLOC_PTR(lod);
2190         if (!lod) {
2191                 lu_dev = ERR_PTR(-ENOMEM);
2192         } else {
2193                 int rc;
2194
2195                 lu_dev = lod2lu_dev(lod);
2196                 dt_device_init(&lod->lod_dt_dev, type);
2197                 rc = lod_init0(env, lod, type, lcfg);
2198                 if (rc != 0) {
2199                         lod_device_free(env, lu_dev);
2200                         lu_dev = ERR_PTR(rc);
2201                 }
2202         }
2203
2204         return lu_dev;
2205 }
2206
2207 static void lod_avoid_guide_fini(struct lod_avoid_guide *lag)
2208 {
2209         if (lag->lag_oss_avoid_array)
2210                 OBD_FREE_PTR_ARRAY(lag->lag_oss_avoid_array,
2211                                    lag->lag_oaa_size);
2212         bitmap_free(lag->lag_ost_avoid_bitmap);
2213 }
2214
2215 /**
2216  * Implementation of lu_device_type_operations::ldto_device_fini() for LOD
2217  *
2218  * Releases the internal resources used by LOD device.
2219  *
2220  * see include/lu_object.h for the details.
2221  */
2222 static struct lu_device *lod_device_fini(const struct lu_env *env,
2223                                          struct lu_device *d)
2224 {
2225         struct lod_device *lod = lu2lod_dev(d);
2226         int rc;
2227
2228         ENTRY;
2229
2230         lod_pools_fini(lod);
2231
2232         lod_procfs_fini(lod);
2233
2234         rc = lod_fini_tgt(env, lod, &lod->lod_ost_descs);
2235         if (rc)
2236                 CERROR("%s: can not fini ost descriptors: rc =  %d\n",
2237                         lod2obd(lod)->obd_name, rc);
2238
2239         rc = lod_fini_tgt(env, lod, &lod->lod_mdt_descs);
2240         if (rc)
2241                 CERROR("%s: can not fini mdt descriptors: rc =  %d\n",
2242                         lod2obd(lod)->obd_name, rc);
2243
2244         RETURN(NULL);
2245 }
2246
2247 /**
2248  * Implementation of obd_ops::o_connect() for LOD
2249  *
2250  * Used to track all the users of this specific LOD device,
2251  * so the device stays up until the last user disconnected.
2252  *
2253  * \param[in] env               LU environment provided by the caller
2254  * \param[out] exp              export the caller will be using to access LOD
2255  * \param[in] obd               OBD device representing LOD device
2256  * \param[in] cluuid            unique identifier of the caller
2257  * \param[in] data              not used
2258  * \param[in] localdata         not used
2259  *
2260  * \retval 0                    on success
2261  * \retval negative             negated errno on error
2262  **/
2263 static int lod_obd_connect(const struct lu_env *env, struct obd_export **exp,
2264                            struct obd_device *obd, struct obd_uuid *cluuid,
2265                            struct obd_connect_data *data, void *localdata)
2266 {
2267         struct lod_device *lod = lu2lod_dev(obd->obd_lu_dev);
2268         struct lustre_handle conn;
2269         int rc;
2270
2271         ENTRY;
2272
2273         CDEBUG(D_CONFIG, "connect #%d\n", lod->lod_connects);
2274
2275         rc = class_connect(&conn, obd, cluuid);
2276         if (rc)
2277                 RETURN(rc);
2278
2279         *exp = class_conn2export(&conn);
2280
2281         spin_lock(&lod->lod_connects_lock);
2282         lod->lod_connects++;
2283         /* at the moment we expect the only user */
2284         LASSERT(lod->lod_connects == 1);
2285         spin_unlock(&lod->lod_connects_lock);
2286
2287         RETURN(0);
2288 }
2289
2290 /**
2291  *
2292  * Implementation of obd_ops::o_disconnect() for LOD
2293  *
2294  * When the caller doesn't need to use this LOD instance, it calls
2295  * obd_disconnect() and LOD releases corresponding export/reference count.
2296  * Once all the users gone, LOD device is released.
2297  *
2298  * \param[in] exp               export provided to the caller in obd_connect()
2299  *
2300  * \retval 0                    on success
2301  * \retval negative             negated errno on error
2302  **/
2303 static int lod_obd_disconnect(struct obd_export *exp)
2304 {
2305         struct obd_device *obd = exp->exp_obd;
2306         struct lod_device *lod = lu2lod_dev(obd->obd_lu_dev);
2307         int rc, release = 0;
2308
2309         ENTRY;
2310
2311         /* Only disconnect the underlying layers on the final disconnect. */
2312         spin_lock(&lod->lod_connects_lock);
2313         lod->lod_connects--;
2314         if (lod->lod_connects != 0) {
2315                 /* why should there be more than 1 connect? */
2316                 spin_unlock(&lod->lod_connects_lock);
2317                 CERROR("%s: disconnect #%d\n", exp->exp_obd->obd_name,
2318                        lod->lod_connects);
2319                 goto out;
2320         }
2321         spin_unlock(&lod->lod_connects_lock);
2322
2323         /* the last user of lod has gone, let's release the device */
2324         release = 1;
2325
2326 out:
2327         rc = class_disconnect(exp); /* bz 9811 */
2328
2329         if (rc == 0 && release)
2330                 class_manual_cleanup(obd);
2331         RETURN(rc);
2332 }
2333
2334 LU_KEY_INIT(lod, struct lod_thread_info);
2335
2336 static void lod_key_fini(const struct lu_context *ctx,
2337                 struct lu_context_key *key, void *data)
2338 {
2339         struct lod_thread_info *info = data;
2340         struct lod_layout_component *lds =
2341                                 info->lti_def_striping.lds_def_comp_entries;
2342
2343         /*
2344          * allocated in lod_get_lov_ea
2345          * XXX: this is overload, a tread may have such store but used only
2346          * once. Probably better would be pool of such stores per LOD.
2347          */
2348         if (info->lti_ea_store) {
2349                 OBD_FREE_LARGE(info->lti_ea_store, info->lti_ea_store_size);
2350                 info->lti_ea_store = NULL;
2351                 info->lti_ea_store_size = 0;
2352         }
2353         lu_buf_free(&info->lti_linkea_buf);
2354
2355         if (lds)
2356                 lod_free_def_comp_entries(&info->lti_def_striping);
2357
2358         if (info->lti_comp_size > 0)
2359                 OBD_FREE_PTR_ARRAY(info->lti_comp_idx,
2360                                    info->lti_comp_size);
2361
2362         lod_avoid_guide_fini(&info->lti_avoid);
2363
2364         OBD_FREE_PTR(info);
2365 }
2366
2367 /* context key: lod_thread_key */
2368 LU_CONTEXT_KEY_DEFINE(lod, LCT_MD_THREAD);
2369
2370 LU_TYPE_INIT_FINI(lod, &lod_thread_key);
2371
2372 static const struct lu_device_type_operations lod_device_type_ops = {
2373         .ldto_init              = lod_type_init,
2374         .ldto_fini              = lod_type_fini,
2375
2376         .ldto_start             = lod_type_start,
2377         .ldto_stop              = lod_type_stop,
2378
2379         .ldto_device_alloc      = lod_device_alloc,
2380         .ldto_device_free       = lod_device_free,
2381
2382         .ldto_device_fini       = lod_device_fini
2383 };
2384
2385 static struct lu_device_type lod_device_type = {
2386         .ldt_tags     = LU_DEVICE_DT,
2387         .ldt_name     = LUSTRE_LOD_NAME,
2388         .ldt_ops      = &lod_device_type_ops,
2389         .ldt_ctx_tags = LCT_MD_THREAD,
2390 };
2391
2392 /**
2393  * Implementation of obd_ops::o_get_info() for LOD
2394  *
2395  * Currently, there is only one supported key: KEY_OSP_CONNECTED , to provide
2396  * the caller binary status whether LOD has seen connection to any OST target.
2397  * It will also check if the MDT update log context being initialized (if
2398  * needed).
2399  *
2400  * \param[in] env               LU environment provided by the caller
2401  * \param[in] exp               export of the caller
2402  * \param[in] keylen            len of the key
2403  * \param[in] key               the key
2404  * \param[in] vallen            not used
2405  * \param[in] val               not used
2406  *
2407  * \retval                      0 if a connection was seen
2408  * \retval                      -EAGAIN if LOD isn't running yet or no
2409  *                              connection has been seen yet
2410  * \retval                      -EINVAL if not supported key is requested
2411  **/
2412 static int lod_obd_get_info(const struct lu_env *env, struct obd_export *exp,
2413                             u32 keylen, void *key, u32 *vallen, void *val)
2414 {
2415         int rc = -EINVAL;
2416
2417         if (KEY_IS(KEY_OSP_CONNECTED)) {
2418                 struct obd_device *obd = exp->exp_obd;
2419                 struct lod_device *d;
2420                 struct lod_tgt_desc *tgt;
2421                 int rc = 1;
2422
2423                 if (!obd->obd_set_up || obd->obd_stopping)
2424                         RETURN(-EAGAIN);
2425
2426                 d = lu2lod_dev(obd->obd_lu_dev);
2427                 lod_getref(&d->lod_ost_descs);
2428                 lod_foreach_ost(d, tgt) {
2429                         rc = obd_get_info(env, tgt->ltd_exp, keylen, key,
2430                                           vallen, val);
2431                         /* one healthy device is enough */
2432                         if (rc == 0)
2433                                 break;
2434                 }
2435                 lod_putref(d, &d->lod_ost_descs);
2436
2437                 lod_getref(&d->lod_mdt_descs);
2438                 lod_foreach_mdt(d, tgt) {
2439                         struct llog_ctxt *ctxt;
2440                         struct obd_device *ld = tgt->ltd_tgt->dd_lu_dev.ld_obd;
2441
2442                         if (!tgt->ltd_active)
2443                                 continue;
2444
2445                         ctxt = llog_get_context(ld, LLOG_UPDATELOG_ORIG_CTXT);
2446                         LASSERT(ctxt != NULL);
2447                         if (!ctxt->loc_handle) {
2448                                 CDEBUG(D_INFO, "%s: %s is not ready(%p).\n",
2449                                        obd->obd_name, ld->obd_name, ctxt);
2450                                 llog_ctxt_put(ctxt);
2451                                 rc = -EAGAIN;
2452                                 break;
2453                         }
2454                         llog_ctxt_put(ctxt);
2455                 }
2456                 lod_putref(d, &d->lod_mdt_descs);
2457
2458                 RETURN(rc);
2459         }
2460
2461         RETURN(rc);
2462 }
2463
2464 static int lod_obd_set_info_async(const struct lu_env *env,
2465                                   struct obd_export *exp,
2466                                   u32 keylen, void *key,
2467                                   u32 vallen, void *val,
2468                                   struct ptlrpc_request_set *set)
2469 {
2470         struct obd_device *obd = class_exp2obd(exp);
2471         struct lod_device *d;
2472         struct lod_tgt_desc *tgt;
2473         int no_set = 0;
2474         int rc = 0, rc2;
2475
2476         ENTRY;
2477
2478         if (!set) {
2479                 no_set = 1;
2480                 set = ptlrpc_prep_set();
2481                 if (!set)
2482                         RETURN(-ENOMEM);
2483         }
2484
2485         d = lu2lod_dev(obd->obd_lu_dev);
2486         lod_getref(&d->lod_ost_descs);
2487         lod_foreach_ost(d, tgt) {
2488                 if (tgt->ltd_discon)
2489                         continue;
2490
2491                 rc2 = obd_set_info_async(env, tgt->ltd_exp, keylen, key,
2492                                          vallen, val, set);
2493                 if (rc2 != 0 && rc == 0)
2494                         rc = rc2;
2495         }
2496         lod_putref(d, &d->lod_ost_descs);
2497
2498         lod_getref(&d->lod_mdt_descs);
2499         lod_foreach_mdt(d, tgt) {
2500                 if (tgt->ltd_discon)
2501                         continue;
2502
2503                 rc2 = obd_set_info_async(env, tgt->ltd_exp, keylen, key,
2504                                          vallen, val, set);
2505                 if (rc2 != 0 && rc == 0)
2506                         rc = rc2;
2507         }
2508         lod_putref(d, &d->lod_mdt_descs);
2509
2510
2511         if (no_set) {
2512                 rc2 = ptlrpc_set_wait(env, set);
2513                 if (rc2 == 0 && rc == 0)
2514                         rc = rc2;
2515                 ptlrpc_set_destroy(set);
2516         }
2517         RETURN(rc);
2518 }
2519
2520
2521 #define QMT0_DEV_NAME_LEN (LUSTRE_MAXFSNAME + sizeof("-QMT0000"))
2522 static struct obd_device *obd_find_qmt0(char *obd_name)
2523 {
2524         char qmt_name[QMT0_DEV_NAME_LEN];
2525         struct obd_device *qmt = NULL;
2526
2527         if (!server_name2fsname(obd_name, qmt_name, NULL)) {
2528                 strlcat(qmt_name, "-QMT0000", QMT0_DEV_NAME_LEN);
2529                 qmt = class_name2obd(qmt_name);
2530         }
2531
2532         return qmt;
2533 }
2534
2535 /* Run QMT0000 pool operations only for MDT0000 */
2536 static inline bool lod_pool_need_qmt0(const char *obd_name)
2537 {
2538         __u32 idx;
2539         int type;
2540
2541         type = server_name2index(obd_name, &idx, NULL);
2542
2543         return type == LDD_F_SV_TYPE_MDT && idx == 0;
2544 }
2545
2546 static int lod_pool_new_q(struct obd_device *obd, char *poolname)
2547 {
2548         int err = lod_pool_new(obd, poolname);
2549
2550         if (!err && lod_pool_need_qmt0(obd->obd_name)) {
2551                 obd = obd_find_qmt0(obd->obd_name);
2552                 if (obd)
2553                         obd_pool_new(obd, poolname);
2554         }
2555
2556         return err;
2557 }
2558
2559 static int lod_pool_remove_q(struct obd_device *obd, char *poolname,
2560                              char *ostname)
2561 {
2562         int err = lod_pool_remove(obd, poolname, ostname);
2563
2564         if (!err && lod_pool_need_qmt0(obd->obd_name)) {
2565                 obd = obd_find_qmt0(obd->obd_name);
2566                 if (obd)
2567                         obd_pool_rem(obd, poolname, ostname);
2568         }
2569
2570         return err;
2571 }
2572
2573 static int lod_pool_add_q(struct obd_device *obd, char *poolname, char *ostname)
2574 {
2575         int err = lod_pool_add(obd, poolname, ostname);
2576
2577         if (!err && lod_pool_need_qmt0(obd->obd_name)) {
2578                 obd = obd_find_qmt0(obd->obd_name);
2579                 if (obd)
2580                         obd_pool_add(obd, poolname, ostname);
2581         }
2582
2583         return err;
2584 }
2585
2586 static int lod_pool_del_q(struct obd_device *obd, char *poolname)
2587 {
2588         int err = lod_pool_del(obd, poolname);
2589
2590         if (!err && lod_pool_need_qmt0(obd->obd_name)) {
2591                 obd = obd_find_qmt0(obd->obd_name);
2592                 if (obd)
2593                         obd_pool_del(obd, poolname);
2594         }
2595
2596         return err;
2597 }
2598
2599 static inline int lod_sub_print_llog(const struct lu_env *env,
2600                                      struct dt_device *dt, void *data)
2601 {
2602         struct llog_ctxt *ctxt;
2603         int rc = 0;
2604
2605         ENTRY;
2606         ctxt = llog_get_context(dt->dd_lu_dev.ld_obd,
2607                                 LLOG_UPDATELOG_ORIG_CTXT);
2608         if (!ctxt)
2609                 RETURN(0);
2610
2611         if (ctxt->loc_handle) {
2612                 struct llog_print_data *lprd = data;
2613                 struct obd_ioctl_data *ioc_data = lprd->lprd_data;
2614                 int l, remains;
2615                 long from;
2616                 char *out;
2617
2618                 LASSERT(ioc_data);
2619                 if (ioc_data->ioc_inllen1 > 0) {
2620                         remains = ioc_data->ioc_inllen4 +
2621                                   round_up(ioc_data->ioc_inllen1, 8) +
2622                                   round_up(ioc_data->ioc_inllen2, 8) +
2623                                   round_up(ioc_data->ioc_inllen3, 8);
2624
2625                         rc = kstrtol(ioc_data->ioc_inlbuf2, 0, &from);
2626                         if (rc)
2627                                 GOTO(ctxt_put, rc);
2628
2629                         /* second iteration from jt_llog_print_iter() */
2630                         if (from > 1)
2631                                 GOTO(ctxt_put, rc = 0);
2632
2633                         out = ioc_data->ioc_bulk;
2634                         ioc_data->ioc_inllen1 = 0;
2635                 } else {
2636                         out = ioc_data->ioc_bulk + ioc_data->ioc_offset;
2637                         remains = ioc_data->ioc_count;
2638                 }
2639
2640                 l = snprintf(out, remains, "%s [catalog]: "DFID"\n",
2641                              ctxt->loc_obd->obd_name,
2642                              PLOGID(&ctxt->loc_handle->lgh_id));
2643                 out += l;
2644                 remains -= l;
2645                 if (remains <= 0) {
2646                         CERROR("%s: not enough space for print log records: rc = %d\n",
2647                                ctxt->loc_obd->obd_name, -LLOG_EEMPTY);
2648                         GOTO(ctxt_put, rc = -LLOG_EEMPTY);
2649                 }
2650
2651                 ioc_data->ioc_offset += l;
2652                 ioc_data->ioc_count = remains;
2653
2654                 rc = llog_process_or_fork(env, ctxt->loc_handle, llog_print_cb,
2655                                           data, NULL, false);
2656         }
2657         GOTO(ctxt_put, rc);
2658 ctxt_put:
2659         llog_ctxt_put(ctxt);
2660
2661         return rc;
2662 }
2663
2664 /* print update catalog and update logs FID of all sub devices */
2665 static int lod_llog_print(const struct lu_env *env, struct lod_device *lod,
2666                           void *data)
2667 {
2668         struct lod_tgt_desc *mdt;
2669         bool empty = true;
2670         int rc = 0;
2671
2672         ENTRY;
2673         rc = lod_sub_print_llog(env, lod->lod_child, data);
2674         if (!rc) {
2675                 empty = false;
2676         } else if (rc == -LLOG_EEMPTY) {
2677                 rc = 0;
2678         } else {
2679                 CERROR("%s: llog_print failed: rc = %d\n",
2680                        lod2obd(lod)->obd_name, rc);
2681                 RETURN(rc);
2682         }
2683
2684         lod_getref(&lod->lod_mdt_descs);
2685         lod_foreach_mdt(lod, mdt) {
2686                 rc = lod_sub_print_llog(env, mdt->ltd_tgt, data);
2687                 if (!rc) {
2688                         empty = false;
2689                 } else if (rc == -LLOG_EEMPTY) {
2690                         rc = 0;
2691                 } else {
2692                         CERROR("%s: llog_print of MDT %u failed: rc = %d\n",
2693                                lod2obd(lod)->obd_name, mdt->ltd_index, rc);
2694                         break;
2695                 }
2696         }
2697         lod_putref(lod, &lod->lod_mdt_descs);
2698
2699         RETURN(rc ? rc : empty ? -LLOG_EEMPTY : 0);
2700 }
2701
2702 /* cancel update catalog from update catlist */
2703 static int lod_llog_cancel(const struct lu_env *env, struct lod_device *lod)
2704 {
2705         struct lod_tgt_desc *tgt;
2706         int index;
2707         int rc;
2708         int rc2;
2709
2710         rc = lodname2mdt_index(lod2obd(lod)->obd_name, (__u32 *)&index);
2711         if (rc < 0)
2712                 return rc;
2713
2714         rc = lod_sub_cancel_llog(env, lod, lod->lod_child, index);
2715
2716         lod_getref(&lod->lod_mdt_descs);
2717         lod_foreach_mdt(lod, tgt) {
2718                 LASSERT(tgt && tgt->ltd_tgt);
2719                 rc2 = lod_sub_cancel_llog(env, lod, tgt->ltd_tgt,
2720                                           tgt->ltd_index);
2721                 if (rc2 && !rc)
2722                         rc = rc2;
2723         }
2724         lod_putref(lod, &lod->lod_mdt_descs);
2725
2726         return rc;
2727 }
2728
2729 static int lod_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
2730                          void *karg, void __user *uarg)
2731 {
2732         struct obd_device *obd = exp->exp_obd;
2733         struct lod_device *lod = lu2lod_dev(obd->obd_lu_dev);
2734         struct obd_ioctl_data *data;
2735         struct lu_env env;
2736         int rc;
2737
2738         ENTRY;
2739         CDEBUG(D_IOCTL, "%s: cmd=%x len=%u karg=%pK uarg=%pK\n",
2740                obd->obd_name, cmd, len, karg, uarg);
2741         if (unlikely(karg == NULL))
2742                 RETURN(OBD_IOC_ERROR(obd->obd_name, cmd, "karg=NULL", -EINVAL));
2743         data = karg;
2744
2745         rc = lu_env_init(&env, LCT_LOCAL | LCT_MD_THREAD);
2746         if (rc) {
2747                 CERROR("%s: can't initialize env: rc = %d\n",
2748                        lod2obd(lod)->obd_name, rc);
2749                 RETURN(rc);
2750         }
2751
2752         switch (cmd) {
2753         case OBD_IOC_LLOG_PRINT: {
2754                 struct llog_print_data lprd = {
2755                         .lprd_data = data,
2756                         .lprd_raw = data->ioc_u32_1,
2757                 };
2758                 char *logname;
2759
2760                 logname = data->ioc_inlbuf1;
2761                 if (strcmp(logname, lod_update_log_name) != 0) {
2762                         rc = -EINVAL;
2763                         CERROR("%s: llog iocontrol support %s only: rc = %d\n",
2764                                lod2obd(lod)->obd_name, lod_update_log_name, rc);
2765                         RETURN(rc);
2766                 }
2767
2768                 LASSERT(data->ioc_inllen1 > 0);
2769                 rc = lod_llog_print(&env, lod, &lprd);
2770                 break;
2771         }
2772         case OBD_IOC_LLOG_CANCEL:
2773                 rc = lod_llog_cancel(&env, lod);
2774                 break;
2775         default:
2776                 rc = OBD_IOC_ERROR(obd->obd_name, cmd, "unrecognized", -ENOTTY);
2777                 break;
2778         }
2779         lu_env_fini(&env);
2780
2781         RETURN(rc);
2782 }
2783
2784 static const struct obd_ops lod_obd_device_ops = {
2785         .o_owner        = THIS_MODULE,
2786         .o_connect      = lod_obd_connect,
2787         .o_disconnect   = lod_obd_disconnect,
2788         .o_get_info     = lod_obd_get_info,
2789         .o_set_info_async = lod_obd_set_info_async,
2790         .o_pool_new     = lod_pool_new_q,
2791         .o_pool_rem     = lod_pool_remove_q,
2792         .o_pool_add     = lod_pool_add_q,
2793         .o_pool_del     = lod_pool_del_q,
2794         .o_iocontrol    = lod_iocontrol,
2795 };
2796
2797 static int __init lod_init(void)
2798 {
2799         struct obd_type *sym;
2800         int rc;
2801
2802         rc = lu_kmem_init(lod_caches);
2803         if (rc)
2804                 return rc;
2805
2806         rc = class_register_type(&lod_obd_device_ops, NULL, true,
2807                                  LUSTRE_LOD_NAME, &lod_device_type);
2808         if (rc) {
2809                 lu_kmem_fini(lod_caches);
2810                 return rc;
2811         }
2812
2813         /* create "lov" entry for compatibility purposes */
2814         sym = class_add_symlinks(LUSTRE_LOV_NAME, true);
2815         if (IS_ERR(sym)) {
2816                 rc = PTR_ERR(sym);
2817                 /* does real "lov" already exist ? */
2818                 if (rc == -EEXIST)
2819                         rc = 0;
2820         }
2821
2822         return rc;
2823 }
2824
2825 static void __exit lod_exit(void)
2826 {
2827         struct obd_type *sym = class_search_type(LUSTRE_LOV_NAME);
2828
2829         /* if this was never fully initialized by the lov layer
2830          * then we are responsible for freeing this obd_type
2831          */
2832         if (sym) {
2833                 /* final put if we manage this obd type */
2834                 if (sym->typ_sym_filter)
2835                         kobject_put(&sym->typ_kobj);
2836                 /* put reference taken by class_search_type */
2837                 kobject_put(&sym->typ_kobj);
2838         }
2839
2840         class_unregister_type(LUSTRE_LOD_NAME);
2841         lu_kmem_fini(lod_caches);
2842 }
2843
2844 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
2845 MODULE_DESCRIPTION("Lustre Logical Object Device ("LUSTRE_LOD_NAME")");
2846 MODULE_VERSION(LUSTRE_VERSION_STRING);
2847 MODULE_LICENSE("GPL");
2848
2849 module_init(lod_init);
2850 module_exit(lod_exit);