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