Whamcloud - gitweb
6617160a35701cb53b00c24e4f2e52cdb3ace868
[fs/lustre-release.git] / lustre / mgc / mgc_request.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/mgc/mgc_request.c
33  *
34  * Author: Nathan Rutman <nathan@clusterfs.com>
35  */
36
37 #define DEBUG_SUBSYSTEM S_MGC
38 #define D_MGC D_CONFIG /*|D_WARNING*/
39
40 #include <linux/module.h>
41 #include <linux/kthread.h>
42 #include <linux/random.h>
43
44 #include <dt_object.h>
45 #include <lprocfs_status.h>
46 #include <lustre_dlm.h>
47 #include <lustre_disk.h>
48 #include <lustre_log.h>
49 #include <lustre_nodemap.h>
50 #include <lustre_swab.h>
51 #include <obd_class.h>
52 #include <lustre_barrier.h>
53
54 #include "mgc_internal.h"
55
56 static int mgc_name2resid(char *name, int len, struct ldlm_res_id *res_id,
57                           int type)
58 {
59         __u64 resname = 0;
60
61         if (len > sizeof(resname)) {
62                 CERROR("name too long: %s\n", name);
63                 return -EINVAL;
64         }
65         if (len <= 0) {
66                 CERROR("missing name: %s\n", name);
67                 return -EINVAL;
68         }
69         memcpy(&resname, name, len);
70
71         /* Always use the same endianness for the resid */
72         memset(res_id, 0, sizeof(*res_id));
73         res_id->name[0] = cpu_to_le64(resname);
74         /* XXX: unfortunately, sptlprc and config llog share one lock */
75         switch(type) {
76         case CONFIG_T_CONFIG:
77         case CONFIG_T_SPTLRPC:
78                 resname = 0;
79                 break;
80         case CONFIG_T_RECOVER:
81         case CONFIG_T_PARAMS:
82         case CONFIG_T_NODEMAP:
83         case CONFIG_T_BARRIER:
84                 resname = type;
85                 break;
86         default:
87                 LBUG();
88         }
89         res_id->name[1] = cpu_to_le64(resname);
90         CDEBUG(D_MGC, "log %s to resid %#llx/%#llx (%.8s)\n", name,
91                res_id->name[0], res_id->name[1], (char *)&res_id->name[0]);
92         return 0;
93 }
94
95 int mgc_fsname2resid(char *fsname, struct ldlm_res_id *res_id, int type)
96 {
97         /* fsname is at most 8 chars long, maybe contain "-".
98          * e.g. "lustre", "SUN-000" */
99         return mgc_name2resid(fsname, strlen(fsname), res_id, type);
100 }
101 EXPORT_SYMBOL(mgc_fsname2resid);
102
103 int mgc_logname2resid(char *logname, struct ldlm_res_id *res_id, int type)
104 {
105         char *name_end;
106         int len;
107
108         /* logname consists of "fsname-nodetype".
109          * e.g. "lustre-MDT0001", "SUN-000-client"
110          * there is an exception: llog "params" */
111         name_end = strrchr(logname, '-');
112         if (!name_end)
113                 len = strlen(logname);
114         else
115                 len = name_end - logname;
116         return mgc_name2resid(logname, len, res_id, type);
117 }
118 EXPORT_SYMBOL(mgc_logname2resid);
119
120 /********************** config llog list **********************/
121 static struct list_head config_llog_list = LIST_HEAD_INIT(config_llog_list);
122 static DEFINE_SPINLOCK(config_list_lock);       /* protects config_llog_list */
123
124 /* Take a reference to a config log */
125 static int config_log_get(struct config_llog_data *cld)
126 {
127         ENTRY;
128         atomic_inc(&cld->cld_refcount);
129         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
130                 atomic_read(&cld->cld_refcount));
131         RETURN(0);
132 }
133
134 /* Drop a reference to a config log.  When no longer referenced,
135    we can free the config log data */
136 static void config_log_put(struct config_llog_data *cld)
137 {
138         ENTRY;
139
140         if (unlikely(!cld))
141                 RETURN_EXIT;
142
143         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
144                 atomic_read(&cld->cld_refcount));
145         LASSERT(atomic_read(&cld->cld_refcount) > 0);
146
147         /* spinlock to make sure no item with 0 refcount in the list */
148         if (atomic_dec_and_lock(&cld->cld_refcount, &config_list_lock)) {
149                 list_del(&cld->cld_list_chain);
150                 spin_unlock(&config_list_lock);
151
152                 CDEBUG(D_MGC, "dropping config log %s\n", cld->cld_logname);
153
154                 config_log_put(cld->cld_barrier);
155                 config_log_put(cld->cld_recover);
156                 config_log_put(cld->cld_params);
157                 config_log_put(cld->cld_nodemap);
158                 config_log_put(cld->cld_sptlrpc);
159                 if (cld_is_sptlrpc(cld))
160                         sptlrpc_conf_log_stop(cld->cld_logname);
161
162                 class_export_put(cld->cld_mgcexp);
163                 OBD_FREE(cld, sizeof(*cld) + strlen(cld->cld_logname) + 1);
164         }
165
166         EXIT;
167 }
168
169 /* Find a config log by name */
170 static
171 struct config_llog_data *config_log_find(char *logname,
172                                          struct config_llog_instance *cfg)
173 {
174         struct config_llog_data *cld;
175         struct config_llog_data *found = NULL;
176         unsigned long cfg_instance;
177
178         ENTRY;
179         LASSERT(logname != NULL);
180
181         cfg_instance = cfg ? cfg->cfg_instance : 0;
182         spin_lock(&config_list_lock);
183         list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
184                 /* check if cfg_instance is the one we want */
185                 if (cfg_instance != cld->cld_cfg.cfg_instance)
186                         continue;
187
188                 /* instance may be NULL, should check name */
189                 if (strcmp(logname, cld->cld_logname) == 0) {
190                         found = cld;
191                         config_log_get(found);
192                         break;
193                 }
194         }
195         spin_unlock(&config_list_lock);
196         RETURN(found);
197 }
198
199 static
200 struct config_llog_data *do_config_log_add(struct obd_device *obd,
201                                            char *logname,
202                                            int type,
203                                            struct config_llog_instance *cfg,
204                                            struct super_block *sb)
205 {
206         struct config_llog_data *cld;
207         int rc;
208
209         ENTRY;
210
211         CDEBUG(D_MGC, "do adding config log %s-%016lx\n", logname,
212                cfg ? cfg->cfg_instance : 0);
213
214         OBD_ALLOC(cld, sizeof(*cld) + strlen(logname) + 1);
215         if (!cld)
216                 RETURN(ERR_PTR(-ENOMEM));
217
218         rc = mgc_logname2resid(logname, &cld->cld_resid, type);
219         if (rc) {
220                 OBD_FREE(cld, sizeof(*cld) + strlen(cld->cld_logname) + 1);
221                 RETURN(ERR_PTR(rc));
222         }
223
224         strcpy(cld->cld_logname, logname);
225         if (cfg)
226                 cld->cld_cfg = *cfg;
227         else
228                 cld->cld_cfg.cfg_callback = class_config_llog_handler;
229         mutex_init(&cld->cld_lock);
230         cld->cld_cfg.cfg_last_idx = 0;
231         cld->cld_cfg.cfg_flags = 0;
232         cld->cld_cfg.cfg_sb = sb;
233         cld->cld_type = type;
234         atomic_set(&cld->cld_refcount, 1);
235
236         /* Keep the mgc around until we are done */
237         cld->cld_mgcexp = class_export_get(obd->obd_self_export);
238
239         if (cld_is_sptlrpc(cld))
240                 sptlrpc_conf_log_start(logname);
241
242         spin_lock(&config_list_lock);
243         list_add(&cld->cld_list_chain, &config_llog_list);
244         spin_unlock(&config_list_lock);
245
246         if (cld_is_sptlrpc(cld) || cld_is_nodemap(cld) || cld_is_barrier(cld)) {
247                 rc = mgc_process_log(obd, cld);
248                 if (rc && rc != -ENOENT)
249                         CERROR("%s: failed processing log, type %d: rc = %d\n",
250                                obd->obd_name, type, rc);
251         }
252
253         RETURN(cld);
254 }
255
256 static struct config_llog_data *config_recover_log_add(struct obd_device *obd,
257                                         char *fsname,
258                                         struct config_llog_instance *cfg,
259                                         struct super_block *sb)
260 {
261         struct config_llog_instance lcfg = *cfg;
262         struct lustre_sb_info *lsi = s2lsi(sb);
263         struct config_llog_data *cld;
264         char logname[32];
265
266         if (IS_OST(lsi))
267                 return NULL;
268
269         /* for osp-on-ost, see lustre_start_osp() */
270         if (IS_MDT(lsi) && lcfg.cfg_instance)
271                 return NULL;
272
273         /* We have to use different llog for clients and MDTs for DNE,
274          * where only clients are notified if one of DNE server restarts.
275          */
276         LASSERT(strlen(fsname) < sizeof(logname) / 2);
277         strncpy(logname, fsname, sizeof(logname));
278         if (IS_SERVER(lsi)) { /* mdt */
279                 LASSERT(lcfg.cfg_instance == 0);
280                 lcfg.cfg_instance = ll_get_cfg_instance(sb);
281                 strncat(logname, "-mdtir", sizeof(logname));
282         } else {
283                 LASSERT(lcfg.cfg_instance != 0);
284                 strncat(logname, "-cliir", sizeof(logname));
285         }
286
287         cld = do_config_log_add(obd, logname, CONFIG_T_RECOVER, &lcfg, sb);
288         return cld;
289 }
290
291 static struct config_llog_data *config_log_find_or_add(struct obd_device *obd,
292                                 char *logname, struct super_block *sb, int type,
293                                 struct config_llog_instance *cfg)
294 {
295         struct config_llog_instance lcfg = *cfg;
296         struct config_llog_data *cld;
297
298         /* Note class_config_llog_handler() depends on getting "obd" back */
299         lcfg.cfg_instance = sb ? ll_get_cfg_instance(sb) : (unsigned long)obd;
300
301         cld = config_log_find(logname, &lcfg);
302         if (unlikely(cld != NULL))
303                 return cld;
304
305         return do_config_log_add(obd, logname, type, &lcfg, sb);
306 }
307
308 /** Add this log to the list of active logs watched by an MGC.
309  * Active means we're watching for updates.
310  * We have one active log per "mount" - client instance or servername.
311  * Each instance may be at a different point in the log.
312  */
313 static struct config_llog_data *
314 config_log_add(struct obd_device *obd, char *logname,
315                struct config_llog_instance *cfg, struct super_block *sb)
316 {
317         struct lustre_sb_info *lsi = s2lsi(sb);
318         struct config_llog_data *cld = NULL;
319         struct config_llog_data *sptlrpc_cld = NULL;
320         struct config_llog_data *params_cld = NULL;
321         struct config_llog_data *nodemap_cld = NULL;
322         struct config_llog_data *barrier_cld = NULL;
323         char seclogname[32];
324         char *ptr;
325         int rc;
326         bool locked = false;
327         ENTRY;
328
329         CDEBUG(D_MGC, "add config log %s-%016lx\n", logname,
330                cfg->cfg_instance);
331
332         /*
333          * for each regular log, the depended sptlrpc log name is
334          * <fsname>-sptlrpc. multiple regular logs may share one sptlrpc log.
335          */
336         ptr = strrchr(logname, '-');
337         if (ptr == NULL || ptr - logname > 8) {
338                 CERROR("logname %s is too long\n", logname);
339                 RETURN(ERR_PTR(-EINVAL));
340         }
341
342         memcpy(seclogname, logname, ptr - logname);
343         strcpy(seclogname + (ptr - logname), "-sptlrpc");
344
345         if (cfg->cfg_sub_clds & CONFIG_SUB_SPTLRPC) {
346                 sptlrpc_cld = config_log_find_or_add(obd, seclogname, NULL,
347                                                      CONFIG_T_SPTLRPC, cfg);
348                 if (IS_ERR(sptlrpc_cld)) {
349                         CERROR("%s: can't create sptlrpc log %s: rc = %ld\n",
350                                obd->obd_name, seclogname, PTR_ERR(sptlrpc_cld));
351                         RETURN(sptlrpc_cld);
352                 }
353         }
354
355         if (!IS_MGS(lsi) && cfg->cfg_sub_clds & CONFIG_SUB_NODEMAP) {
356                 nodemap_cld = config_log_find_or_add(obd, LUSTRE_NODEMAP_NAME,
357                                                      NULL, CONFIG_T_NODEMAP,
358                                                      cfg);
359                 if (IS_ERR(nodemap_cld)) {
360                         rc = PTR_ERR(nodemap_cld);
361                         CERROR("%s: cannot create nodemap log: rc = %d\n",
362                                obd->obd_name, rc);
363                         GOTO(out_sptlrpc, rc);
364                 }
365         }
366
367         if (cfg->cfg_sub_clds & CONFIG_SUB_PARAMS) {
368                 params_cld = config_log_find_or_add(obd, PARAMS_FILENAME, sb,
369                                                     CONFIG_T_PARAMS, cfg);
370                 if (IS_ERR(params_cld)) {
371                         rc = PTR_ERR(params_cld);
372                         CERROR("%s: can't create params log: rc = %d\n",
373                                obd->obd_name, rc);
374                         GOTO(out_nodemap, rc);
375                 }
376         }
377
378         if (IS_MDT(s2lsi(sb)) && cfg->cfg_sub_clds & CONFIG_SUB_BARRIER) {
379                 snprintf(seclogname + (ptr - logname), sizeof(seclogname) - 1,
380                          "-%s", BARRIER_FILENAME);
381                 barrier_cld = config_log_find_or_add(obd, seclogname, sb,
382                                                      CONFIG_T_BARRIER, cfg);
383                 if (IS_ERR(barrier_cld)) {
384                         rc = PTR_ERR(barrier_cld);
385                         CERROR("%s: can't create barrier log: rc = %d\n",
386                                obd->obd_name, rc);
387                         GOTO(out_params, rc);
388                 }
389         }
390
391         cld = do_config_log_add(obd, logname, CONFIG_T_CONFIG, cfg, sb);
392         if (IS_ERR(cld)) {
393                 rc = PTR_ERR(cld);
394                 CERROR("%s: can't create log: rc = %d\n",
395                        obd->obd_name, rc);
396                 GOTO(out_barrier, rc = PTR_ERR(cld));
397         }
398
399         LASSERT(lsi->lsi_lmd);
400         if (!(lsi->lsi_lmd->lmd_flags & LMD_FLG_NOIR) &&
401             cfg->cfg_sub_clds & CONFIG_SUB_RECOVER) {
402                 struct config_llog_data *recover_cld;
403
404                 ptr = strrchr(seclogname, '-');
405                 if (ptr != NULL) {
406                         *ptr = 0;
407                 } else {
408                         CERROR("%s: sptlrpc log name not correct, %s: "
409                                "rc = %d\n", obd->obd_name, seclogname, -EINVAL);
410                         GOTO(out_cld, rc = -EINVAL);
411                 }
412
413                 recover_cld = config_recover_log_add(obd, seclogname, cfg, sb);
414                 if (IS_ERR(recover_cld)) {
415                         rc = PTR_ERR(recover_cld);
416                         CERROR("%s: can't create recover log: rc = %d\n",
417                                obd->obd_name, rc);
418                         GOTO(out_cld, rc);
419                 }
420
421                 mutex_lock(&cld->cld_lock);
422                 locked = true;
423                 cld->cld_recover = recover_cld;
424         }
425
426         if (!locked)
427                 mutex_lock(&cld->cld_lock);
428         cld->cld_params = params_cld;
429         cld->cld_barrier = barrier_cld;
430         cld->cld_nodemap = nodemap_cld;
431         cld->cld_sptlrpc = sptlrpc_cld;
432         mutex_unlock(&cld->cld_lock);
433
434         RETURN(cld);
435
436 out_cld:
437         config_log_put(cld);
438 out_barrier:
439         config_log_put(barrier_cld);
440 out_params:
441         config_log_put(params_cld);
442 out_nodemap:
443         config_log_put(nodemap_cld);
444 out_sptlrpc:
445         config_log_put(sptlrpc_cld);
446
447         return ERR_PTR(rc);
448 }
449
450 static inline void config_mark_cld_stop(struct config_llog_data *cld)
451 {
452         if (cld) {
453                 mutex_lock(&cld->cld_lock);
454                 spin_lock(&config_list_lock);
455                 cld->cld_stopping = 1;
456                 spin_unlock(&config_list_lock);
457                 mutex_unlock(&cld->cld_lock);
458         }
459 }
460
461 /** Stop watching for updates on this log.
462  */
463 static int config_log_end(char *logname, struct config_llog_instance *cfg)
464 {
465         struct config_llog_data *cld;
466         struct config_llog_data *cld_sptlrpc = NULL;
467         struct config_llog_data *cld_params = NULL;
468         struct config_llog_data *cld_recover = NULL;
469         struct config_llog_data *cld_nodemap = NULL;
470         struct config_llog_data *cld_barrier = NULL;
471         int rc = 0;
472
473         ENTRY;
474
475         cld = config_log_find(logname, cfg);
476         if (cld == NULL)
477                 RETURN(-ENOENT);
478
479         mutex_lock(&cld->cld_lock);
480         /*
481          * if cld_stopping is set, it means we didn't start the log thus
482          * not owning the start ref. this can happen after previous umount:
483          * the cld still hanging there waiting for lock cancel, and we
484          * remount again but failed in the middle and call log_end without
485          * calling start_log.
486          */
487         if (unlikely(cld->cld_stopping)) {
488                 mutex_unlock(&cld->cld_lock);
489                 /* drop the ref from the find */
490                 config_log_put(cld);
491                 RETURN(rc);
492         }
493
494         spin_lock(&config_list_lock);
495         cld->cld_stopping = 1;
496         spin_unlock(&config_list_lock);
497
498         cld_recover = cld->cld_recover;
499         cld->cld_recover = NULL;
500         cld_params = cld->cld_params;
501         cld->cld_params = NULL;
502         cld_nodemap = cld->cld_nodemap;
503         cld->cld_nodemap = NULL;
504         cld_barrier = cld->cld_barrier;
505         cld->cld_barrier = NULL;
506         cld_sptlrpc = cld->cld_sptlrpc;
507         cld->cld_sptlrpc = NULL;
508         mutex_unlock(&cld->cld_lock);
509
510         config_mark_cld_stop(cld_recover);
511         config_log_put(cld_recover);
512
513         config_mark_cld_stop(cld_params);
514         config_log_put(cld_params);
515
516         /* don't set cld_stopping on nm lock as other targets may be active */
517         config_log_put(cld_nodemap);
518
519         if (cld_barrier) {
520                 mutex_lock(&cld_barrier->cld_lock);
521                 cld_barrier->cld_stopping = 1;
522                 mutex_unlock(&cld_barrier->cld_lock);
523                 config_log_put(cld_barrier);
524         }
525
526         config_log_put(cld_sptlrpc);
527
528         /* drop the ref from the find */
529         config_log_put(cld);
530         /* drop the start ref */
531         config_log_put(cld);
532
533         CDEBUG(D_MGC, "end config log %s (%d)\n", logname ? logname : "client",
534                rc);
535         RETURN(rc);
536 }
537
538 int lprocfs_mgc_rd_ir_state(struct seq_file *m, void *data)
539 {
540         struct obd_device       *obd = data;
541         struct obd_import       *imp;
542         struct obd_connect_data *ocd;
543         struct config_llog_data *cld;
544
545         ENTRY;
546         LASSERT(obd);
547         LPROCFS_CLIMP_CHECK(obd);
548         imp = obd->u.cli.cl_import;
549         ocd = &imp->imp_connect_data;
550
551         seq_printf(m, "imperative_recovery: %s\n",
552                    OCD_HAS_FLAG(ocd, IMP_RECOV) ? "ENABLED" : "DISABLED");
553         seq_printf(m, "client_state:\n");
554
555         spin_lock(&config_list_lock);
556         list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
557                 if (cld->cld_recover == NULL)
558                         continue;
559                 seq_printf(m,  "    - { client: %s, nidtbl_version: %u }\n",
560                            cld->cld_logname,
561                            cld->cld_recover->cld_cfg.cfg_last_idx);
562         }
563         spin_unlock(&config_list_lock);
564
565         LPROCFS_CLIMP_EXIT(obd);
566         RETURN(0);
567 }
568
569 /* reenqueue any lost locks */
570 #define RQ_RUNNING      0x1
571 #define RQ_NOW          0x2
572 #define RQ_LATER        0x4
573 #define RQ_STOP         0x8
574 #define RQ_PRECLEANUP   0x10
575 static int                    rq_state = 0;
576 static wait_queue_head_t      rq_waitq;
577 static DECLARE_COMPLETION(rq_exit);
578 static DECLARE_COMPLETION(rq_start);
579
580 static void do_requeue(struct config_llog_data *cld)
581 {
582         int rc = 0;
583         ENTRY;
584
585         LASSERT(atomic_read(&cld->cld_refcount) > 0);
586
587         /*
588          * Do not run mgc_process_log on a disconnected export or an
589          * export which is being disconnected. Take the client
590          * semaphore to make the check non-racy.
591          */
592         down_read_nested(&cld->cld_mgcexp->exp_obd->u.cli.cl_sem,
593                          OBD_CLI_SEM_MGC);
594         if (cld->cld_mgcexp->exp_obd->u.cli.cl_conn_count != 0) {
595                 CDEBUG(D_MGC, "updating log %s\n", cld->cld_logname);
596                 rc = mgc_process_log(cld->cld_mgcexp->exp_obd, cld);
597                 if (rc && rc != -ENOENT)
598                         CERROR("failed processing log: %d\n", rc);
599         } else {
600                 CDEBUG(D_MGC, "disconnecting, won't update log %s\n",
601                        cld->cld_logname);
602         }
603         up_read(&cld->cld_mgcexp->exp_obd->u.cli.cl_sem);
604
605         EXIT;
606 }
607
608 /* this timeout represents how many seconds MGC should wait before
609  * requeue config and recover lock to the MGS. We need to randomize this
610  * in order to not flood the MGS.
611  */
612 #define MGC_TIMEOUT_MIN_SECONDS   5
613 #define MGC_TIMEOUT_RAND_CENTISEC 500
614
615 static int mgc_requeue_thread(void *data)
616 {
617         int rc = 0;
618         bool first = true;
619         ENTRY;
620
621         CDEBUG(D_MGC, "Starting requeue thread\n");
622
623         /* Keep trying failed locks periodically */
624         spin_lock(&config_list_lock);
625         rq_state |= RQ_RUNNING;
626         while (!(rq_state & RQ_STOP)) {
627                 struct l_wait_info lwi;
628                 struct config_llog_data *cld, *cld_prev;
629                 int rand = prandom_u32_max(MGC_TIMEOUT_RAND_CENTISEC);
630                 int to;
631
632                 /* Any new or requeued lostlocks will change the state */
633                 rq_state &= ~(RQ_NOW | RQ_LATER);
634                 spin_unlock(&config_list_lock);
635
636                 if (first) {
637                         first = false;
638                         complete(&rq_start);
639                 }
640
641                 /* Always wait a few seconds to allow the server who
642                    caused the lock revocation to finish its setup, plus some
643                    random so everyone doesn't try to reconnect at once. */
644                 to = cfs_time_seconds(MGC_TIMEOUT_MIN_SECONDS * 100 + rand);
645                 /* rand is centi-seconds */
646                 lwi = LWI_TIMEOUT(to / 100, NULL, NULL);
647                 l_wait_event(rq_waitq, rq_state & (RQ_STOP | RQ_PRECLEANUP),
648                              &lwi);
649
650                 /*
651                  * iterate & processing through the list. for each cld, process
652                  * its depending sptlrpc cld firstly (if any) and then itself.
653                  *
654                  * it's guaranteed any item in the list must have
655                  * reference > 0; and if cld_lostlock is set, at
656                  * least one reference is taken by the previous enqueue.
657                  */
658                 cld_prev = NULL;
659
660                 spin_lock(&config_list_lock);
661                 rq_state &= ~RQ_PRECLEANUP;
662                 list_for_each_entry(cld, &config_llog_list,
663                                     cld_list_chain) {
664                         if (!cld->cld_lostlock || cld->cld_stopping)
665                                 continue;
666
667                         /* hold reference to avoid being freed during
668                          * subsequent processing. */
669                         config_log_get(cld);
670                         cld->cld_lostlock = 0;
671                         spin_unlock(&config_list_lock);
672
673                         config_log_put(cld_prev);
674                         cld_prev = cld;
675
676                         if (likely(!(rq_state & RQ_STOP))) {
677                                 do_requeue(cld);
678                                 spin_lock(&config_list_lock);
679                         } else {
680                                 spin_lock(&config_list_lock);
681                                 break;
682                         }
683                 }
684                 spin_unlock(&config_list_lock);
685                 config_log_put(cld_prev);
686
687                 /* Wait a bit to see if anyone else needs a requeue */
688                 lwi = (struct l_wait_info) { 0 };
689                 l_wait_event(rq_waitq, rq_state & (RQ_NOW | RQ_STOP),
690                              &lwi);
691                 spin_lock(&config_list_lock);
692         }
693
694         /* spinlock and while guarantee RQ_NOW and RQ_LATER are not set */
695         rq_state &= ~RQ_RUNNING;
696         spin_unlock(&config_list_lock);
697
698         complete(&rq_exit);
699
700         CDEBUG(D_MGC, "Ending requeue thread\n");
701         RETURN(rc);
702 }
703
704 /* Add a cld to the list to requeue.  Start the requeue thread if needed.
705    We are responsible for dropping the config log reference from here on out. */
706 static void mgc_requeue_add(struct config_llog_data *cld)
707 {
708         bool wakeup = false;
709         ENTRY;
710
711         CDEBUG(D_INFO, "log %s: requeue (r=%d sp=%d st=%x)\n",
712                 cld->cld_logname, atomic_read(&cld->cld_refcount),
713                 cld->cld_stopping, rq_state);
714         LASSERT(atomic_read(&cld->cld_refcount) > 0);
715
716         mutex_lock(&cld->cld_lock);
717         spin_lock(&config_list_lock);
718         if (!(rq_state & RQ_STOP) && !cld->cld_stopping && !cld->cld_lostlock) {
719                 cld->cld_lostlock = 1;
720                 rq_state |= RQ_NOW;
721                 wakeup = true;
722         }
723         spin_unlock(&config_list_lock);
724         mutex_unlock(&cld->cld_lock);
725         if (wakeup)
726                 wake_up(&rq_waitq);
727
728         EXIT;
729 }
730
731 /********************** class fns **********************/
732 static int mgc_local_llog_init(const struct lu_env *env,
733                                struct obd_device *obd,
734                                struct obd_device *disk)
735 {
736         struct llog_ctxt        *ctxt;
737         int                      rc;
738
739         ENTRY;
740
741         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_CONFIG_ORIG_CTXT, disk,
742                         &llog_osd_ops);
743         if (rc)
744                 RETURN(rc);
745
746         ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
747         LASSERT(ctxt);
748         ctxt->loc_dir = obd->u.cli.cl_mgc_configs_dir;
749         llog_ctxt_put(ctxt);
750
751         RETURN(0);
752 }
753
754 static int mgc_local_llog_fini(const struct lu_env *env,
755                                struct obd_device *obd)
756 {
757         struct llog_ctxt *ctxt;
758
759         ENTRY;
760
761         ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
762         llog_cleanup(env, ctxt);
763
764         RETURN(0);
765 }
766
767 static int mgc_fs_setup(const struct lu_env *env, struct obd_device *obd,
768                         struct super_block *sb)
769 {
770         struct lustre_sb_info   *lsi = s2lsi(sb);
771         struct client_obd       *cli = &obd->u.cli;
772         struct lu_fid            rfid, fid;
773         struct dt_object        *root, *dto;
774         int                      rc = 0;
775
776         ENTRY;
777
778         LASSERT(lsi);
779         LASSERT(lsi->lsi_dt_dev);
780
781         /* The mgc fs exclusion mutex. Only one fs can be setup at a time. */
782         mutex_lock(&cli->cl_mgc_mutex);
783
784         /* Setup the configs dir */
785         fid.f_seq = FID_SEQ_LOCAL_NAME;
786         fid.f_oid = 1;
787         fid.f_ver = 0;
788         rc = local_oid_storage_init(env, lsi->lsi_dt_dev, &fid,
789                                     &cli->cl_mgc_los);
790         if (rc)
791                 RETURN(rc);
792
793         rc = dt_root_get(env, lsi->lsi_dt_dev, &rfid);
794         if (rc)
795                 GOTO(out_los, rc);
796
797         root = dt_locate_at(env, lsi->lsi_dt_dev, &rfid,
798                             &cli->cl_mgc_los->los_dev->dd_lu_dev, NULL);
799         if (unlikely(IS_ERR(root)))
800                 GOTO(out_los, rc = PTR_ERR(root));
801
802         dto = local_file_find_or_create(env, cli->cl_mgc_los, root,
803                                         MOUNT_CONFIGS_DIR,
804                                         S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO);
805         dt_object_put_nocache(env, root);
806         if (IS_ERR(dto))
807                 GOTO(out_los, rc = PTR_ERR(dto));
808
809         cli->cl_mgc_configs_dir = dto;
810
811         LASSERT(lsi->lsi_osd_exp->exp_obd->obd_lvfs_ctxt.dt);
812         rc = mgc_local_llog_init(env, obd, lsi->lsi_osd_exp->exp_obd);
813         if (rc)
814                 GOTO(out_llog, rc);
815
816         /* We take an obd ref to insure that we can't get to mgc_cleanup
817          * without calling mgc_fs_cleanup first. */
818         class_incref(obd, "mgc_fs", obd);
819
820         /* We keep the cl_mgc_sem until mgc_fs_cleanup */
821         EXIT;
822 out_llog:
823         if (rc) {
824                 dt_object_put(env, cli->cl_mgc_configs_dir);
825                 cli->cl_mgc_configs_dir = NULL;
826         }
827 out_los:
828         if (rc < 0) {
829                 local_oid_storage_fini(env, cli->cl_mgc_los);
830                 cli->cl_mgc_los = NULL;
831                 mutex_unlock(&cli->cl_mgc_mutex);
832         }
833         return rc;
834 }
835
836 static int mgc_fs_cleanup(const struct lu_env *env, struct obd_device *obd)
837 {
838         struct client_obd       *cli = &obd->u.cli;
839         ENTRY;
840
841         LASSERT(cli->cl_mgc_los != NULL);
842
843         mgc_local_llog_fini(env, obd);
844
845         dt_object_put_nocache(env, cli->cl_mgc_configs_dir);
846         cli->cl_mgc_configs_dir = NULL;
847
848         local_oid_storage_fini(env, cli->cl_mgc_los);
849         cli->cl_mgc_los = NULL;
850
851         class_decref(obd, "mgc_fs", obd);
852         mutex_unlock(&cli->cl_mgc_mutex);
853
854         RETURN(0);
855 }
856
857 static int mgc_llog_init(const struct lu_env *env, struct obd_device *obd)
858 {
859         struct llog_ctxt        *ctxt;
860         int                      rc;
861
862         ENTRY;
863
864         /* setup only remote ctxt, the local disk context is switched per each
865          * filesystem during mgc_fs_setup() */
866         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_CONFIG_REPL_CTXT, obd,
867                         &llog_client_ops);
868         if (rc)
869                 RETURN(rc);
870
871         ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
872         LASSERT(ctxt);
873
874         llog_initiator_connect(ctxt);
875         llog_ctxt_put(ctxt);
876
877         RETURN(0);
878 }
879
880 static int mgc_llog_fini(const struct lu_env *env, struct obd_device *obd)
881 {
882         struct llog_ctxt *ctxt;
883
884         ENTRY;
885
886         ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
887         if (ctxt)
888                 llog_cleanup(env, ctxt);
889
890         RETURN(0);
891 }
892
893
894 static atomic_t mgc_count = ATOMIC_INIT(0);
895 static int mgc_precleanup(struct obd_device *obd)
896 {
897         int     rc = 0;
898         int     temp;
899         ENTRY;
900
901         if (atomic_dec_and_test(&mgc_count)) {
902                 LASSERT(rq_state & RQ_RUNNING);
903                 /* stop requeue thread */
904                 temp = RQ_STOP;
905         } else {
906                 /* wakeup requeue thread to clean our cld */
907                 temp = RQ_NOW | RQ_PRECLEANUP;
908         }
909
910         spin_lock(&config_list_lock);
911         rq_state |= temp;
912         spin_unlock(&config_list_lock);
913         wake_up(&rq_waitq);
914
915         if (temp & RQ_STOP)
916                 wait_for_completion(&rq_exit);
917         obd_cleanup_client_import(obd);
918
919         rc = mgc_llog_fini(NULL, obd);
920         if (rc != 0)
921                 CERROR("failed to cleanup llogging subsystems\n");
922
923         RETURN(rc);
924 }
925
926 static int mgc_cleanup(struct obd_device *obd)
927 {
928         int rc;
929         ENTRY;
930
931         /* COMPAT_146 - old config logs may have added profiles we don't
932            know about */
933         if (obd->obd_type->typ_refcnt <= 1)
934                 /* Only for the last mgc */
935                 class_del_profiles();
936
937         lprocfs_obd_cleanup(obd);
938         ptlrpcd_decref();
939
940         rc = client_obd_cleanup(obd);
941         RETURN(rc);
942 }
943
944 static int mgc_setup(struct obd_device *obd, struct lustre_cfg *lcfg)
945 {
946         struct task_struct      *task;
947         int                      rc;
948         ENTRY;
949
950         rc = ptlrpcd_addref();
951         if (rc < 0)
952                 RETURN(rc);
953
954         rc = client_obd_setup(obd, lcfg);
955         if (rc)
956                 GOTO(err_decref, rc);
957
958         rc = mgc_llog_init(NULL, obd);
959         if (rc) {
960                 CERROR("failed to setup llogging subsystems\n");
961                 GOTO(err_cleanup, rc);
962         }
963
964         rc = mgc_tunables_init(obd);
965         if (rc)
966                 GOTO(err_sysfs, rc);
967
968         if (atomic_inc_return(&mgc_count) == 1) {
969                 rq_state = 0;
970                 init_waitqueue_head(&rq_waitq);
971
972                 /* start requeue thread */
973                 task = kthread_run(mgc_requeue_thread, NULL, "ll_cfg_requeue");
974                 if (IS_ERR(task)) {
975                         rc = PTR_ERR(task);
976                         CERROR("%s: cannot start requeue thread: rc = %d; "
977                                "no more log updates\n",
978                                obd->obd_name, rc);
979                         GOTO(err_sysfs, rc);
980                 }
981                 /* rc is the task_struct pointer of mgc_requeue_thread. */
982                 rc = 0;
983                 wait_for_completion(&rq_start);
984         }
985
986         RETURN(rc);
987
988 err_sysfs:
989         lprocfs_obd_cleanup(obd);
990 err_cleanup:
991         client_obd_cleanup(obd);
992 err_decref:
993         ptlrpcd_decref();
994         RETURN(rc);
995 }
996
997 /* based on ll_mdc_blocking_ast */
998 static int mgc_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
999                             void *data, int flag)
1000 {
1001         struct lustre_handle lockh;
1002         struct config_llog_data *cld = (struct config_llog_data *)data;
1003         int rc = 0;
1004         ENTRY;
1005
1006         switch (flag) {
1007         case LDLM_CB_BLOCKING:
1008                 /* mgs wants the lock, give it up... */
1009                 LDLM_DEBUG(lock, "MGC blocking CB");
1010                 ldlm_lock2handle(lock, &lockh);
1011                 rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
1012                 break;
1013         case LDLM_CB_CANCELING:
1014                 /* We've given up the lock, prepare ourselves to update. */
1015                 LDLM_DEBUG(lock, "MGC cancel CB");
1016
1017                 CDEBUG(D_MGC, "Lock res "DLDLMRES" (%.8s)\n",
1018                        PLDLMRES(lock->l_resource),
1019                        (char *)&lock->l_resource->lr_name.name[0]);
1020
1021                 if (!cld) {
1022                         CDEBUG(D_INFO, "missing data, won't requeue\n");
1023                         break;
1024                 }
1025
1026                 /* held at mgc_process_log(). */
1027                 LASSERT(atomic_read(&cld->cld_refcount) > 0);
1028
1029                 lock->l_ast_data = NULL;
1030                 /* Are we done with this log? */
1031                 if (cld->cld_stopping) {
1032                         CDEBUG(D_MGC, "log %s: stopping, won't requeue\n",
1033                                 cld->cld_logname);
1034                         config_log_put(cld);
1035                         break;
1036                 }
1037                 /* Make sure not to re-enqueue when the mgc is stopping
1038                    (we get called from client_disconnect_export) */
1039                 if (lock->l_conn_export == NULL ||
1040                     lock->l_conn_export->exp_obd->u.cli.cl_conn_count == 0) {
1041                         CDEBUG(D_MGC, "log %.8s: disconnecting, won't requeue\n",
1042                                 cld->cld_logname);
1043                         config_log_put(cld);
1044                         break;
1045                 }
1046
1047                 /* Re-enqueue now */
1048                 mgc_requeue_add(cld);
1049                 config_log_put(cld);
1050                 break;
1051         default:
1052                 LBUG();
1053         }
1054
1055         RETURN(rc);
1056 }
1057
1058 /* Not sure where this should go... */
1059 /* This is the timeout value for MGS_CONNECT request plus a ping interval, such
1060  * that we can have a chance to try the secondary MGS if any. */
1061 #define  MGC_ENQUEUE_LIMIT (INITIAL_CONNECT_TIMEOUT + (AT_OFF ? 0 : at_min) \
1062                                 + PING_INTERVAL)
1063 #define  MGC_TARGET_REG_LIMIT 10
1064 #define  MGC_TARGET_REG_LIMIT_MAX RECONNECT_DELAY_MAX
1065 #define  MGC_SEND_PARAM_LIMIT 10
1066
1067 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 13, 53, 0)
1068 /* Send parameter to MGS*/
1069 static int mgc_set_mgs_param(struct obd_export *exp,
1070                              struct mgs_send_param *msp)
1071 {
1072         struct ptlrpc_request *req;
1073         struct mgs_send_param *req_msp, *rep_msp;
1074         int rc;
1075         ENTRY;
1076
1077         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1078                                         &RQF_MGS_SET_INFO, LUSTRE_MGS_VERSION,
1079                                         MGS_SET_INFO);
1080         if (!req)
1081                 RETURN(-ENOMEM);
1082
1083         req_msp = req_capsule_client_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
1084         if (!req_msp) {
1085                 ptlrpc_req_finished(req);
1086                 RETURN(-ENOMEM);
1087         }
1088
1089         memcpy(req_msp, msp, sizeof(*req_msp));
1090         ptlrpc_request_set_replen(req);
1091
1092         /* Limit how long we will wait for the enqueue to complete */
1093         req->rq_delay_limit = MGC_SEND_PARAM_LIMIT;
1094         rc = ptlrpc_queue_wait(req);
1095         if (!rc) {
1096                 rep_msp = req_capsule_server_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
1097                 memcpy(msp, rep_msp, sizeof(*rep_msp));
1098         }
1099
1100         ptlrpc_req_finished(req);
1101
1102         RETURN(rc);
1103 }
1104 #endif
1105
1106 /* Take a config lock so we can get cancel notifications */
1107 static int mgc_enqueue(struct obd_export *exp, enum ldlm_type type,
1108                        union ldlm_policy_data *policy, enum ldlm_mode mode,
1109                        __u64 *flags, ldlm_glimpse_callback glimpse_callback,
1110                        void *data, __u32 lvb_len, void *lvb_swabber,
1111                        struct lustre_handle *lockh)
1112 {
1113         struct config_llog_data *cld = (struct config_llog_data *)data;
1114         struct ldlm_enqueue_info einfo = {
1115                 .ei_type        = type,
1116                 .ei_mode        = mode,
1117                 .ei_cb_bl       = mgc_blocking_ast,
1118                 .ei_cb_cp       = ldlm_completion_ast,
1119                 .ei_cb_gl       = glimpse_callback,
1120         };
1121         struct ptlrpc_request *req;
1122         int short_limit = cld_is_sptlrpc(cld);
1123         int rc;
1124         ENTRY;
1125
1126         CDEBUG(D_MGC, "Enqueue for %s (res %#llx)\n", cld->cld_logname,
1127                cld->cld_resid.name[0]);
1128
1129         /* We need a callback for every lockholder, so don't try to
1130            ldlm_lock_match (see rev 1.1.2.11.2.47) */
1131         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1132                                         &RQF_LDLM_ENQUEUE, LUSTRE_DLM_VERSION,
1133                                         LDLM_ENQUEUE);
1134         if (req == NULL)
1135                 RETURN(-ENOMEM);
1136
1137         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER, 0);
1138         ptlrpc_request_set_replen(req);
1139
1140         /* check if this is server or client */
1141         if (cld->cld_cfg.cfg_sb) {
1142                 struct lustre_sb_info *lsi = s2lsi(cld->cld_cfg.cfg_sb);
1143                 if (lsi && IS_SERVER(lsi))
1144                         short_limit = 1;
1145         }
1146         /* Limit how long we will wait for the enqueue to complete */
1147         req->rq_delay_limit = short_limit ? 5 : MGC_ENQUEUE_LIMIT;
1148         rc = ldlm_cli_enqueue(exp, &req, &einfo, &cld->cld_resid, NULL, flags,
1149                               NULL, 0, LVB_T_NONE, lockh, 0);
1150         /* A failed enqueue should still call the mgc_blocking_ast,
1151            where it will be requeued if needed ("grant failed"). */
1152         ptlrpc_req_finished(req);
1153         RETURN(rc);
1154 }
1155
1156 static int mgc_cancel(struct obd_export *exp, enum ldlm_mode mode,
1157                       struct lustre_handle *lockh)
1158 {
1159         ENTRY;
1160
1161         ldlm_lock_decref(lockh, mode);
1162
1163         RETURN(0);
1164 }
1165
1166 static void mgc_notify_active(struct obd_device *unused)
1167 {
1168         /* wakeup mgc_requeue_thread to requeue mgc lock */
1169         spin_lock(&config_list_lock);
1170         rq_state |= RQ_NOW;
1171         spin_unlock(&config_list_lock);
1172         wake_up(&rq_waitq);
1173
1174         /* TODO: Help the MGS rebuild nidtbl. -jay */
1175 }
1176
1177 /* Send target_reg message to MGS */
1178 static int mgc_target_register(struct obd_export *exp,
1179                                struct mgs_target_info *mti)
1180 {
1181         struct ptlrpc_request  *req;
1182         struct mgs_target_info *req_mti, *rep_mti;
1183         int                     rc;
1184         ENTRY;
1185
1186         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1187                                         &RQF_MGS_TARGET_REG, LUSTRE_MGS_VERSION,
1188                                         MGS_TARGET_REG);
1189         if (req == NULL)
1190                 RETURN(-ENOMEM);
1191
1192         req_mti = req_capsule_client_get(&req->rq_pill, &RMF_MGS_TARGET_INFO);
1193         if (!req_mti) {
1194                 ptlrpc_req_finished(req);
1195                 RETURN(-ENOMEM);
1196         }
1197
1198         memcpy(req_mti, mti, sizeof(*req_mti));
1199         ptlrpc_request_set_replen(req);
1200         CDEBUG(D_MGC, "register %s\n", mti->mti_svname);
1201         /* Limit how long we will wait for the enqueue to complete */
1202         req->rq_delay_limit = MGC_TARGET_REG_LIMIT;
1203
1204         /* if the target needs to regenerate the config log in MGS, it's better
1205          * to use some longer limit to let MGC have time to change connection to
1206          * another MGS (or try again with the same MGS) for the target (server)
1207          * will fail and exit if the request expired due to delay limit. */
1208         if (mti->mti_flags & (LDD_F_UPDATE | LDD_F_NEED_INDEX))
1209                 req->rq_delay_limit = MGC_TARGET_REG_LIMIT_MAX;
1210
1211         rc = ptlrpc_queue_wait(req);
1212         if (!rc) {
1213                 rep_mti = req_capsule_server_get(&req->rq_pill,
1214                                                  &RMF_MGS_TARGET_INFO);
1215                 memcpy(mti, rep_mti, sizeof(*rep_mti));
1216                 CDEBUG(D_MGC, "register %s got index = %d\n",
1217                        mti->mti_svname, mti->mti_stripe_index);
1218         }
1219         ptlrpc_req_finished(req);
1220
1221         RETURN(rc);
1222 }
1223
1224 static int mgc_set_info_async(const struct lu_env *env, struct obd_export *exp,
1225                               u32 keylen, void *key,
1226                               u32 vallen, void *val,
1227                               struct ptlrpc_request_set *set)
1228 {
1229         int rc = -EINVAL;
1230         ENTRY;
1231
1232         /* Turn off initial_recov after we try all backup servers once */
1233         if (KEY_IS(KEY_INIT_RECOV_BACKUP)) {
1234                 struct obd_import *imp = class_exp2cliimp(exp);
1235                 int value;
1236                 if (vallen != sizeof(int))
1237                         RETURN(-EINVAL);
1238                 value = *(int *)val;
1239                 CDEBUG(D_MGC, "InitRecov %s %d/d%d:i%d:r%d:or%d:%s\n",
1240                        imp->imp_obd->obd_name, value,
1241                        imp->imp_deactive, imp->imp_invalid,
1242                        imp->imp_replayable, imp->imp_obd->obd_replayable,
1243                        ptlrpc_import_state_name(imp->imp_state));
1244                 /* Resurrect the import immediately if
1245                  * 1. we previously got disconnected,
1246                  * 2. value > 1 (at the same node with MGS)
1247                  * */
1248                 if (imp->imp_state == LUSTRE_IMP_DISCON || value > 1)
1249                         ptlrpc_reconnect_import(imp);
1250
1251                 RETURN(0);
1252         }
1253
1254         /* FIXME move this to mgc_process_config */
1255         if (KEY_IS(KEY_REGISTER_TARGET)) {
1256                 struct mgs_target_info *mti;
1257                 if (vallen != sizeof(struct mgs_target_info))
1258                         RETURN(-EINVAL);
1259                 mti = (struct mgs_target_info *)val;
1260                 CDEBUG(D_MGC, "register_target %s %#x\n",
1261                        mti->mti_svname, mti->mti_flags);
1262                 rc =  mgc_target_register(exp, mti);
1263                 RETURN(rc);
1264         }
1265         if (KEY_IS(KEY_SET_FS)) {
1266                 struct super_block *sb = (struct super_block *)val;
1267
1268                 if (vallen != sizeof(struct super_block))
1269                         RETURN(-EINVAL);
1270
1271                 rc = mgc_fs_setup(env, exp->exp_obd, sb);
1272                 RETURN(rc);
1273         }
1274         if (KEY_IS(KEY_CLEAR_FS)) {
1275                 if (vallen != 0)
1276                         RETURN(-EINVAL);
1277                 rc = mgc_fs_cleanup(env, exp->exp_obd);
1278                 RETURN(rc);
1279         }
1280 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 13, 53, 0)
1281         if (KEY_IS(KEY_SET_INFO)) {
1282                 struct mgs_send_param *msp;
1283
1284                 msp = (struct mgs_send_param *)val;
1285                 rc =  mgc_set_mgs_param(exp, msp);
1286                 RETURN(rc);
1287         }
1288 #endif
1289         if (KEY_IS(KEY_MGSSEC)) {
1290                 struct client_obd     *cli = &exp->exp_obd->u.cli;
1291                 struct sptlrpc_flavor  flvr;
1292
1293                 /*
1294                  * empty string means using current flavor, if which haven't
1295                  * been set yet, set it as null.
1296                  *
1297                  * if flavor has been set previously, check the asking flavor
1298                  * must match the existing one.
1299                  */
1300                 if (vallen == 0) {
1301                         if (cli->cl_flvr_mgc.sf_rpc != SPTLRPC_FLVR_INVALID)
1302                                 RETURN(0);
1303                         val = "null";
1304                         vallen = 4;
1305                 }
1306
1307                 rc = sptlrpc_parse_flavor(val, &flvr);
1308                 if (rc) {
1309                         CERROR("invalid sptlrpc flavor %s to MGS\n",
1310                                (char *) val);
1311                         RETURN(rc);
1312                 }
1313
1314                 /*
1315                  * caller already hold a mutex
1316                  */
1317                 if (cli->cl_flvr_mgc.sf_rpc == SPTLRPC_FLVR_INVALID) {
1318                         cli->cl_flvr_mgc = flvr;
1319                 } else if (memcmp(&cli->cl_flvr_mgc, &flvr,
1320                                   sizeof(flvr)) != 0) {
1321                         char    str[20];
1322
1323                         sptlrpc_flavor2name(&cli->cl_flvr_mgc,
1324                                             str, sizeof(str));
1325                         LCONSOLE_ERROR("asking sptlrpc flavor %s to MGS but "
1326                                        "currently %s is in use\n",
1327                                        (char *) val, str);
1328                         rc = -EPERM;
1329                 }
1330                 RETURN(rc);
1331         }
1332
1333         RETURN(rc);
1334 }
1335
1336 static int mgc_get_info(const struct lu_env *env, struct obd_export *exp,
1337                         __u32 keylen, void *key, __u32 *vallen, void *val)
1338 {
1339         int rc = -EINVAL;
1340
1341         if (KEY_IS(KEY_CONN_DATA)) {
1342                 struct obd_import *imp = class_exp2cliimp(exp);
1343                 struct obd_connect_data *data = val;
1344
1345                 if (*vallen == sizeof(*data)) {
1346                         *data = imp->imp_connect_data;
1347                         rc = 0;
1348                 }
1349         }
1350
1351         return rc;
1352 }
1353
1354 static int mgc_import_event(struct obd_device *obd,
1355                             struct obd_import *imp,
1356                             enum obd_import_event event)
1357 {
1358         int rc = 0;
1359
1360         LASSERT(imp->imp_obd == obd);
1361         CDEBUG(D_MGC, "import event %#x\n", event);
1362
1363         switch (event) {
1364         case IMP_EVENT_DISCON:
1365                 /* MGC imports should not wait for recovery */
1366                 if (OCD_HAS_FLAG(&imp->imp_connect_data, IMP_RECOV))
1367                         ptlrpc_pinger_ir_down();
1368                 break;
1369         case IMP_EVENT_INACTIVE:
1370                 break;
1371         case IMP_EVENT_INVALIDATE: {
1372                 struct ldlm_namespace *ns = obd->obd_namespace;
1373                 ldlm_namespace_cleanup(ns, LDLM_FL_LOCAL_ONLY);
1374                 break;
1375         }
1376         case IMP_EVENT_ACTIVE:
1377                 CDEBUG(D_INFO, "%s: Reactivating import\n", obd->obd_name);
1378                 /* Clearing obd_no_recov allows us to continue pinging */
1379                 obd->obd_no_recov = 0;
1380                 mgc_notify_active(obd);
1381                 if (OCD_HAS_FLAG(&imp->imp_connect_data, IMP_RECOV))
1382                         ptlrpc_pinger_ir_up();
1383                 break;
1384         case IMP_EVENT_OCD:
1385                 break;
1386         case IMP_EVENT_DEACTIVATE:
1387         case IMP_EVENT_ACTIVATE:
1388                 break;
1389         default:
1390                 CERROR("Unknown import event %#x\n", event);
1391                 LBUG();
1392         }
1393         RETURN(rc);
1394 }
1395
1396 enum {
1397         CONFIG_READ_NRPAGES_INIT = 1 << (20 - PAGE_SHIFT),
1398         CONFIG_READ_NRPAGES      = 4
1399 };
1400
1401 static int mgc_apply_recover_logs(struct obd_device *mgc,
1402                                   struct config_llog_data *cld,
1403                                   __u64 max_version,
1404                                   void *data, int datalen, bool mne_swab)
1405 {
1406         struct config_llog_instance *cfg = &cld->cld_cfg;
1407         struct lustre_sb_info *lsi = s2lsi(cfg->cfg_sb);
1408         struct mgs_nidtbl_entry *entry;
1409         struct lustre_cfg *lcfg;
1410         struct lustre_cfg_bufs bufs;
1411         u64 prev_version = 0;
1412         char *inst;
1413         char *buf;
1414         int bufsz;
1415         int pos = 0;
1416         int rc  = 0;
1417         int off = 0;
1418
1419         ENTRY;
1420         LASSERT(cfg->cfg_instance != 0);
1421         LASSERT(ll_get_cfg_instance(cfg->cfg_sb) == cfg->cfg_instance);
1422
1423         OBD_ALLOC(inst, PAGE_SIZE);
1424         if (inst == NULL)
1425                 RETURN(-ENOMEM);
1426
1427         if (!IS_SERVER(lsi)) {
1428                 pos = snprintf(inst, PAGE_SIZE, "%016lx", cfg->cfg_instance);
1429                 if (pos >= PAGE_SIZE) {
1430                         OBD_FREE(inst, PAGE_SIZE);
1431                         return -E2BIG;
1432                 }
1433 #ifdef HAVE_SERVER_SUPPORT
1434         } else {
1435                 LASSERT(IS_MDT(lsi));
1436                 rc = server_name2svname(lsi->lsi_svname, inst, NULL,
1437                                         PAGE_SIZE);
1438                 if (rc) {
1439                         OBD_FREE(inst, PAGE_SIZE);
1440                         RETURN(-EINVAL);
1441                 }
1442                 pos = strlen(inst);
1443 #endif /* HAVE_SERVER_SUPPORT */
1444         }
1445
1446         ++pos;
1447         buf   = inst + pos;
1448         bufsz = PAGE_SIZE - pos;
1449
1450         while (datalen > 0) {
1451                 int   entry_len = sizeof(*entry);
1452                 int   is_ost, i;
1453                 struct obd_device *obd;
1454                 char *obdname;
1455                 char *cname;
1456                 char *params;
1457                 char *uuid;
1458
1459                 rc = -EINVAL;
1460                 if (datalen < sizeof(*entry))
1461                         break;
1462
1463                 entry = (typeof(entry))(data + off);
1464
1465                 /* sanity check */
1466                 if (entry->mne_nid_type != 0) /* only support type 0 for ipv4 */
1467                         break;
1468                 if (entry->mne_nid_count == 0) /* at least one nid entry */
1469                         break;
1470                 if (entry->mne_nid_size != sizeof(lnet_nid_t))
1471                         break;
1472
1473                 entry_len += entry->mne_nid_count * entry->mne_nid_size;
1474                 if (datalen < entry_len) /* must have entry_len at least */
1475                         break;
1476
1477                 /* Keep this swab for normal mixed endian handling. LU-1644 */
1478                 if (mne_swab)
1479                         lustre_swab_mgs_nidtbl_entry(entry);
1480                 if (entry->mne_length > PAGE_SIZE) {
1481                         CERROR("MNE too large (%u)\n", entry->mne_length);
1482                         break;
1483                 }
1484
1485                 if (entry->mne_length < entry_len)
1486                         break;
1487
1488                 off     += entry->mne_length;
1489                 datalen -= entry->mne_length;
1490                 if (datalen < 0)
1491                         break;
1492
1493                 if (entry->mne_version > max_version) {
1494                         CERROR("entry index(%lld) is over max_index(%lld)\n",
1495                                entry->mne_version, max_version);
1496                         break;
1497                 }
1498
1499                 if (prev_version >= entry->mne_version) {
1500                         CERROR("index unsorted, prev %lld, now %lld\n",
1501                                prev_version, entry->mne_version);
1502                         break;
1503                 }
1504                 prev_version = entry->mne_version;
1505
1506                 /*
1507                  * Write a string with format "nid::instance" to
1508                  * lustre/<osc|mdc>/<target>-<osc|mdc>-<instance>/import.
1509                  */
1510
1511                 is_ost = entry->mne_type == LDD_F_SV_TYPE_OST;
1512                 memset(buf, 0, bufsz);
1513                 obdname = buf;
1514                 pos = 0;
1515
1516                 /* lustre-OST0001-osc-<instance #> */
1517                 strcpy(obdname, cld->cld_logname);
1518                 cname = strrchr(obdname, '-');
1519                 if (cname == NULL) {
1520                         CERROR("mgc %s: invalid logname %s\n",
1521                                mgc->obd_name, obdname);
1522                         break;
1523                 }
1524
1525                 pos = cname - obdname;
1526                 obdname[pos] = 0;
1527                 pos += sprintf(obdname + pos, "-%s%04x",
1528                                   is_ost ? "OST" : "MDT", entry->mne_index);
1529
1530                 cname = is_ost ? "osc" : "mdc",
1531                 pos += sprintf(obdname + pos, "-%s-%s", cname, inst);
1532                 lustre_cfg_bufs_reset(&bufs, obdname);
1533
1534                 /* find the obd by obdname */
1535                 obd = class_name2obd(obdname);
1536                 if (obd == NULL) {
1537                         CDEBUG(D_INFO, "mgc %s: cannot find obdname %s\n",
1538                                mgc->obd_name, obdname);
1539                         rc = 0;
1540                         /* this is a safe race, when the ost is starting up...*/
1541                         continue;
1542                 }
1543
1544                 /* osc.import = "connection=<Conn UUID>::<target instance>" */
1545                 ++pos;
1546                 params = buf + pos;
1547                 pos += sprintf(params, "%s.import=%s", cname, "connection=");
1548                 uuid = buf + pos;
1549
1550                 down_read(&obd->u.cli.cl_sem);
1551                 if (obd->u.cli.cl_import == NULL) {
1552                         /* client does not connect to the OST yet */
1553                         up_read(&obd->u.cli.cl_sem);
1554                         rc = 0;
1555                         continue;
1556                 }
1557
1558                 /* iterate all nids to find one */
1559                 /* find uuid by nid */
1560                 rc = -ENOENT;
1561                 for (i = 0; i < entry->mne_nid_count; i++) {
1562                         rc = client_import_find_conn(obd->u.cli.cl_import,
1563                                                      entry->u.nids[i],
1564                                                      (struct obd_uuid *)uuid);
1565                         if (rc == 0)
1566                                 break;
1567                 }
1568
1569                 up_read(&obd->u.cli.cl_sem);
1570                 if (rc < 0) {
1571                         CERROR("mgc: cannot find uuid by nid %s\n",
1572                                libcfs_nid2str(entry->u.nids[0]));
1573                         break;
1574                 }
1575
1576                 CDEBUG(D_INFO, "Find uuid %s by nid %s\n",
1577                        uuid, libcfs_nid2str(entry->u.nids[0]));
1578
1579                 pos += strlen(uuid);
1580                 pos += sprintf(buf + pos, "::%u", entry->mne_instance);
1581                 LASSERT(pos < bufsz);
1582
1583                 lustre_cfg_bufs_set_string(&bufs, 1, params);
1584
1585                 OBD_ALLOC(lcfg, lustre_cfg_len(bufs.lcfg_bufcount,
1586                                                bufs.lcfg_buflen));
1587                 if (!lcfg) {
1588                         rc = -ENOMEM;
1589                         break;
1590                 }
1591                 lustre_cfg_init(lcfg, LCFG_PARAM, &bufs);
1592
1593                 CDEBUG(D_INFO, "ir apply logs %lld/%lld for %s -> %s\n",
1594                        prev_version, max_version, obdname, params);
1595
1596                 rc = class_process_config(lcfg);
1597                 OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount,
1598                                               lcfg->lcfg_buflens));
1599                 if (rc)
1600                         CDEBUG(D_INFO, "process config for %s error %d\n",
1601                                obdname, rc);
1602
1603                 /* continue, even one with error */
1604         }
1605
1606         OBD_FREE(inst, PAGE_SIZE);
1607         RETURN(rc);
1608 }
1609
1610 /**
1611  * This function is called if this client was notified for target restarting
1612  * by the MGS. A CONFIG_READ RPC is going to send to fetch recovery or
1613  * nodemap logs.
1614  */
1615 static int mgc_process_recover_nodemap_log(struct obd_device *obd,
1616                                            struct config_llog_data *cld)
1617 {
1618         struct ptlrpc_connection *mgc_conn;
1619         struct ptlrpc_request *req = NULL;
1620         struct config_llog_instance *cfg = &cld->cld_cfg;
1621         struct mgs_config_body *body;
1622         struct mgs_config_res *res;
1623         struct nodemap_config *new_config = NULL;
1624         struct lu_nodemap *recent_nodemap = NULL;
1625         struct ptlrpc_bulk_desc *desc;
1626         struct page **pages = NULL;
1627         __u64 config_read_offset = 0;
1628         __u8 nodemap_cur_pass = 0;
1629         int nrpages = 0;
1630         bool eof = true;
1631         bool mne_swab = false;
1632         int i;
1633         int ealen;
1634         int rc;
1635         ENTRY;
1636
1637         mgc_conn = class_exp2cliimp(cld->cld_mgcexp)->imp_connection;
1638
1639         /* don't need to get local config */
1640         if (cld_is_nodemap(cld) &&
1641             (LNET_NETTYP(LNET_NIDNET(mgc_conn->c_peer.nid)) == LOLND))
1642                 GOTO(out, rc = 0);
1643
1644         /* allocate buffer for bulk transfer.
1645          * if this is the first time for this mgs to read logs,
1646          * CONFIG_READ_NRPAGES_INIT will be used since it will read all logs
1647          * once; otherwise, it only reads increment of logs, this should be
1648          * small and CONFIG_READ_NRPAGES will be used.
1649          */
1650         nrpages = CONFIG_READ_NRPAGES;
1651         if (cfg->cfg_last_idx == 0 || cld_is_nodemap(cld))
1652                 nrpages = CONFIG_READ_NRPAGES_INIT;
1653
1654         OBD_ALLOC(pages, sizeof(*pages) * nrpages);
1655         if (pages == NULL)
1656                 GOTO(out, rc = -ENOMEM);
1657
1658         for (i = 0; i < nrpages; i++) {
1659                 pages[i] = alloc_page(GFP_KERNEL);
1660                 if (pages[i] == NULL)
1661                         GOTO(out, rc = -ENOMEM);
1662         }
1663
1664 again:
1665 #ifdef HAVE_SERVER_SUPPORT
1666         if (cld_is_nodemap(cld) && config_read_offset == 0) {
1667                 new_config = nodemap_config_alloc();
1668                 if (IS_ERR(new_config)) {
1669                         rc = PTR_ERR(new_config);
1670                         new_config = NULL;
1671                         GOTO(out, rc);
1672                 }
1673         }
1674 #endif
1675         LASSERT(cld_is_recover(cld) || cld_is_nodemap(cld));
1676         LASSERT(mutex_is_locked(&cld->cld_lock));
1677         req = ptlrpc_request_alloc(class_exp2cliimp(cld->cld_mgcexp),
1678                                    &RQF_MGS_CONFIG_READ);
1679         if (req == NULL)
1680                 GOTO(out, rc = -ENOMEM);
1681
1682         rc = ptlrpc_request_pack(req, LUSTRE_MGS_VERSION, MGS_CONFIG_READ);
1683         if (rc)
1684                 GOTO(out, rc);
1685
1686         /* pack request */
1687         body = req_capsule_client_get(&req->rq_pill, &RMF_MGS_CONFIG_BODY);
1688         LASSERT(body != NULL);
1689         LASSERT(sizeof(body->mcb_name) > strlen(cld->cld_logname));
1690         if (strlcpy(body->mcb_name, cld->cld_logname, sizeof(body->mcb_name))
1691             >= sizeof(body->mcb_name))
1692                 GOTO(out, rc = -E2BIG);
1693         if (cld_is_nodemap(cld))
1694                 body->mcb_offset = config_read_offset;
1695         else
1696                 body->mcb_offset = cfg->cfg_last_idx + 1;
1697         body->mcb_type   = cld->cld_type;
1698         body->mcb_bits   = PAGE_SHIFT;
1699         body->mcb_units  = nrpages;
1700         body->mcb_nm_cur_pass = nodemap_cur_pass;
1701
1702         /* allocate bulk transfer descriptor */
1703         desc = ptlrpc_prep_bulk_imp(req, nrpages, 1,
1704                                     PTLRPC_BULK_PUT_SINK | PTLRPC_BULK_BUF_KIOV,
1705                                     MGS_BULK_PORTAL,
1706                                     &ptlrpc_bulk_kiov_pin_ops);
1707         if (desc == NULL)
1708                 GOTO(out, rc = -ENOMEM);
1709
1710         for (i = 0; i < nrpages; i++)
1711                 desc->bd_frag_ops->add_kiov_frag(desc, pages[i], 0,
1712                                                  PAGE_SIZE);
1713
1714         ptlrpc_request_set_replen(req);
1715         rc = ptlrpc_queue_wait(req);
1716         if (rc)
1717                 GOTO(out, rc);
1718
1719         res = req_capsule_server_get(&req->rq_pill, &RMF_MGS_CONFIG_RES);
1720         if (!res)
1721                 GOTO(out, rc = -EPROTO);
1722
1723         if (cld_is_nodemap(cld)) {
1724                 config_read_offset = res->mcr_offset;
1725                 eof = config_read_offset == II_END_OFF;
1726                 nodemap_cur_pass = res->mcr_nm_cur_pass;
1727         } else {
1728                 if (res->mcr_size < res->mcr_offset)
1729                         GOTO(out, rc = -EINVAL);
1730
1731                 /* always update the index even though it might have errors with
1732                  * handling the recover logs
1733                  */
1734                 cfg->cfg_last_idx = res->mcr_offset;
1735                 eof = res->mcr_offset == res->mcr_size;
1736
1737                 CDEBUG(D_INFO, "Latest version %lld, more %d.\n",
1738                        res->mcr_offset, eof == false);
1739         }
1740
1741         ealen = sptlrpc_cli_unwrap_bulk_read(req, req->rq_bulk, 0);
1742         if (ealen < 0)
1743                 GOTO(out, rc = ealen);
1744
1745         if (ealen > nrpages << PAGE_SHIFT)
1746                 GOTO(out, rc = -EINVAL);
1747
1748         if (ealen == 0) { /* no logs transferred */
1749 #ifdef HAVE_SERVER_SUPPORT
1750                 /* config changed since first read RPC */
1751                 if (cld_is_nodemap(cld) && config_read_offset == 0) {
1752                         CDEBUG(D_INFO, "nodemap config changed in transit, retrying\n");
1753                         GOTO(out, rc = -EAGAIN);
1754                 }
1755 #endif
1756                 if (!eof)
1757                         rc = -EINVAL;
1758                 GOTO(out, rc);
1759         }
1760
1761         mne_swab = ptlrpc_rep_need_swab(req);
1762
1763         /* When a nodemap config is received, we build a new nodemap config,
1764          * with new nodemap structs. We keep track of the most recently added
1765          * nodemap since the config is read ordered by nodemap_id, and so it
1766          * is likely that the next record will be related. Because access to
1767          * the nodemaps is single threaded until the nodemap_config is active,
1768          * we don't need to reference count with recent_nodemap, though
1769          * recent_nodemap should be set to NULL when the nodemap_config
1770          * is either destroyed or set active.
1771          */
1772         for (i = 0; i < nrpages && ealen > 0; i++) {
1773                 int rc2;
1774                 union lu_page   *ptr;
1775
1776                 ptr = kmap(pages[i]);
1777                 if (cld_is_nodemap(cld))
1778                         rc2 = nodemap_process_idx_pages(new_config, ptr,
1779                                                        &recent_nodemap);
1780                 else
1781                         rc2 = mgc_apply_recover_logs(obd, cld, res->mcr_offset,
1782                                                      ptr,
1783                                                      min_t(int, ealen,
1784                                                            PAGE_SIZE),
1785                                                      mne_swab);
1786                 kunmap(pages[i]);
1787                 if (rc2 < 0) {
1788                         CWARN("%s: error processing %s log %s: rc = %d\n",
1789                               obd->obd_name,
1790                               cld_is_nodemap(cld) ? "nodemap" : "recovery",
1791                               cld->cld_logname,
1792                               rc2);
1793                         GOTO(out, rc = rc2);
1794                 }
1795
1796                 ealen -= PAGE_SIZE;
1797         }
1798
1799 out:
1800         if (req) {
1801                 ptlrpc_req_finished(req);
1802                 req = NULL;
1803         }
1804
1805         if (rc == 0 && !eof)
1806                 goto again;
1807
1808 #ifdef HAVE_SERVER_SUPPORT
1809         if (new_config != NULL) {
1810                 /* recent_nodemap cannot be used after set_active/dealloc */
1811                 if (rc == 0)
1812                         nodemap_config_set_active_mgc(new_config);
1813                 else
1814                         nodemap_config_dealloc(new_config);
1815         }
1816 #endif
1817
1818         if (pages) {
1819                 for (i = 0; i < nrpages; i++) {
1820                         if (pages[i] == NULL)
1821                                 break;
1822                         __free_page(pages[i]);
1823                 }
1824                 OBD_FREE(pages, sizeof(*pages) * nrpages);
1825         }
1826         return rc;
1827 }
1828
1829 static int mgc_barrier_glimpse_ast(struct ldlm_lock *lock, void *data)
1830 {
1831         struct config_llog_data *cld = lock->l_ast_data;
1832         int rc;
1833         ENTRY;
1834
1835         if (cld->cld_stopping)
1836                 RETURN(-ENODEV);
1837
1838         rc = barrier_handler(s2lsi(cld->cld_cfg.cfg_sb)->lsi_dt_dev,
1839                              (struct ptlrpc_request *)data);
1840
1841         RETURN(rc);
1842 }
1843
1844 /* Copy a remote log locally */
1845 static int mgc_llog_local_copy(const struct lu_env *env,
1846                                struct obd_device *obd,
1847                                struct llog_ctxt *rctxt,
1848                                struct llog_ctxt *lctxt, char *logname)
1849 {
1850         char    *temp_log;
1851         int      rc;
1852
1853         ENTRY;
1854
1855         /*
1856          * - copy it to backup using llog_backup()
1857          * - copy remote llog to logname using llog_backup()
1858          * - if failed then move bakup to logname again
1859          */
1860
1861         OBD_ALLOC(temp_log, strlen(logname) + 2);
1862         if (!temp_log)
1863                 RETURN(-ENOMEM);
1864         sprintf(temp_log, "%sT", logname);
1865
1866         /* make a copy of local llog at first */
1867         rc = llog_backup(env, obd, lctxt, lctxt, logname, temp_log);
1868         if (rc < 0 && rc != -ENOENT)
1869                 GOTO(out, rc);
1870         /* copy remote llog to the local copy */
1871         rc = llog_backup(env, obd, rctxt, lctxt, logname, logname);
1872         if (rc == -ENOENT) {
1873                 /* no remote llog, delete local one too */
1874                 llog_erase(env, lctxt, NULL, logname);
1875         } else if (rc < 0) {
1876                 /* error during backup, get local one back from the copy */
1877                 llog_backup(env, obd, lctxt, lctxt, temp_log, logname);
1878 out:
1879                 CERROR("%s: failed to copy remote log %s: rc = %d\n",
1880                        obd->obd_name, logname, rc);
1881         }
1882         llog_erase(env, lctxt, NULL, temp_log);
1883         OBD_FREE(temp_log, strlen(logname) + 2);
1884         return rc;
1885 }
1886
1887 /* local_only means it cannot get remote llogs */
1888 static int mgc_process_cfg_log(struct obd_device *mgc,
1889                                struct config_llog_data *cld, int local_only)
1890 {
1891         struct llog_ctxt        *ctxt, *lctxt = NULL;
1892         struct client_obd       *cli = &mgc->u.cli;
1893         struct lustre_sb_info   *lsi = NULL;
1894         int                      rc = 0;
1895         struct lu_env           *env;
1896
1897         ENTRY;
1898
1899         LASSERT(cld);
1900         LASSERT(mutex_is_locked(&cld->cld_lock));
1901
1902         if (cld->cld_cfg.cfg_sb)
1903                 lsi = s2lsi(cld->cld_cfg.cfg_sb);
1904
1905         OBD_ALLOC_PTR(env);
1906         if (env == NULL)
1907                 RETURN(-ENOMEM);
1908
1909         rc = lu_env_init(env, LCT_MG_THREAD);
1910         if (rc)
1911                 GOTO(out_free, rc);
1912
1913         ctxt = llog_get_context(mgc, LLOG_CONFIG_REPL_CTXT);
1914         LASSERT(ctxt);
1915
1916         lctxt = llog_get_context(mgc, LLOG_CONFIG_ORIG_CTXT);
1917
1918         /* Copy the setup log locally if we can. Don't mess around if we're
1919          * running an MGS though (logs are already local). */
1920         if (lctxt && lsi && IS_SERVER(lsi) && !IS_MGS(lsi) &&
1921             cli->cl_mgc_configs_dir != NULL &&
1922             lu2dt_dev(cli->cl_mgc_configs_dir->do_lu.lo_dev) ==
1923             lsi->lsi_dt_dev) {
1924                 if (!local_only && !lsi->lsi_dt_dev->dd_rdonly)
1925                         /* Only try to copy log if we have the lock. */
1926                         rc = mgc_llog_local_copy(env, mgc, ctxt, lctxt,
1927                                                  cld->cld_logname);
1928                 if (local_only || rc) {
1929                         if (strcmp(cld->cld_logname, PARAMS_FILENAME) != 0 &&
1930                             llog_is_empty(env, lctxt, cld->cld_logname)) {
1931                                 LCONSOLE_ERROR_MSG(0x13a, "Failed to get MGS "
1932                                                    "log %s and no local copy."
1933                                                    "\n", cld->cld_logname);
1934                                 GOTO(out_pop, rc = -ENOENT);
1935                         }
1936                         CDEBUG(D_MGC, "Failed to get MGS log %s, using local "
1937                                "copy for now, will try to update later.\n",
1938                                cld->cld_logname);
1939                         rc = 0;
1940                 }
1941                 /* Now, whether we copied or not, start using the local llog.
1942                  * If we failed to copy, we'll start using whatever the old
1943                  * log has. */
1944                 llog_ctxt_put(ctxt);
1945                 ctxt = lctxt;
1946                 lctxt = NULL;
1947         } else {
1948                 if (local_only) /* no local log at client side */
1949                         GOTO(out_pop, rc = -EIO);
1950         }
1951
1952         rc = -EAGAIN;
1953         if (lsi && IS_SERVER(lsi) && !IS_MGS(lsi) &&
1954             lsi->lsi_dt_dev->dd_rdonly) {
1955                 struct llog_ctxt *rctxt;
1956
1957                 /* Under readonly mode, we may have no local copy or local
1958                  * copy is incomplete, so try to use remote llog firstly. */
1959                 rctxt = llog_get_context(mgc, LLOG_CONFIG_REPL_CTXT);
1960                 LASSERT(rctxt);
1961
1962                 rc = class_config_parse_llog(env, rctxt, cld->cld_logname,
1963                                              &cld->cld_cfg);
1964                 llog_ctxt_put(rctxt);
1965         }
1966
1967         if (rc && rc != -ENOENT)
1968                 rc = class_config_parse_llog(env, ctxt, cld->cld_logname,
1969                                              &cld->cld_cfg);
1970
1971         /*
1972          * update settings on existing OBDs.
1973          * the logname must be <fsname>-sptlrpc
1974          */
1975         if (rc == 0 && cld_is_sptlrpc(cld))
1976                 class_notify_sptlrpc_conf(cld->cld_logname,
1977                                           strlen(cld->cld_logname) -
1978                                           strlen("-sptlrpc"));
1979         EXIT;
1980
1981 out_pop:
1982         __llog_ctxt_put(env, ctxt);
1983         if (lctxt)
1984                 __llog_ctxt_put(env, lctxt);
1985
1986         lu_env_fini(env);
1987 out_free:
1988         OBD_FREE_PTR(env);
1989         return rc;
1990 }
1991
1992 static bool mgc_import_in_recovery(struct obd_import *imp)
1993 {
1994         bool in_recovery = true;
1995
1996         spin_lock(&imp->imp_lock);
1997         if (imp->imp_state == LUSTRE_IMP_FULL ||
1998             imp->imp_state == LUSTRE_IMP_CLOSED)
1999                 in_recovery = false;
2000         spin_unlock(&imp->imp_lock);
2001
2002         return in_recovery;
2003 }
2004
2005 /**
2006  * Get a configuration log from the MGS and process it.
2007  *
2008  * This function is called for both clients and servers to process the
2009  * configuration log from the MGS.  The MGC enqueues a DLM lock on the
2010  * log from the MGS, and if the lock gets revoked the MGC will be notified
2011  * by the lock cancellation callback that the config log has changed,
2012  * and will enqueue another MGS lock on it, and then continue processing
2013  * the new additions to the end of the log.
2014  *
2015  * Since the MGC import is not replayable, if the import is being evicted
2016  * (rcl == -ESHUTDOWN, \see ptlrpc_import_delay_req()), retry to process
2017  * the log until recovery is finished or the import is closed.
2018  *
2019  * Make a local copy of the log before parsing it if appropriate (non-MGS
2020  * server) so that the server can start even when the MGS is down.
2021  *
2022  * There shouldn't be multiple processes running process_log at once --
2023  * sounds like badness.  It actually might be fine, as long as they're not
2024  * trying to update from the same log simultaneously, in which case we
2025  * should use a per-log semaphore instead of cld_lock.
2026  *
2027  * \param[in] mgc       MGC device by which to fetch the configuration log
2028  * \param[in] cld       log processing state (stored in lock callback data)
2029  *
2030  * \retval              0 on success
2031  * \retval              negative errno on failure
2032  */
2033 int mgc_process_log(struct obd_device *mgc, struct config_llog_data *cld)
2034 {
2035         struct lustre_handle lockh = { 0 };
2036         __u64 flags = LDLM_FL_NO_LRU;
2037         int rc = 0, rcl;
2038         bool retry = false;
2039         ENTRY;
2040
2041         LASSERT(cld != NULL);
2042
2043         /* I don't want multiple processes running process_log at once --
2044            sounds like badness.  It actually might be fine, as long as
2045            we're not trying to update from the same log
2046            simultaneously (in which case we should use a per-log sem.) */
2047 restart:
2048         mutex_lock(&cld->cld_lock);
2049         if (cld->cld_stopping) {
2050                 mutex_unlock(&cld->cld_lock);
2051                 RETURN(0);
2052         }
2053
2054         OBD_FAIL_TIMEOUT(OBD_FAIL_MGC_PAUSE_PROCESS_LOG, 20);
2055
2056         CDEBUG(D_MGC, "Process log %s-%016lx from %d\n", cld->cld_logname,
2057                cld->cld_cfg.cfg_instance, cld->cld_cfg.cfg_last_idx + 1);
2058
2059         /* Get the cfg lock on the llog */
2060         rcl = mgc_enqueue(mgc->u.cli.cl_mgc_mgsexp, LDLM_PLAIN, NULL,
2061                           LCK_CR, &flags,
2062                           cld_is_barrier(cld) ? mgc_barrier_glimpse_ast : NULL,
2063                           cld, 0, NULL, &lockh);
2064         if (rcl == 0) {
2065                 /* Get the cld, it will be released in mgc_blocking_ast. */
2066                 config_log_get(cld);
2067                 rc = ldlm_lock_set_data(&lockh, (void *)cld);
2068                 LASSERT(rc == 0);
2069         } else {
2070                 CDEBUG(D_MGC, "Can't get cfg lock: %d\n", rcl);
2071
2072                 if (rcl == -ESHUTDOWN &&
2073                     atomic_read(&mgc->u.cli.cl_mgc_refcount) > 0 && !retry) {
2074                         struct obd_import *imp;
2075                         struct l_wait_info lwi;
2076                         int secs = cfs_time_seconds(obd_timeout);
2077
2078                         mutex_unlock(&cld->cld_lock);
2079                         imp = class_exp2cliimp(mgc->u.cli.cl_mgc_mgsexp);
2080
2081                         /* Let's force the pinger, and wait the import to be
2082                          * connected, note: since mgc import is non-replayable,
2083                          * and even the import state is disconnected, it does
2084                          * not mean the "recovery" is stopped, so we will keep
2085                          * waitting until timeout or the import state is
2086                          * FULL or closed */
2087                         ptlrpc_pinger_force(imp);
2088
2089                         lwi = LWI_TIMEOUT(secs, NULL, NULL);
2090                         l_wait_event(imp->imp_recovery_waitq,
2091                                      !mgc_import_in_recovery(imp), &lwi);
2092
2093                         if (imp->imp_state == LUSTRE_IMP_FULL) {
2094                                 retry = true;
2095                                 goto restart;
2096                         } else {
2097                                 mutex_lock(&cld->cld_lock);
2098                                 /* unlock/lock mutex, so check stopping again */
2099                                 if (cld->cld_stopping) {
2100                                         mutex_unlock(&cld->cld_lock);
2101                                         RETURN(0);
2102                                 }
2103                                 spin_lock(&config_list_lock);
2104                                 cld->cld_lostlock = 1;
2105                                 spin_unlock(&config_list_lock);
2106                         }
2107                 } else {
2108                         /* mark cld_lostlock so that it will requeue
2109                          * after MGC becomes available. */
2110                         spin_lock(&config_list_lock);
2111                         cld->cld_lostlock = 1;
2112                         spin_unlock(&config_list_lock);
2113                 }
2114         }
2115
2116         if (cld_is_recover(cld) || cld_is_nodemap(cld)) {
2117                 if (!rcl)
2118                         rc = mgc_process_recover_nodemap_log(mgc, cld);
2119                 else if (cld_is_nodemap(cld))
2120                         rc = rcl;
2121
2122                 if (cld_is_recover(cld) && rc) {
2123                         if (!rcl) {
2124                                 CERROR("%s: recover log %s failed, not fatal: rc = %d\n",
2125                                        mgc->obd_name, cld->cld_logname, rc);
2126                                 spin_lock(&config_list_lock);
2127                                 cld->cld_lostlock = 1;
2128                                 spin_unlock(&config_list_lock);
2129                         }
2130                         rc = 0; /* this is not a fatal error for recover log */
2131                 }
2132         } else if (!cld_is_barrier(cld)) {
2133                 rc = mgc_process_cfg_log(mgc, cld, rcl != 0);
2134         }
2135
2136         CDEBUG(D_MGC, "%s: configuration from log '%s' %sed (%d).\n",
2137                mgc->obd_name, cld->cld_logname, rc ? "fail" : "succeed", rc);
2138
2139         mutex_unlock(&cld->cld_lock);
2140
2141         /* Now drop the lock so MGS can revoke it */
2142         if (!rcl) {
2143                 rcl = mgc_cancel(mgc->u.cli.cl_mgc_mgsexp, LCK_CR, &lockh);
2144                 if (rcl)
2145                         CERROR("Can't drop cfg lock: %d\n", rcl);
2146         }
2147
2148         /* requeue nodemap lock immediately if transfer was interrupted */
2149         if (cld_is_nodemap(cld) && rc == -EAGAIN) {
2150                 mgc_requeue_add(cld);
2151                 rc = 0;
2152         }
2153
2154         RETURN(rc);
2155 }
2156
2157
2158 /** Called from lustre_process_log.
2159  * LCFG_LOG_START gets the config log from the MGS, processes it to start
2160  * any services, and adds it to the list logs to watch (follow).
2161  */
2162 static int mgc_process_config(struct obd_device *obd, size_t len, void *buf)
2163 {
2164         struct lustre_cfg *lcfg = buf;
2165         struct config_llog_instance *cfg = NULL;
2166         char *logname;
2167         int rc = 0;
2168         ENTRY;
2169
2170         switch(lcfg->lcfg_command) {
2171         case LCFG_LOV_ADD_OBD: {
2172                 /* Overloading this cfg command: register a new target */
2173                 struct mgs_target_info *mti;
2174
2175                 if (LUSTRE_CFG_BUFLEN(lcfg, 1) !=
2176                     sizeof(struct mgs_target_info))
2177                         GOTO(out, rc = -EINVAL);
2178
2179                 mti = (struct mgs_target_info *)lustre_cfg_buf(lcfg, 1);
2180                 CDEBUG(D_MGC, "add_target %s %#x\n",
2181                        mti->mti_svname, mti->mti_flags);
2182                 rc = mgc_target_register(obd->u.cli.cl_mgc_mgsexp, mti);
2183                 break;
2184         }
2185         case LCFG_LOV_DEL_OBD:
2186                 /* Unregister has no meaning at the moment. */
2187                 CERROR("lov_del_obd unimplemented\n");
2188                 rc = -ENOSYS;
2189                 break;
2190         case LCFG_SPTLRPC_CONF: {
2191                 rc = sptlrpc_process_config(lcfg);
2192                 break;
2193         }
2194         case LCFG_LOG_START: {
2195                 struct config_llog_data *cld;
2196                 struct super_block *sb;
2197
2198                 logname = lustre_cfg_string(lcfg, 1);
2199                 cfg = (struct config_llog_instance *)lustre_cfg_buf(lcfg, 2);
2200                 sb = *(struct super_block **)lustre_cfg_buf(lcfg, 3);
2201
2202                 CDEBUG(D_MGC, "parse_log %s from %d\n", logname,
2203                        cfg->cfg_last_idx);
2204
2205                 /* We're only called through here on the initial mount */
2206                 cld = config_log_add(obd, logname, cfg, sb);
2207                 if (IS_ERR(cld)) {
2208                         rc = PTR_ERR(cld);
2209                         break;
2210                 }
2211
2212                 rc = mgc_process_log(obd, cld);
2213                 if (rc == 0 && cld->cld_recover != NULL) {
2214                         if (OCD_HAS_FLAG(&obd->u.cli.cl_import->
2215                                          imp_connect_data, IMP_RECOV)) {
2216                                 rc = mgc_process_log(obd, cld->cld_recover);
2217                         } else {
2218                                 struct config_llog_data *cir;
2219
2220                                 mutex_lock(&cld->cld_lock);
2221                                 cir = cld->cld_recover;
2222                                 cld->cld_recover = NULL;
2223                                 mutex_unlock(&cld->cld_lock);
2224                                 config_log_put(cir);
2225                         }
2226
2227                         if (rc)
2228                                 CERROR("Cannot process recover llog %d\n", rc);
2229                 }
2230
2231                 if (rc == 0 && cld->cld_params != NULL) {
2232                         rc = mgc_process_log(obd, cld->cld_params);
2233                         if (rc == -ENOENT) {
2234                                 CDEBUG(D_MGC, "There is no params "
2235                                               "config file yet\n");
2236                                 rc = 0;
2237                         }
2238                         /* params log is optional */
2239                         if (rc)
2240                                 CERROR("%s: can't process params llog: rc = %d\n",
2241                                        obd->obd_name, rc);
2242                 }
2243
2244                 break;
2245         }
2246         case LCFG_LOG_END: {
2247                 logname = lustre_cfg_string(lcfg, 1);
2248
2249                 if (lcfg->lcfg_bufcount >= 2)
2250                         cfg = (struct config_llog_instance *)lustre_cfg_buf(
2251                                 lcfg, 2);
2252                 rc = config_log_end(logname, cfg);
2253                 break;
2254         }
2255         default: {
2256                 CERROR("Unknown command: %d\n", lcfg->lcfg_command);
2257                 GOTO(out, rc = -EINVAL);
2258
2259         }
2260         }
2261 out:
2262         RETURN(rc);
2263 }
2264
2265 static struct obd_ops mgc_obd_ops = {
2266         .o_owner        = THIS_MODULE,
2267         .o_setup        = mgc_setup,
2268         .o_precleanup   = mgc_precleanup,
2269         .o_cleanup      = mgc_cleanup,
2270         .o_add_conn     = client_import_add_conn,
2271         .o_del_conn     = client_import_del_conn,
2272         .o_connect      = client_connect_import,
2273         .o_disconnect   = client_disconnect_export,
2274         .o_set_info_async = mgc_set_info_async,
2275         .o_get_info       = mgc_get_info,
2276         .o_import_event = mgc_import_event,
2277         .o_process_config = mgc_process_config,
2278 };
2279
2280 static int __init mgc_init(void)
2281 {
2282         return class_register_type(&mgc_obd_ops, NULL, false, NULL,
2283                                    LUSTRE_MGC_NAME, NULL);
2284 }
2285
2286 static void __exit mgc_exit(void)
2287 {
2288         class_unregister_type(LUSTRE_MGC_NAME);
2289 }
2290
2291 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
2292 MODULE_DESCRIPTION("Lustre Management Client");
2293 MODULE_VERSION(LUSTRE_VERSION_STRING);
2294 MODULE_LICENSE("GPL");
2295
2296 module_init(mgc_init);
2297 module_exit(mgc_exit);