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