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