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