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