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