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