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