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