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